rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
class record(nt.void): def _finalize(self, descr): self.fields = descr.fields
class record(nt.void):
def _createdescr(self): self._descr = sb.dtypedescr({'names':self._names, 'formats':self._f_formats, 'offsets':self._offsets, 'titles':self._titles } )
return "A record with fields", self.fields
return "A record with fields: %s" % (','.join(self.fields.keys()),)
def __repr__(self): return "A record with fields", self.fields
def __getattribute___(self, attr):
def __getattribute__(self, attr): if attr in ['setfield', 'getfield', 'fields']: return nt.void.__getattribute__(self, attr) fielddict = nt.void.__getattribute__(self, 'fields') res = fielddict.get(attr,None) if res: return self.getfield(*res[:2]) return nt.void.__getattribute__(self, attr) def __setattr__(self, attr,...
def __getattribute___(self, attr): fielddict = nt.void.__getattribute__(self,'fields') try: res = fielddict[attr][:2] except: return nt.void.__getattribute__(self, attr) return self.getfield(*res)
try: res = fielddict[attr][:2] except: return nt.void.__getattribute__(self, attr) return self.getfield(*res) def __setattr__(self, attr, val): fielddict = nt.void.__getattribute__(self,'fields') try: res = fielddict[attr][:2] except: return nt.void.__setattr__(self,attr,val) return self.setfield(val,*res)
res = fielddict.get(attr,None) if res: return self.setfield(val,*res[:2]) return nt.void.__setattr__(self,attr,val)
def __getattribute___(self, attr): fielddict = nt.void.__getattribute__(self,'fields') try: res = fielddict[attr][:2] except: return nt.void.__getattribute__(self, attr) return self.getfield(*res)
self.getfield(*(self.fields[obj][:2]))
return self.getfield(*(self.fields[obj][:2]))
def __getitem__(self, obj): self.getfield(*(self.fields[obj][:2]))
self.setfield(*(self.fields[obj][:2]))
return self.setfield(*(self.fields[obj][:2]))
def __setitem__(self, obj, val): self.setfield(*(self.fields[obj][:2]))
if isinstance(formats,string):
if isinstance(formats,str):
def __new__(subtype, shape, formats, names=None, titles=None, buf=None, offset=0, strides=None, swap=0, aligned=0):
print "warning: specified temp_dir '%s' does not exist or is " \
print "warning: specified temp_dir '%s' does not exist " \
def configure_temp_dir(temp_dir=None): if temp_dir is None: temp_dir = tempfile.gettempdir() elif not os.path.exists(temp_dir) or not os.access(temp_dir,os.W_OK): print "warning: specified temp_dir '%s' does not exist or is " \ "or is not writable. Using the default temp directory" % \ temp_dir temp_dir = tempfile.gett...
print "warning: specified build_dir '%s' does not exist or is " \
print "warning: specified build_dir '%s' does not exist " \
def configure_build_dir(build_dir=None): # make sure build_dir exists and is writable if build_dir and (not os.path.exists(build_dir) or not os.access(build_dir,os.W_OK)): print "warning: specified build_dir '%s' does not exist or is " \ "or is not writable. Trying default locations" % build_dir build_dir = None if bu...
\t\tif (arr->descr->elsize==sizeof(char)) { \t\t\tif (*len == -1) \t\t\t\t*len = (arr->descr->elsize)*PyArray_SIZE(arr); \t\t\tSTRINGMALLOC(*str,*len); \t\t\tSTRINGCOPYN(*str,arr->data,*len); \t\t\treturn 1; \t\t} \t\tPyErr_SetString(PyExc_ValueError,\"array object element size is not 1.\"); \t\tgoto capi_fail;
\t\tif (*len == -1) \t\t\t*len = (arr->itemsize)*PyArray_SIZE(arr); \t\tSTRINGMALLOC(*str,*len); \t\tSTRINGCOPYN(*str,arr->data,*len); \t\treturn 1;
#ifdef DEBUGCFUNCS
class test_properties(ScipyTestCase):
class test_properties(NumpyTestCase):
def check_basic(self): A = array([[1,2],[3,4]]) mA = matrix(A) assert all(mA.A == A)
class test_casting(ScipyTestCase):
class test_casting(NumpyTestCase):
def check_noaxis(self): A = matrix([[1,0],[0,1]]) assert A.sum() == matrix(2) assert A.mean() == matrix(0.5)
class test_algebra(ScipyTestCase):
class test_algebra(NumpyTestCase):
def check_basic(self): A = arange(100).reshape(10,10) mA = matrix(A)
class test_matrix_return(ScipyTestCase):
class test_matrix_return(NumpyTestCase):
def check_basic(self): import numpy.linalg as linalg
ScipyTest().run()
NumpyTest().run()
def check_instance_methods(self): a = matrix([1.0], dtype='f8') methodargs = { 'astype' : ('intc',), 'clip' : (0.0, 1.0), 'compress' : ([1],), 'repeat' : (1,), 'reshape' : (1,), 'swapaxes' : (0,0) } excluded_methods = [ 'argmin', 'choose', 'dump', 'dumps', 'fill', 'getfield', 'getA', 'item', 'nonzero', 'put', 'putmask'...
for typ in [subroutine_exp, function_exp]: ind = 0 while 1: a = typ.search(astr[ind:]) if a is None: break tup = a.span() tup = (ind+tup[0],ind+tup[1]) spanlist.append(tup) ind = tup[1]
ind = 0 while 1: start = astr.find("subroutine", ind) if start == -1: break fini1 = astr.find("end subroutine",start) fini2 = astr.find("\n",fini1) spanlist.append((start, fini2)) ind = fini2 ind = 0 while 1: start = astr.find("function", ind) if start == -1: break pre = astr.rfind("\n", ind, start) presave = start ...
def parse_structure(astr): spanlist = [] for typ in [subroutine_exp, function_exp]: ind = 0 while 1: a = typ.search(astr[ind:]) if a is None: break tup = a.span() tup = (ind+tup[0],ind+tup[1]) spanlist.append(tup) ind = tup[1] spanlist.sort() return spanlist
thelist,num = conv(rep[1])
thelist = conv(rep[1])
def expand_sub(substr,extra=''): global _names, _thissub # find all named replacements reps = named_re.findall(substr) _names = {} _names.update(_special_names) numsubs = None for rep in reps: name = rep[0].strip().lower() thelist,num = conv(rep[1]) _names[name] = thelist substr = named_re.sub(r"<\1>",substr) # get r...
return d
return d or '.'
def get_path(mod_name,parent_path=None): """ This function makes sure installation is done from the correct directory no matter if it is installed from the command line or from another package or run_setup function. """ if mod_name == '__main__': d = os.path.abspath('.') elif mod_name == '__builtin__': #builtin if/the...
import init
def parse(self): import init try: main = BeginSource(self) return main except KeyboardInterrupt: raise except: reader = self.reader while reader is not None: message = reader.format_message('FATAL ERROR', 'while processing line', reader.linecount, reader.linecount) reader.show_message(message, sys.stdout) reader = read...
return self.setfield(*(self.fields[obj][:2]))
return self.setfield(val, *(self.fields[obj][:2]))
def __setitem__(self, obj, val): return self.setfield(*(self.fields[obj][:2]))
names=None, titles=None, aligned=0, byteorder=None):
names=None, titles=None, aligned=False, byteorder=None):
def fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=0, byteorder=None): """ create a record array from a (flat) list of arrays >>> x1=array([1,2,3,4]) >>> x2=array(['a','dd','xyz','12']) >>> x3=array([1.1,2,3,4]) >>> r=fromarrays([x1,x2,x3],names='a,b,c') >>> print r[1] (2,...
titles=None, aligned=0, byteorder=None):
titles=None, aligned=False, byteorder=None):
def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=0, byteorder=None): """ create a recarray from a list of records in text form The data in the same field can be heterogeneous, they will be promoted to the highest data type. This method is intended for creating smaller re...
names=None, titles=None, byteorder=None, aligned=0):
names=None, titles=None, aligned=False, byteorder=None):
def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, byteorder=None, aligned=0): """ create a (read-only) record array from binary data contained in a string""" if dtype is None and formats is None: raise ValueError, "Must have dtype= or formats=" if dtype is not None: ...
names=None, titles=None, byteorder=None, aligned=0):
names=None, titles=None, aligned=False, byteorder=None):
def fromfile(fd, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, byteorder=None, aligned=0): """Create an array from binary file data If file is a string then that file is opened, else it is assumed to be a file object. >>> import testdata, sys >>> fd=open(testdata.filename) >>> fd.seek(2880*...
if os.environ.has_key(self.dir_env_var):
if self.dir_env_var and os.environ.has_key(self.dir_env_var):
def get_paths(self, section, key): dirs = self.cp.get(section, key).split(os.pathsep) if os.environ.has_key(self.dir_env_var): dirs = os.environ[self.dir_env_var].split(os.pathsep) + dirs default_dirs = self.cp.get('DEFAULT', key).split(os.pathsep) dirs.extend(default_dirs) ret = [] [ret.append(d) for d in dirs if os.p...
for d in default_include_dirs: d = os.path.join(d, os.path.basename(py_incl_dir)) if d not in include_dirs: include_dirs.append(d)
if os.name=='posix': for d in default_include_dirs: d = os.path.join(d, os.path.basename(py_incl_dir)) if d not in include_dirs: include_dirs.append(d)
def __init__(self): from distutils.sysconfig import get_python_inc py_incl_dir = get_python_inc() include_dirs = [py_incl_dir] for d in default_include_dirs: d = os.path.join(d, os.path.basename(py_incl_dir)) if d not in include_dirs: include_dirs.append(d) system_info.__init__(self, default_lib_dirs=[], default_includ...
print numpy_info().get_info() print numarray_info().get_info()
def show_all(): import system_info import pprint match_info = re.compile(r'.*?_info').match for n in filter(match_info,dir(system_info)): if n in ['system_info','get_info']: continue c = getattr(system_info,n)() c.verbosity = 2 r = c.get_info()
return self.ufunc(*args).astype(self.otypes[0])
ret = self.ufunc(*args) c = self.otypes[0] try: return ret.astype(c) except AttributeError: return array(ret).astype(c)
def __call__(self, *args): # get number of outputs and output types by calling # the function on the first entries of args nargs = len(args) if (nargs > self.nin) or (nargs < self.nin_wo_defaults): raise ValueError, "mismatch between python function inputs"\ " and received arguments" if self.nout is None or self.otype...
return tuple([x.astype(c) for x, c in zip(self.ufunc(*args), self.otypes)])
ret = [] for x, c in zip(self.ufunc(*args), self.otypes): try: ret.append(x.astype(c)) except AttributeError: ret.append(array(x).astype(c)) return tuple(ret)
def __call__(self, *args): # get number of outputs and output types by calling # the function on the first entries of args nargs = len(args) if (nargs > self.nin) or (nargs < self.nin_wo_defaults): raise ValueError, "mismatch between python function inputs"\ " and received arguments" if self.nout is None or self.otype...
map(set.__setitem__, inseq, [])
for item in inseq: set[item] = None
def unique(inseq): """Returns unique items in 1-dimensional sequence. """ set = {} map(set.__setitem__, inseq, []) return asarray(set.keys())
from scipy.lib._dotblas import dot, vdot, inner, alterdot, restoredot
from _dotblas import dot, vdot, inner, alterdot, restoredot
def vdot(a, b): """Returns the dot product of 2 vectors (or anything that can be made into a vector). NB: this is not the same as `dot`, as it takes the conjugate of its first argument if complex and always returns a scalar.""" return dot(asarray(a).ravel().conj(), asarray(b).ravel())
self.build_src = os.path.join(self.build_base, 'src')
plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) self.build_src = os.path.join(self.build_base, 'src'+plat_specifier)
def finalize_options(self): self.set_undefined_options('build', ('build_base', 'build_base'), ('build_lib', 'build_lib'), ('force', 'force')) if self.package is None: self.package = self.distribution.ext_package self.extensions = self.distribution.ext_modules self.libraries = self.distribution.libraries or [] self.py_m...
return self.getfield(*(self.dtype.fields[obj][:2]))
myf = self.dtype.fields if isinstance(obj, int): obj = myf[-1][obj] return self.getfield(*(myf[obj][:2]))
def __getitem__(self, obj): return self.getfield(*(self.dtype.fields[obj][:2]))
return self.setfield(val, *(self.dtype.fields[obj][:2]))
myf = self.dtype.fields if isinstance(obj, int): obj = myf[-1][obj] return self.setfield(val, *(myf[obj][:2]))
def __setitem__(self, obj, val): return self.setfield(val, *(self.dtype.fields[obj][:2]))
if exe[0]=='"': exe = exe[1:-1]
def find_executable(exe, path=None): """ Return full path of a executable. """ log.debug('find_executable(%r)' % exe) if path is None: path = os.environ.get('PATH',os.defpath) if os.name=='posix': realpath = os.path.realpath else: realpath = lambda a:a suffices = [''] if os.name in ['nt','dos','os2']: fn,ext = os.path...
st = _exec_command(command, use_shell=use_shell, **env)
st = _exec_command(command, use_shell=use_shell, use_tee=use_tee,**env)
def exec_command( command, execute_in='', use_shell=None, use_tee = None, _with_python = 1, **env ): """ Return (status,output) of executed command. command is a concatenated string of executable and arguments. The output contains both stdout and stderr messages. The following special keyword arguments can be used: us...
def _exec_command( command, use_shell=None, **env ):
def _exec_command( command, use_shell=None, use_tee = None, **env ):
def _exec_command( command, use_shell=None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' using_command = 0 if use_shell: # We use shell (unless use_shell==0) so that wildcards can be # used. sh = os.environ.get('SHELL','/bin/sh') if type(command) is type([]): argv = [sh,...
if using_command:
if 0 and using_command:
def _exec_command( command, use_shell=None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' using_command = 0 if use_shell: # We use shell (unless use_shell==0) so that wildcards can be # used. sh = os.environ.get('SHELL','/bin/sh') if type(command) is type([]): argv = [sh,...
text = '%sCOMMAND %r FAILED: %s' %(text,command,errmess)
text = text + errmess print errmess
def _exec_command( command, use_shell=None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' using_command = 0 if use_shell: # We use shell (unless use_shell==0) so that wildcards can be # used. sh = os.environ.get('SHELL','/bin/sh') if type(command) is type([]): argv = [sh,...
def test_svn(): s,o = exec_command(['svn','status'])
def test_svn(**kws): s,o = exec_command(['svn','status'],**kws)
def test_svn(): s,o = exec_command(['svn','status']) assert s,(s,o)
test_svn()
test_svn(use_tee=1) test_cl(use_tee=1)
def test_svn(): s,o = exec_command(['svn','status']) assert s,(s,o)
'int* _D%(name)s = %(name)s->nd;\n' \ '%(type)s* %(name)s_data = %(name)s->data;\n'
'int _D%(name)s = %(name)s->nd;\n' \ '%(type)s* %(name)s_data = (%(type)s*) %(name)s->data;\n'
def standard_decl_code(self): type = numeric_to_blitz_type_mapping[self.numeric_type] name = self.name templ = '// %(name)s array declaration\n' \ 'PyArrayObject* %(name)s = py_to_numpy(py_%(name)s,"%(name)s");\n' \ 'int* _N%(name)s = %(name)s->dimensions;\n' \ 'int* _S%(name)s = %(name)s->strides;\n' \ 'int* _D%(name)...
from scipy.lib._dotblas import dot, vdot, inner, alterdot, restoredot
from scipy.basic._dotblas import dot, vdot, inner, alterdot, restoredot
def vdot(a, b): """Returns the dot product of 2 vectors (or anything that can be made into a vector). NB: this is not the same as `dot`, as it takes the conjugate of its first argument if complex and always returns a scalar.""" return dot(asarray(a).ravel().conj(), asarray(b).ravel())
totlist |= condlist
totlist |= condlist[k]
def piecewise(x, condlist, funclist, *args, **kw): """Return a piecewise-defined function. x is the domain condlist is a list of boolean arrays or a single boolean array The length of the condition list must be n2 or n2-1 where n2 is the length of the function list. If len(condlist)==n2-1, then an 'otherwise' condit...
typename = "'%s'" % str(arr.dtype)
if arr.dtype.names: typename = "%s" % str(arr.dtype) else: typename = "'%s'" % str(arr.dtype)
def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): if arr.size > 0 or arr.shape==(0,): lst = array2string(arr, max_line_width, precision, suppress_small, ', ', "array(") else: # show zero-length shape unless it is (0,) lst = "[], shape=%s" % (repr(arr.shape),) typeless = arr.dtype.type in _t...
_summaryThreshhold = 1000
_summaryThreshold = 1000
def _numeric_compress(arr): nonzero = 0 for i in xrange(arr.nelements()): if arr[i] != 0: nonzero += 1 retarr = _nc.zeros((nonzero,)) nonzero = 0 for i in xrange(arr.nelements()): if arr[i] != 0: retarr[nonzero] = abs(arr[i]) nonzero += 1 return retarr
global _summaryThreshhold, _summaryEdgeItems, _float_output_precision, \
global _summaryThreshold, _summaryEdgeItems, _float_output_precision, \
def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None): """Set options associated with printing. precision the default number of digits of precision for floating point output (default 8) threshold total number of array elements which trigger summarization rather than full...
_summaryThreshhold = threshold
_summaryThreshold = threshold
def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None): """Set options associated with printing. precision the default number of digits of precision for floating point output (default 8) threshold total number of array elements which trigger summarization rather than full...
return _float_output_precision, _summaryThreshhold, _summaryEdgeItems, \
return _float_output_precision, _summaryThreshold, _summaryEdgeItems, \
def get_printoptions(): return _float_output_precision, _summaryThreshhold, _summaryEdgeItems, \ _line_width, _float_output_suppress_small
if a.size > _summaryThreshhold:
if a.size > _summaryThreshold:
def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix=""): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if a.size > _summaryThreshhold: summar...
test, errstr = result.errors[-1]
test, errstr = result.errors[-1][:2]
def __call__(self, result=None): if result is None: return unittest.TestCase.__call__(self, result)
if os.environ.get('TERM',None) in ['rxvt','xterm']: def red_text(s): return '\x1b[31m%s\x1b[0m'%s def green_text(s): return '\x1b[32m%s\x1b[0m'%s def yellow_text(s): return '\x1b[33m%s\x1b[0m'%s def blue_text(s): return '\x1b[34m%s\x1b[0m'%s def cyan_text(s): return '\x1b[35m%s\x1b[0m'%s else: def red_text(s): return ...
def run_command(command): """ not sure how to get exit status on nt. """ in_pipe,out_pipe = os.popen4(command) in_pipe.close() text = out_pipe.read() return 0, text
print compiler
print cyan_text(compiler)
def show_compilers(): for compiler_class in all_compilers: compiler = compiler_class() if compiler.is_available(): print compiler
self.announce(' using %s Fortran compiler' % fc)
self.announce(cyan_text(' using %s Fortran compiler' % fc))
def finalize_options (self): self.set_undefined_options('build', ('build_temp', 'build_flib'), ('build_temp', 'build_temp'), ('debug', 'debug'), ('force', 'force')) fc = find_fortran_compiler(self.fcompiler, self.fcompiler_exec, self.f90compiler_exec) if not fc: raise DistutilsOptionError, 'Fortran compiler not availab...
print cmd
print yellow_text(cmd)
def f_compile(self,compiler,switches, source_files, module_dirs=None, temp_dir=''):
print cmd
print yellow_text(cmd)
def create_static_lib(self, object_files, library_name, output_dir='', debug=None): lib_file = os.path.join(output_dir,'lib'+library_name+'.a') newer = distutils.dep_util.newer # This doesn't work -- no way to know if the file is in the archive #object_files = filter(lambda o,lib=lib_file:\ # distutils....
print 'command:', self.ver_cmd
print 'command:', yellow_text(self.ver_cmd)
def get_version(self): """Return the compiler version. If compiler is not available, return empty string.""" # XXX: Is there compilers that have no version? If yes, # this test will fail even if the compiler is available. if self.version is not None: # Finding version is expensive, so return previously found # ver...
print exit_status, out_text
print exit_status,
def get_version(self): """Return the compiler version. If compiler is not available, return empty string.""" # XXX: Is there compilers that have no version? If yes, # this test will fail even if the compiler is available. if self.version is not None: # Finding version is expensive, so return previously found # ver...
if 'FORTRAN' in requirements or 'F' in requirements:
if 'FORTRAN' in requirements or \ 'F_CONTIGUOUS' in requirements or \ 'F' in requirements:
def require(a, dtype=None, requirements=None): if requirements is None: requirements = [] else: requirements = [x.upper() for x in requirements] if not requirements: return asanyarray(a, dtype=dtype) if 'ENSUREARRAY' in requirements or 'E' in requirements: subok = 0 else: subok = 1 arr = array(a, dtype=dtype, copy=F...
elif 'CONTIGUOUS' in requirements or 'C' in requirements:
elif 'CONTIGUOUS' in requirements or \ 'C_CONTIGUOUS' in requirements or \ 'C' in requirements:
def require(a, dtype=None, requirements=None): if requirements is None: requirements = [] else: requirements = [x.upper() for x in requirements] if not requirements: return asanyarray(a, dtype=dtype) if 'ENSUREARRAY' in requirements or 'E' in requirements: subok = 0 else: subok = 1 arr = array(a, dtype=dtype, copy=F...
"""Returns True if 'a' is laid out in Fortran-order in memory (and a.ndim > 1)
"""Returns True if 'a' is arranged in Fortran-order in memory with a.ndim > 1
def isfortran(a): """Returns True if 'a' is laid out in Fortran-order in memory (and a.ndim > 1) """ return a.flags.fnc
f2py_opts.append('--'+i)
f2py_options.append('--'+i)
def f2py_sources (self, sources, ext):
while 1:
for _ in max_iter:
def __init__(self, float_conv=float,int_conv=int, float_to_float=float, float_to_str = lambda v:'%24.16e' % v, title = 'Python floating point number'): """ float_conv - convert integer to float (array) int_conv - convert float (array) to integer float_to_float - convert float array to float float_to_str - convert arr...
Compute average over the given axis. If axis is None, average over all dimensions of the array. Equivalent to a.mean(axis), but with a default axis of 0 instead of None. The average of an integer or floating-point array always has type Float. If an integer axis is given, this equals: a.sum(axis) * 1.0 / len(a) If ...
Average the array over the given axis. If the axis is None, average over all dimensions of the array. Equivalent to a.mean(axis), but with a default axis of 0 instead of None. If an integer axis is given, this equals: a.sum(axis) * 1.0 / len(a) If axis is None, this equals: a.sum(axis) * 1.0 / product(a.shape) If ...
def average(a, axis=0, weights=None, returned=False): """average(a, axis=0, weights=None, returned=False) Compute average over the given axis. If axis is None, average over all dimensions of the array. Equivalent to a.mean(axis), but with a default axis of 0 instead of None. The average of an integer or floating-po...
exec code in locs,globs
exec code in globs,locs
def measure(self,code_str,times=1): """ Return elapsed time for executing code_str in the namespace of the caller for given times. """ frame = sys._getframe(1) locs,globs = frame.f_locals,frame.f_globals code = compile(code_str, 'ScipyTestCase runner for '+self.__class__.__name__, 'exec') i = 0 elapsed = jiffies() whil...
' items (call build_src before built_ext).' % (ext.name)
' items (call build_src before build_ext).' % (ext.name)
def run(self): if not self.extensions: return
def default_config_dict(name = None, parent_name = None):
def default_config_dict(name = None, parent_name = None, local_path=None):
def default_config_dict(name = None, parent_name = None): """ Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py. """ d={} for key in list_keys: d[key] = [] for key in dict_keys: d[key] = {} full_name = dot_join(parent_name,name) if full_name: # XXX: The following ...
frame = get_frame(1) caller_name = eval('__name__',frame.f_globals,frame.f_locals) local_path = get_path(caller_name)
if local_path is None: frame = get_frame(1) caller_name = eval('__name__',frame.f_globals,frame.f_locals) local_path = get_path(caller_name)
def default_config_dict(name = None, parent_name = None): """ Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py. """ d={} for key in list_keys: d[key] = [] for key in dict_keys: d[key] = {} full_name = dot_join(parent_name,name) if full_name: # XXX: The following ...
config = default_config_dict(package_name, parent or '')
config = default_config_dict(package_name, parent or '', local_path=dirname)
def get_subpackages(path, parent=None, parent_path=None, include_packages=[], ignore_packages=[]): """ Return a list of configurations found in a tree of Python packages. It is assumed that each package xxx in path/xxx has file path/xxx/info_xxx.py that follows convention specified in scipy/DEVELOPERS.txt. Packages ...
return re.match(r'.*?Pentium II\b',
return re.match(r'.*?Pentium.*?II\b',
def _is_PentiumII(self): return re.match(r'.*?Pentium II\b', self.info[0]['model name']) is not None
return re.match(r'.*?PentiumMMX\b',
return re.match(r'.*?Pentium.*?MMX\b',
def _is_PentiumMMX(self): return re.match(r'.*?PentiumMMX\b', self.info[0]['model name']) is not None
return re.match(r'.*?Pentium III\b',
return re.match(r'.*?Pentium.*?III\b',
def _is_PentiumIII(self): return re.match(r'.*?Pentium III\b', self.info[0]['model name']) is not None
return re.match(r'.*?Pentium (IV|4)\b',
return re.match(r'.*?Pentium.*?(IV|4)\b',
def _is_PentiumIV(self): return re.match(r'.*?Pentium (IV|4)\b', self.info[0]['model name']) is not None
assert_equal(amax(b),[8.0,10.0,9.0])
assert_equal(amax(b,axis=0),[8.0,10.0,9.0])
def check_basic(self): a = [3,4,5,10,-3,-5,6.0] assert_equal(amax(a),10.0) b = [[3,6.0, 9.0], [4,10.0,5.0], [8,3.0,2.0]] assert_equal(amax(b),[8.0,10.0,9.0]) assert_equal(amax(b,axis=1),[9.0,10.0,8.0])
assert_equal(amin(b),[3.0,3.0,2.0])
assert_equal(amin(b,axis=0),[3.0,3.0,2.0])
def check_basic(self): a = [3,4,5,10,-3,-5,6.0] assert_equal(amin(a),-5.0) b = [[3,6.0, 9.0], [4,10.0,5.0], [8,3.0,2.0]] assert_equal(amin(b),[3.0,3.0,2.0]) assert_equal(amin(b,axis=1),[3.0,4.0,2.0])
if option == 'N' and lwork==1: results = lapack_routine('A', m, n, a, m, s, u, m, vt, n, work, -1, iwork, 0) lwork = int(work[0]) assert lwork > 1
def svd(a, full_matrices=1, compute_uv=1): """Singular Value Decomposition. u,s,vh = svd(a) If a is an M x N array, then the svd produces a factoring of the array into two unitary (orthogonal) 2-d arrays u (MxM) and vh (NxN) and a min(M,N)-length array of singular values such that a == dot(u,dot(S,vh)) where S is a...
if isinstance(obj, str) or isinstance(obj, unicode):
if isinstance(obj, (str, _unicode)):
def array(obj, itemsize=None, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if itemsize is None: itemsize = obj.itemsize if copy or (itemsize != obj.itemsize) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtype.char, item...
return chararray(val.shape, itemsize, unicode, buffer=val, strides=val.strides, fortran=fortran)
return val.view(chararray)
def array(obj, itemsize=None, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if itemsize is None: itemsize = obj.itemsize if copy or (itemsize != obj.itemsize) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtype.char, item...
join('include','scipy','*object.h')
join('include','scipy','*object.h'), join(codegen_dir,'genapi.py'), join(codegen_dir,'*.txt')
def generate_umath_c(ext,build_dir): target = join(build_dir,'__umath_generated.c') script = generate_umath_py if newer(script,target): f = open(target,'w') f.write(generate_umath.make_code(generate_umath.defdict, generate_umath.__file__)) f.close() return []
join(codegen_dir,'generate_ufunc_api.py')
join(codegen_dir,'generate_ufunc_api.py'),
def generate_umath_c(ext,build_dir): target = join(build_dir,'__umath_generated.c') script = generate_umath_py if newer(script,target): f = open(target,'w') f.write(generate_umath.make_code(generate_umath.defdict, generate_umath.__file__)) f.close() return []
a = N.exp(N.array([1000]),dtype=N.longfloat) assert(str(a[0]) in str(a))
a = N.exp(N.array([1000],dtype=N.longfloat)) assert(str(a)[1:9] == str(a[0])[:8])
def check_longfloat_repr(self,level=rlevel): """Ticket #112""" a = N.exp(N.array([1000]),dtype=N.longfloat) assert(str(a[0]) in str(a))
exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): sig = os.WTERMSIG(exitstatus) log.error('subprocess exited with signal %d' % (sig,)) if sig == signal.SIGINT: raise KeyboardInterrupt ok = exitstatus == 0 ok = 1
if hasattr(os, 'WEXITSTATUS'): exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): sig = os.WTERMSIG(exitstatus) log.error('subprocess exited with signal %d' % (sig,)) if sig == signal.SIGINT: raise KeyboardInterrupt else: exitcode = exitstatus log.info("success!")
def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ from distutils.ccompiler import CompileError, LinkError s...
ok = 0
log.info("failure.")
def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ from distutils.ccompiler import CompileError, LinkError s...
log.info(ok and "success!" or "failure.")
def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ from distutils.ccompiler import CompileError, LinkError s...
'distributions.c', 'gamma.c', 'polevl.c', 'isnan.c', 'const.c']],
'distributions.c']],
def get_dotblas_sources(ext, build_dir): if blas_info: return ext.depends[:1] return None # no extension module will be built
'PyObject* py_%s = %s;\n' \
def declaration_code(self,templatize = 0,inline=0): var_name = self.retrieve_py_variable(inline) #code = 'PyObject* py_%s = %s;\n' \ # 'FILE* %s = convert_to_file(py_%s,"%s");\n' % \ # (self.name,var_name,self.name,self.name,self.name) code = 'PyObject* py_%s = %s;\n' \ 'PyObject* py_%s = %s;\n' \ 'FI...
def _construct_nbytes_lookup():
_alignment = _typedict() _maxvals = _typedict() _minvals = _typedict() def _construct_lookups():
def _construct_nbytes_lookup(): for name, val in typeinfo.iteritems(): if not isinstance(val, tuple): continue nbytes[val[-1]] = val[2] / 8
nbytes[val[-1]] = val[2] / 8 _construct_nbytes_lookup()
obj = val[-1] nbytes[obj] = val[2] / 8 _alignment[obj] = val[3] if (len(val) > 5): _maxvals[obj] = val[4] _minvals[obj] = val[5] else: _maxvals[obj] = None _minvals[obj] = None _construct_lookups()
def _construct_nbytes_lookup(): for name, val in typeinfo.iteritems(): if not isinstance(val, tuple): continue nbytes[val[-1]] = val[2] / 8
sys.path.append(test_dir)
sys.path.insert(0,test_dir)
def module_test(mod_name,mod_file,level=10): """* *""" import os,sys,string #print 'testing', mod_name d,f = os.path.split(mod_file) # add the tests directory to the python path test_dir = os.path.join(d,'tests') sys.path.append(test_dir) # call the "test_xxx.test()" function for the appropriate # module. # This sh...
sys.path = sys.path[:-1]
sys.path = sys.path[1:]
def module_test(mod_name,mod_file,level=10): """* *""" import os,sys,string #print 'testing', mod_name d,f = os.path.split(mod_file) # add the tests directory to the python path test_dir = os.path.join(d,'tests') sys.path.append(test_dir) # call the "test_xxx.test()" function for the appropriate # module. # This sh...
sys.path.append(test_dir)
sys.path.insert(0,test_dir)
def module_test_suite(mod_name,mod_file,level=10): #try: import os,sys,string print ' creating test suite for:', mod_name d,f = os.path.split(mod_file) # add the tests directory to the python path test_dir = os.path.join(d,'tests') sys.path.append(test_dir) # call the "test_xxx.test()" function for the appropriate # ...
sys.path = sys.path[:-1]
sys.path = sys.path[1:]
def module_test_suite(mod_name,mod_file,level=10): #try: import os,sys,string print ' creating test suite for:', mod_name d,f = os.path.split(mod_file) # add the tests directory to the python path test_dir = os.path.join(d,'tests') sys.path.append(test_dir) # call the "test_xxx.test()" function for the appropriate # ...
iadd('\tPyDict_SetItemString(d, \"%s\", PyFortranObject_New(f2py_%s_def,f2py_init_%s));'%(name,name,name))
iadd('\tF2PyDict_SetItemString(d, \"%s\", PyFortranObject_New(f2py_%s_def,f2py_init_%s));'%(name,name,name))
def dadd(line,s=doc): s[0] = '%s\n%s'%(s[0],line)
dl='';il='';f=0;fc=1
dl='';il='';f=0;fc=1;inp=0
def analyzeline(m,case,line): global groupcounter,groupname,groupcache,grouplist,filepositiontext,\ currentfilename,f77modulename,neededinterface,neededmodule,expectbegin,\ gotnextfile,previous_context block=m.group('this') if case != 'multiline': previous_context = None if expectbegin and case not in ['begin','call','...
if c=="'": fc=not fc if c=='/' and fc: f=f+1;continue
if not inp: if c=="'": fc=not fc if c=='/' and fc: f=f+1;continue if c=='(': inp = inp + 1 elif c==')': inp = inp - 1
def analyzeline(m,case,line): global groupcounter,groupname,groupcache,grouplist,filepositiontext,\ currentfilename,f77modulename,neededinterface,neededmodule,expectbegin,\ gotnextfile,previous_context block=m.group('this') if case != 'multiline': previous_context = None if expectbegin and case not in ['begin','call','...
assert all(array(conjugate(transpose(B)), mB.H))
assert all(array(conjugate(transpose(B)) == mB.H))
def test_basic(self): from scipy import linalg A = array([[1., 2.], [3., 4.]]) mA = matrix(A) assert allclose(linalg.inv(A), mA.I) assert all(array(transpose(A) == mA.T)) assert all(array(transpose(A) == mA.H)) assert all(A == mA.A) B = A + 2j*A mB = matrix(B) assert allclose(linalg.inv(B), mB.I) assert all(array(tra...
self.dll_libraries=[]
if sys.version[:3] > '2.3': self.dll_libraries = ['msvcr71']
def __init__ (self, verbose=0, dry_run=0, force=0): distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose,dry_run, force) # we need to support 3.2 which doesn't match the standard # get_versions methods regex if self.gcc_version is None: import re out = os.popen('gcc -dumpversion','r') out_string = out.re...
((test_module)*3 + (level,))
((test_module,)*3 + (level,))
def module_test(mod_name,mod_file,level=10): """* *""" import os,sys,string #print 'testing', mod_name d,f = os.path.split(mod_file) # add the tests directory to the python path test_dir = os.path.join(d,'tests') sys.path.append(test_dir) # call the "test_xxx.test()" function for the appropriate # module. # This sh...
max_iter = range(1000)
max_iterN = 10000 msg = "Did not converge after %d tries with %s"
def __init__(self, float_conv=float,int_conv=int, float_to_float=float, float_to_str = lambda v:'%24.16e' % v, title = 'Python floating point number'): """ float_conv - convert integer to float (array) int_conv - convert float (array) to integer float_to_float - convert float array to float float_to_str - convert arr...
for _ in max_iter:
for _ in xrange(max_iterN):
def __init__(self, float_conv=float,int_conv=int, float_to_float=float, float_to_str = lambda v:'%24.16e' % v, title = 'Python floating point number'): """ float_conv - convert integer to float (array) int_conv - convert float (array) to integer float_to_float - convert float array to float float_to_str - convert arr...