rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
If a name which doesn't exist in numpy's namespace is given, an exception [[WHAT? ImportError, probably?]] is raised. [NotImplemented]
If a name which doesn't exist in scipy's namespace is given, a warning on missing info.py file is shown.
def __call__(self,*packages, **options): """Load one or more packages into numpy's top-level namespace.
If no input arguments are given, then all of numpy's subpackages are
If no input arguments are given, then all of scipy's subpackages are
def __call__(self,*packages, **options): """Load one or more packages into numpy's top-level namespace.
Outputs: The function returns a tuple with all the names of the modules which were actually imported. [NotImplemented]
def __call__(self,*packages, **options): """Load one or more packages into numpy's top-level namespace.
opt.append(os.path.join(d,'LIB'))
opt.append(os.path.join(d,'lib'))
def get_library_dirs(self): opt = FCompiler.get_library_dirs(self) d = os.environ.get('ABSOFT') if d: opt.append(os.path.join(d,'LIB')) return opt
opt.extend(['fio','f90math','fmath'])
if self.get_version() >= '8.0': opt.extend(['f90math','fio','f77math','U77']) else: opt.extend(['fio','f90math','fmath','U77'])
def get_libraries(self): opt = FCompiler.get_libraries(self) opt.extend(['fio','f90math','fmath']) if os.name =='nt': opt.append('COMDLG32') return opt
def get_site_cfg(): frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back
def get_standard_file(fname): """Returns a list of files named 'fname' from 1) System-wide directory (directory-location of this module) 2) Users HOME directory (os.environ['HOME']) 3) Local directory """ filenames = []
def get_site_cfg(): # back up frame until we can't go back anymore -- get to main setup.py called frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back try: f = frame.f_globals['__file__'] except NameError: pass else: cf = os.path.join(os.path.split(os.path.abspath(f))[0], 'site.cfg') if os.path....
f = frame.f_globals['__file__']
f = __file__
def get_site_cfg(): # back up frame until we can't go back anymore -- get to main setup.py called frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back try: f = frame.f_globals['__file__'] except NameError: pass else: cf = os.path.join(os.path.split(os.path.abspath(f))[0], 'site.cfg') if os.path....
cf = os.path.join(os.path.split(os.path.abspath(f))[0], 'site.cfg') if os.path.isfile(cf): return cf try: f = __file__ except NameError,msg: f = sys.argv[0] cf = os.path.join(os.path.split(os.path.abspath(f))[0], 'site.cfg') return cf
user_file = os.path.join(f, fname) if os.path.isfile(user_file): filenames.append(user_file) if os.path.isfile(fname): filenames.append(os.path.abspath(fname)) return filenames
def get_site_cfg(): # back up frame until we can't go back anymore -- get to main setup.py called frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back try: f = frame.f_globals['__file__'] except NameError: pass else: cf = os.path.join(os.path.split(os.path.abspath(f))[0], 'site.cfg') if os.path....
cf = get_site_cfg() self.cp.read([cf]) if not self.cp.has_section(self.section): self.cp.add_section(self.section)
self.files = get_standard_file('site.cfg') self.parse_config_files()
def __init__ (self, default_lib_dirs=default_lib_dirs, default_include_dirs=default_include_dirs, verbosity = 1, ): self.__class__.info = {} self.local_prefixes = [] defaults = {} defaults['libraries'] = '' defaults['library_dirs'] = os.pathsep.join(default_lib_dirs) defaults['include_dirs'] = os.pathsep.join(default_i...
else: warnings.warn("Library error: libs=%s found_libs=%s" % \ (libs, found_libs))
def _check_libs(self,lib_dir,libs, opt_libs, exts): found_libs = self._lib_list(lib_dir, libs, exts) if len(found_libs) == len(libs): found_libs = self._extract_lib_names(found_libs) info = {'libraries' : found_libs, 'library_dirs' : [lib_dir]} opt_found_libs = self._lib_list(lib_dir, opt_libs, exts) if len(opt_found_l...
self.A = rand(10,10) self.b1 = rand(10,1) self.b2 = rand(10) self.b3 = rand(1,10)
self.A = rand(10,8) self.b1 = rand(8,1) self.b2 = rand(8) self.b3 = rand(1,8) self.b4 = rand(10)
def setUp(self): self.A = rand(10,10) self.b1 = rand(10,1) self.b2 = rand(10) self.b3 = rand(1,10) self.N = 14
c1 = dot(A, A) c2 = dot_(A, A)
c1 = dot(A.transpose(), A) c2 = dot_(A.transpose(), A)
def check_matmat(self): A = self.A c1 = dot(A, A) c2 = dot_(A, A) assert_almost_equal(c1, c2, decimal=self.N)
A, b2 = self.A, self.b2 c1 = dot(b2, A) c2 = dot_(b2, A)
A, b4 = self.A, self.b4 c1 = dot(b4, A) c2 = dot_(b4, A)
def check_vecmat(self): A, b2 = self.A, self.b2 c1 = dot(b2, A) c2 = dot_(b2, A) assert_almost_equal(c1, c2, decimal=self.N)
c1 = dot(b3, A) c2 = dot_(b3, A) assert_almost_equal(c1, c2, decimal=self.N)
c1 = dot(b3, A.transpose()) c2 = dot_(b3, A.transpose()) assert_almost_equal(c1, c2, decimal=self.N) def check_vecmat3(self): A, b4 = self.A, self.b4 c1 = dot(A.transpose(),b4) c2 = dot_(A.transpose(),b4) assert_almost_equal(c1, c2, decimal=self.N)
def check_vecmat2(self): b3, A = self.b3, self.A c1 = dot(b3, A) c2 = dot_(b3, A) assert_almost_equal(c1, c2, decimal=self.N)
self._names += ['f%d' % i for i in range(len(self._names)+1, self._nfields+1)]
self._names += ['f%d' % i for i in range(len(self._names), self._nfields)]
def _setfieldnames(self, names, titles): """convert input field names into a list and assign to the _names attribute """
f = get_frame(i)
try: f = get_frame(i) except ValueError: break
def __init__(self, package_name=None, parent_name=None, top_path=None, package_path=None, caller_level=1, **attrs): """ Construct configuration instance of a package.
caller_instance = None
pass
def __init__(self, package_name=None, parent_name=None, top_path=None, package_path=None, caller_level=1, **attrs): """ Construct configuration instance of a package.
def _wildcard_get_subpackage(self, subpackage_name, caller_level = 1):
def _wildcard_get_subpackage(self, subpackage_name, parent_name, caller_level = 1):
def _wildcard_get_subpackage(self, subpackage_name, caller_level = 1): l = subpackage_name.split('.') subpackage_path = njoin([self.local_path]+l) dirs = filter(os.path.isdir,glob.glob(subpackage_path)) config_list = [] for d in dirs: if not os.path.isfile(njoin(d,'__init__.py')): continue if 'build' in d.split(os.sep)...
c = self.get_subpackage(n, caller_level = caller_level+1)
c = self.get_subpackage(n, parent_name = parent_name, caller_level = caller_level+1)
def _wildcard_get_subpackage(self, subpackage_name, caller_level = 1): l = subpackage_name.split('.') subpackage_path = njoin([self.local_path]+l) dirs = filter(os.path.isdir,glob.glob(subpackage_path)) config_list = [] for d in dirs: if not os.path.isfile(njoin(d,'__init__.py')): continue if 'build' in d.split(os.sep)...
subpackage_name, subpackage_path,
subpackage_name, subpackage_path, parent_name,
def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, caller_level = 1): # In case setup_py imports local modules: sys.path.insert(0,os.path.dirname(setup_py)) try: fo_setup_py = open(setup_py, 'U') setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(self.name,subp...
config = Configuration(subpackage_name, self.name,
config = Configuration(subpackage_name, parent_name,
def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, caller_level = 1): # In case setup_py imports local modules: sys.path.insert(0,os.path.dirname(setup_py)) try: fo_setup_py = open(setup_py, 'U') setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(self.name,subp...
args = (self.name,)
args = (parent_name,)
def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, caller_level = 1): # In case setup_py imports local modules: sys.path.insert(0,os.path.dirname(setup_py)) try: fo_setup_py = open(setup_py, 'U') setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(self.name,subp...
def get_subpackage(self,subpackage_name,subpackage_path=None,
def get_subpackage(self,subpackage_name, subpackage_path=None, parent_name=None,
def get_subpackage(self,subpackage_name,subpackage_path=None, caller_level = 1): """ Return list of subpackage configurations.
config = Configuration(subpackage_name, self.name,
config = Configuration(subpackage_name, parent_name,
def get_subpackage(self,subpackage_name,subpackage_path=None, caller_level = 1): """ Return list of subpackage configurations.
def add_subpackage(self,subpackage_name,subpackage_path=None):
def add_subpackage(self,subpackage_name, subpackage_path=None, standalone = False):
def add_subpackage(self,subpackage_name,subpackage_path=None): """ Add subpackage to configuration. """ config_list = self.get_subpackage(subpackage_name,subpackage_path, caller_level = 2) if not config_list: self.warn('No configuration returned, assuming unavailable.') for config in config_list: try: d = config.todict...
_names = dtype.names
_names = descr.names
def fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, 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]...
add_docstring(digitize, r"""digitize(x,bins)
try: add_docstring(digitize, r"""digitize(x,bins)
def diff(a, n=1, axis=-1): """Calculate the nth order discrete difference along given axis. """ if n == 0: return a if n < 0: raise ValueError, 'order must be non-negative but got ' + repr(n) a = asanyarray(a) nd = len(a.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axi...
Return the index of the bin to which each value of x belongs. Each index i returned is such that bins[i-1] <= x < bins[i] if bins is monotonically increasing, or bins [i-1] > x >= bins[i] if bins is monotonically decreasing. Beyond the bounds of the bins 0 or len(bins) is returned as appropriate. """) add_docstring(...
Return the index of the bin to which each value of x belongs. Each index i returned is such that bins[i-1] <= x < bins[i] if bins is monotonically increasing, or bins [i-1] > x >= bins[i] if bins is monotonically decreasing. Beyond the bounds of the bins 0 or len(bins) is returned as appropriate. """) except RuntimeE...
def diff(a, n=1, axis=-1): """Calculate the nth order discrete difference along given axis. """ if n == 0: return a if n < 0: raise ValueError, 'order must be non-negative but got ' + repr(n) a = asanyarray(a) nd = len(a.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axi...
b = asarray(a).sort()
b = array(a,copy=True) b.sort()
def sort_complex(a): """ Sort 'a' as a complex array using the real part first and then the imaginary part if the real part is equal (the default sort order for complex arrays). This function is a wrapper ensuring a complex return type. """ b = asarray(a).sort() if not issubclass(b.dtype, _nx.complexfloating): if b.dt...
return a.sort(0)
b = array(a,copy=True) b.sort(0) return b
def msort(a): return a.sort(0)
log.info('splitcmdline(%r)' % (line))
log.debug('splitcmdline(%r)' % (line))
def splitcmdline(line): """ Inverse of ' '.join(sys.argv). """ log.info('splitcmdline(%r)' % (line)) lst = [] flag = 0 s,pc,cc = '','','' for nc in line+' ': if flag==0: flag = (pc != '\\' and \ ((cc=='"' and 1) or (cc=="'" and 2) or \ (cc==' ' and pc!=' ' and -2))) or flag elif flag==1: flag = (cc=='"' and pc!='\\' an...
status = int(f.read())
status_text = f.read() status = int(status_text)
def _exec_command_posix( command, use_shell = None, use_tee = None, **env ): log.debug('_exec_command_posix(...)') if type(command) is type([]): command_str = ' '.join(command) else: command_str = command tmpfile = tempfile.mktemp() stsfile = None if use_tee: stsfile = tempfile.mktemp() filter = '' if use_tee == 2: f...
argv[0] = quote_arg(argv[0]) if os.name in ['nt','dos']: argv = [os.environ['COMSPEC'],'/C'] + argv using_command = 1
if os.name in ['nt','dos']: argv = [os.environ['COMSPEC'],'/C'] + argv using_command = 1
def _exec_command( command, use_shell=None, use_tee = None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = 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.g...
if 0 and using_command:
if using_command:
def _exec_command( command, use_shell=None, use_tee = None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = 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.g...
status = spawn_command(os.P_WAIT,argv[0],argv,os.environ)
status = spawn_command(os.P_WAIT,argv0,argv,os.environ)
def _exec_command( command, use_shell=None, use_tee = None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = 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.g...
if fortran_ext_re(str(file)):
if fortran_ext_re(file):
def fortran_sources_to_flib(self, ext): """ Extract fortran files from ext.sources and append them to fortran_libraries item having the same name as ext. """ sources = [] f_files = []
names.append(mthname)
if mthname not in names: names.append(mthname)
def _get_method_names(self,clsobj,level): names = [] for mthname in _get_all_method_names(clsobj): if mthname[:5] not in ['bench','check'] \ and mthname[:4] not in ['test']: continue mth = getattr(clsobj, mthname) if type(mth) is not types.MethodType: continue d = mth.im_func.func_defaults if d is not None: mthlevel = ...
if package_name == '__main__': suites.extend(self._get_suite_list(sys.modules[package_name], level))
suites.extend(self._get_suite_list(sys.modules[package_name], level))
def test(self,level=1,verbosity=1): """ Run Scipy module test suite with level and verbosity. """ if type(self.package) is type(''): exec 'import %s as this_package' % (self.package) else: this_package = self.package
del result.errors[-1]
def __call__(self, result=None): if result is None: return unittest.TestCase.__call__(self, result)
del result.errors[-1]
del result.errors[-1] result.testsRun = result.testsRun - 1
def __call__(self, result=None): if result is None: return unittest.TestCase.__call__(self, result)
Environment variables NUMPY_IMPORT_VERBOSE --- pkgload verbose flag, default is 0.
def test(level=1, verbosity=1): return NumpyTest().test(level, verbosity)
print _global_color_map[level](msg % args)
print _global_color_map[level](msg % _fix_args(args))
def _log(self, level, msg, args): if level>= self.threshold: if args: print _global_color_map[level](msg % args) else: print _global_color_map[level](msg) sys.stdout.flush()
print _global_color_map[level](msg % args)
print _global_color_map[level](msg % _fix_args(args))
def _log(self, level, msg, args): if level >= self.threshold: print _global_color_map[level](msg % args) sys.stdout.flush()
if options.get('verbose',False):
if verbose>1:
def __call__(self,*packages, **options): """Load one or more packages into scipy's top-level namespace.
new_object = frame.f_locals.get(package_name) if old_object is not None and old_object is not new_object: print >> sys.stderr, 'Overwriting',package_name,'=',\ `old_object`,'with',`new_object`
if verbose: new_object = frame.f_locals.get(package_name) if old_object is not None and old_object is not new_object: print >> sys.stderr, 'Overwriting',package_name,'=',\ `old_object`,'with',`new_object`
def __call__(self,*packages, **options): """Load one or more packages into scipy's top-level namespace.
if options.get('verbose',False):
if verbose:
def __call__(self,*packages, **options): """Load one or more packages into scipy's top-level namespace.
old_objects = {} for s in symbols: if frame.f_locals.has_key(s): old_objects[s] = frame.f_locals[s]
if verbose: old_objects = {} for s in symbols: if frame.f_locals.has_key(s): old_objects[s] = frame.f_locals[s]
def __call__(self,*packages, **options): """Load one or more packages into scipy's top-level namespace.
for s,old_object in old_objects.items(): new_object = frame.f_locals[s] if new_object is not old_object: print >> sys.stderr, 'Overwriting',s,'=',\ `old_object`,'with',`new_object`
if verbose: for s,old_object in old_objects.items(): new_object = frame.f_locals[s] if new_object is not old_object: print >> sys.stderr, 'Overwriting',s,'=',\ `old_object`,'with',`new_object`
def __call__(self,*packages, **options): """Load one or more packages into scipy's top-level namespace.
or not issubclass(obj, unittest.TestCase):
or not issubclass(obj, unittest.TestCase) \ or obj.__name__[:5] != 'test_':
def _get_module_tests(self,module,level): mstr = self._module_str d,f = os.path.split(module.__file__) short_module_name = module.__name__.split('.')[-1] test_dir = os.path.join(d,'tests') test_file = os.path.join(test_dir,'test_'+short_module_name+'.py')
ver_match = r'GNU Fortran (\(GCC\s*|)(?P<version>[^\s*\)]+)'
ver_match = r'GNU Fortran (\(GCC\)|\(GCC.*\)\)|)\s*(?P<version>[^\s*\)]+)'
def get_version(self): if self.version is not None: return self.version self.version = '' self.announce(yellow_text(self.ver_cmd)) exit_status, out_text = run_command(self.ver_cmd) if self.verbose: out_text = out_text.split('\n')[0] if exit_status in [0,256]: # 256 seems to indicate success on HP-UX but keeping # also ...
opt.extend(['-framework','Python'])
opt.extend(["-Wl,-framework","-Wl,Python","-lcc_dynamic","-bundle"])
def get_flags_linker_so(self): opt = [] if sys.platform=='darwin': opt.extend(['-framework','Python']) else: opt.append("-shared") if sys.platform[:5]=='sunos': # SunOS often has dynamically loaded symbols defined in the # static library libg2c.a The linker doesn't like this. To # ignore the problem, use the -mimpure...
names.append(fname) offsets.append(num)
def _usefields(adict): names = [] formats = [] offsets = [] titles = [] fnames = adict.keys() for fname in fnames: obj = adict[fname] n = len(obj) if not isinstance(obj, tuple) or n not in [2,3]: raise ValueError, "entry not a 2- or 3- tuple" if (n > 2) and (obj[2] == fname): continue num = int(obj[1]) if (num < 0): ra...
raise ValueError, "all itemsizes must be given." formats.append(format)
raise ValueError, "all itemsizes must be fixed."
def _usefields(adict): names = [] formats = [] offsets = [] titles = [] fnames = adict.keys() for fname in fnames: obj = adict[fname] n = len(obj) if not isinstance(obj, tuple) or n not in [2,3]: raise ValueError, "entry not a 2- or 3- tuple" if (n > 2) and (obj[2] == fname): continue num = int(obj[1]) if (num < 0): ra...
titles.append(title) return dtypedescr({"names" : names, "formats" : formats, "offsets" : offsets, "titles" : titles})
allfields.append((fname, format, num, title)) allfields.sort(lambda x,y: cmp(x[2],y[2])) return dtypedescr({"names" : [x[0] for x in allfields], "formats" : [x[1] for x in allfields], "offsets" : [x[2] for x in allfields], "titles" : [x[3] for x in allfields]})
def _usefields(adict): names = [] formats = [] offsets = [] titles = [] fnames = adict.keys() for fname in fnames: obj = adict[fname] n = len(obj) if not isinstance(obj, tuple) or n not in [2,3]: raise ValueError, "entry not a 2- or 3- tuple" if (n > 2) and (obj[2] == fname): continue num = int(obj[1]) if (num < 0): ra...
fullname = name location = 'sys.path'
def ppimport(name): """ ppimport(name) -> module or module wrapper If name has been imported before, return module. Otherwise return ModuleLoader instance that transparently postpones module import until the first attempt to access module name attributes. """ p_frame = _get_frame(1) p_name = p_frame.f_locals['__name__...
ar = numpy.array(ar1).ravel()
def unique1d( ar1, retindx = False ): """Unique elements of 1D array. When ret_indx is True, return also the indices indx such that ar1.flat[indx] is the resulting array of unique elements.""" if retindx: ar = numpy.array(ar1).ravel() perm = ar.argsort() aux = ar.take(perm) flag = ediff1d( aux, 1 ) != 0 return perm.com...
ar = numpy.array( ar1 ).flatten() ar.sort() return ar.compress( ediff1d( ar, 1 ) != 0)
ar = numpy.array(sorted(ar)) return ar.compress(ediff1d(ar, 1) != 0)
def unique1d( ar1, retindx = False ): """Unique elements of 1D array. When ret_indx is True, return also the indices indx such that ar1.flat[indx] is the resulting array of unique elements.""" if retindx: ar = numpy.array(ar1).ravel() perm = ar.argsort() aux = ar.take(perm) flag = ediff1d( aux, 1 ) != 0 return perm.com...
astr = astr.replace("'c'","'S1'")
def replacetypechars(astr): astr = astr.replace("'s'","'h'") astr = astr.replace("'c'","'S1'") astr = astr.replace("'b'","'B'") astr = astr.replace("'1'","'b'") astr = astr.replace("'w'","'H'") astr = astr.replace("'u'","'I'") return astr
filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.dft.oldfft')
filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.dft.old')
def fromstr(filestr): #filestr = replacetypechars(filestr) filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') filestr, fromall1 = changeimports(filestr, 'multiarray', 'numpy.core.multiarray') filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.core.umath') filestr, fromall1 = changeimports...
'base','include'))
'core','include'))
def get_numpy_include_dirs(): # numpy_include_dirs are set by numpy/base/setup.py, otherwise [] include_dirs = Configuration.numpy_include_dirs[:] if not include_dirs: import numpy if numpy.show_core_config is None: # running from numpy_core source directory include_dirs.append(os.path.join(os.path.dirname(numpy.__file...
import numpy.base as base include_dirs.append(os.path.join(os.path.dirname(base.__file__),'include'))
import numpy.core as core include_dirs.append(os.path.join(os.path.dirname(core.__file__),'include'))
def get_numpy_include_dirs(): # numpy_include_dirs are set by numpy/base/setup.py, otherwise [] include_dirs = Configuration.numpy_include_dirs[:] if not include_dirs: import numpy if numpy.show_core_config is None: # running from numpy_core source directory include_dirs.append(os.path.join(os.path.dirname(numpy.__file...
return issubclass(dtype(arg1).type, dtype(arg2).type)
return issubclass(_dtype(arg1).type, _dtype(arg2).type)
def issubdtype(arg1, arg2): return issubclass(dtype(arg1).type, dtype(arg2).type)
raise TypeError("argument must be an ndarray") if cls._dtype_ and obj.dtype != cls._dtype_: raise TypeError("array must have data type", cls._dtype_) if cls._ndim_ and obj.ndim != cls._ndim_: raise TypeError("array must have %d dimension(s)" % cls._ndim_) if cls._shape_ and obj.shape != cls._shape_: raise TypeError("ar...
raise TypeError, "argument must be an ndarray" if cls._dtype_ is not None \ and obj.dtype != cls._dtype_: raise TypeError, "array must have data type %s" % cls._dtype_ if cls._ndim_ is not None \ and obj.ndim != cls._ndim_: raise TypeError, "array must have %d dimension(s)" % cls._ndim_ if cls._shape_ is not None \ and...
def from_param(cls, obj): if not isinstance(obj, ndarray): raise TypeError("argument must be an ndarray") if cls._dtype_ and obj.dtype != cls._dtype_: raise TypeError("array must have data type", cls._dtype_) if cls._ndim_ and obj.ndim != cls._ndim_: raise TypeError("array must have %d dimension(s)" % cls._ndim_) if cl...
def ndpointer(datatype=None, ndim=None, shape=None, flags=None): if datatype is not None: datatype = dtype(datatype)
def ndpointer(dtype=None, ndim=None, shape=None, flags=None): if dtype is not None: dtype = _dtype(dtype)
def ndpointer(datatype=None, ndim=None, shape=None, flags=None): if datatype is not None: datatype = dtype(datatype) num = None if flags is not None: if isinstance(flags, str): flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags flags = _flags_fromnum(flags) if num is None: flags = [x.strip().u...
return _pointer_type_cache[(datatype, ndim, shape, num)]
return _pointer_type_cache[(dtype, ndim, shape, num)]
def ndpointer(datatype=None, ndim=None, shape=None, flags=None): if datatype is not None: datatype = dtype(datatype) num = None if flags is not None: if isinstance(flags, str): flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags flags = _flags_fromnum(flags) if num is None: flags = [x.strip().u...
if datatype is None:
if dtype is None:
def ndpointer(datatype=None, ndim=None, shape=None, flags=None): if datatype is not None: datatype = dtype(datatype) num = None if flags is not None: if isinstance(flags, str): flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags flags = _flags_fromnum(flags) if num is None: flags = [x.strip().u...
elif datatype.names: name = str(id(datatype)) else: name = datatype.str
elif dtype.names: name = str(id(dtype)) else: name = dtype.str
def ndpointer(datatype=None, ndim=None, shape=None, flags=None): if datatype is not None: datatype = dtype(datatype) num = None if flags is not None: if isinstance(flags, str): flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags flags = _flags_fromnum(flags) if num is None: flags = [x.strip().u...
{"_dtype_": datatype,
{"_dtype_": dtype,
def ndpointer(datatype=None, ndim=None, shape=None, flags=None): if datatype is not None: datatype = dtype(datatype) num = None if flags is not None: if isinstance(flags, str): flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags flags = _flags_fromnum(flags) if num is None: flags = [x.strip().u...
_pointer_type_cache[datatype] = klass
_pointer_type_cache[dtype] = klass
def ndpointer(datatype=None, ndim=None, shape=None, flags=None): if datatype is not None: datatype = dtype(datatype) num = None if flags is not None: if isinstance(flags, str): flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags flags = _flags_fromnum(flags) if num is None: flags = [x.strip().u...
if self.otypes == '': otypes = [] for k in range(self.nout): otypes.append(asarray(theout[k]).dtype.char) self.otypes = ''.join(otypes) if (self.ufunc is None) or (self.lastcallargs != nargs):
otypes = [] for k in range(self.nout): otypes.append(asarray(theout[k]).dtype.char) self.otypes = ''.join(otypes) if (self.ufunc is None):
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 self.nin: 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 ...
self.lastcallargs = nargs
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 self.nin: 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 ...
return array(self.ufunc(*args),copy=False).astype(self.otypes[0])
_res = array(self.ufunc(*args),copy=False).astype(self.otypes[0])
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 self.nin: 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 ...
return tuple([array(x,copy=False).astype(c) \
_res = tuple([array(x,copy=False).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 self.nin: 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 ...
if not l:
if l:
def get_version(self,*args,**kwds): version = FCompiler.get_version(self,*args,**kwds) xlf_dir = '/etc/opt/ibmcmp/xlf' if version is None and os.path.isdir(xlf_dir): # If the output of xlf does not contain version info # (that's the case with xlf 8.1, for instance) then # let's try another method: l = os.listdir(xlf_di...
if type(item) != type(()):
if self.maketuple and type(item) != type(()):
def __getitem__(self, item): if type(item) != type(()): return (item,) else: return item
index_exp = _index_expression_class()
index_exp = _index_expression_class(1) s_ = _index_expression_class(0)
def __getslice__(self, start, stop): if stop == self.maxint: stop = None return self[start:stop:None]
return str(a.item())
obj = a.item() if isinstance(obj, tuple): obj = _convert_arrays(obj) return str(obj)
def _formatArray(a, format_function, rank, max_line_len, next_line_prefix, separator, edge_items, summary_insert): """formatArray is designed for two modes of operation: 1. Full output 2. Summarized output """ if rank == 0: return str(a.item()) if summary_insert and 2*edge_items < len(a): leading_items, trailing_it...
try: nosmp = os.environ['NPY_NOSMP']
if sys.version[:3] < '2.4':
def generate_config_h(ext, build_dir): target = join(build_dir,'config.h') if newer(__file__,target): config_cmd = config.get_config_cmd() print 'Generating',target # tc = generate_testcode(target) from distutils import sysconfig python_include = sysconfig.get_python_inc() result = config_cmd.try_run(tc,include_dirs=[p...
except KeyError: nosmp = 0
else: try: nosmp = os.environ['NPY_NOSMP'] nosmp = 1 except KeyError: nosmp = 0
def generate_config_h(ext, build_dir): target = join(build_dir,'config.h') if newer(__file__,target): config_cmd = config.get_config_cmd() print 'Generating',target # tc = generate_testcode(target) from distutils import sysconfig python_include = sysconfig.get_python_inc() result = config_cmd.try_run(tc,include_dirs=[p...
res = func1d(arr[tuple(i)],*args)
res = func1d(arr[tuple(i.tolist())],*args)
def apply_along_axis(func1d,axis,arr,*args): """ Execute func1d(arr[i],*args) where func1d takes 1-D arrays and arr is an N-d array. i varies so as to apply the function along the given axis for each 1-d subarray in arr. """ arr = asarray(arr) nd = arr.ndim if axis < 0: axis += nd if (axis >= nd): raise ValueError("ax...
outarr[tuple(i)] = res
outarr[tuple(i.tolist())] = res
def apply_along_axis(func1d,axis,arr,*args): """ Execute func1d(arr[i],*args) where func1d takes 1-D arrays and arr is an N-d array. i varies so as to apply the function along the given axis for each 1-d subarray in arr. """ arr = asarray(arr) nd = arr.ndim if axis < 0: axis += nd if (axis >= nd): raise ValueError("ax...
res = func1d(arr[tuple(i)],*args) outarr[tuple(i)] = res
res = func1d(arr[tuple(i.tolist())],*args) outarr[tuple(i.tolist())] = res
def apply_along_axis(func1d,axis,arr,*args): """ Execute func1d(arr[i],*args) where func1d takes 1-D arrays and arr is an N-d array. i varies so as to apply the function along the given axis for each 1-d subarray in arr. """ arr = asarray(arr) nd = arr.ndim if axis < 0: axis += nd if (axis >= nd): raise ValueError("ax...
m = imp.load_module(name, open(filename), filename,('.py','U',1))
path = [os.path.dirname(filename)] file, pathname, description = imp.find_module(name, path) try: m = imp.load_module(name, file, pathname, description) finally: file.close()
def rundocs(self, filename=None): """ Run doc string tests found in filename. """ import doctest if filename is None: f = get_frame(1) filename = f.f_globals['__file__'] name = os.path.splitext(os.path.basename(filename))[0] m = imp.load_module(name, open(filename), filename,('.py','U',1)) tests = doctest.DocTestFinder...
return asscalar(x)
return x
def _fix_real_lt_zero(x): x = asarray(x) if any(isreal(x) & (x<0)): x = _tocomplex(x) return asscalar(x)
name = name + '__OF__' + self.name
name = name
def add_library(self,name,sources,**build_info): """ Add library to configuration. Valid keywords for build_info: depends macros include_dirs extra_compiler_args f2py_options """ build_info = copy.copy(build_info) name = name + '__OF__' + self.name build_info['sources'] = sources
typecode = _nx.Int
def __getitem__(self,key): if isinstance(key,types.StringType): frame = sys._getframe().f_back mymat = matrix.bmat(key,frame.f_globals,frame.f_locals) return mymat if type(key) is not types.TupleType: key = (key,) objs = [] for k in range(len(key)): if type(key[k]) is types.SliceType: typecode = _nx.Int step = key[k].s...
typecode = _nx.Float newobj = function_base.linspace(start, stop, num=size, dtype=typecode)
newobj = function_base.linspace(start, stop, num=size)
def __getitem__(self,key): if isinstance(key,types.StringType): frame = sys._getframe().f_back mymat = matrix.bmat(key,frame.f_globals,frame.f_locals) return mymat if type(key) is not types.TupleType: key = (key,) objs = [] for k in range(len(key)): if type(key[k]) is types.SliceType: typecode = _nx.Int step = key[k].s...
newobj = _nx.arange(start, stop, step, dtype=typecode)
newobj = _nx.arange(start, stop, step)
def __getitem__(self,key): if isinstance(key,types.StringType): frame = sys._getframe().f_back mymat = matrix.bmat(key,frame.f_globals,frame.f_locals) return mymat if type(key) is not types.TupleType: key = (key,) objs = [] for k in range(len(key)): if type(key[k]) is types.SliceType: typecode = _nx.Int step = key[k].s...
if len(shape) != 0: n = Numeric.multiply.reduce(shape) s = apply(fun, args + (n,)) s.shape = shape return s else: n = 1 s = apply(fun, args + (n,)) return s[0]
n = Numeric.multiply.reduce(shape) s = apply(fun, args + (n,)) print s.shape return s.reshape(shape)
def _build_random_array(fun, args, shape=[]):
return _old_inspect_getfile(object)
return _old_inspect_getfile(_ppresolve_ignore_failure(object))
def _ppimport_inspect_getfile(object): if isinstance(object,_ModuleLoader): return object.__dict__['__file__'] return _old_inspect_getfile(object)
if os.name=='nt':
if os.name=='nt' and sys.version[:3] > '2.3':
def memusage(): """ Return memory usage of running python. [Not implemented]""" return
opt.append('-framework','Python')
opt.extend(['-framework','Python'])
def get_flags_linker_so(self): opt = [] if sys.platform=='darwin': opt.append('-framework','Python') else: opt.append("-shared") if sys.platform[:5]=='sunos': # SunOS often has dynamically loaded symbols defined in the # static library libg2c.a The linker doesn't like this. To # ignore the problem, use the -mimpure-t...
if os.path.realpath(sys.executable).startswith('/System'):
try: import MacOS except ImportError: is_framework = False else: is_framework = (MacOS.linkmodel == 'framework') if is_framework:
def get_flags_linker_so(self): opt = [] if sys.platform=='darwin': if os.path.realpath(sys.executable).startswith('/System'): # This is when Python is from Apple framework opt.extend(["-Wl,-framework","-Wl,Python"]) #else we are running in Fink python. opt.extend(["-lcc_dynamic","-bundle"]) else: opt.append("-shared") ...
opt.extend(["-Wl,-framework","-Wl,Python"]) opt.extend(["-lcc_dynamic","-bundle"])
target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) if target is None: target = '10.3' major, minor = target.split('.') if int(minor) < 3: minor = '3' warnings.warn('Environment variable ' 'MACOSX_DEPLOYMENT_TARGET reset to 10.3') os.environ['MACOSX_DEPLOYMENT_TARGET'] = '%s.%s' % (major, minor) opt.extend(['-un...
def get_flags_linker_so(self): opt = [] if sys.platform=='darwin': if os.path.realpath(sys.executable).startswith('/System'): # This is when Python is from Apple framework opt.extend(["-Wl,-framework","-Wl,Python"]) #else we are running in Fink python. opt.extend(["-lcc_dynamic","-bundle"]) else: opt.append("-shared") ...
trans1d = False
trans1d = -1
def __getitem__(self,key): trans1d = False ndmin = 1 if isinstance(key, str): frame = sys._getframe().f_back mymat = matrix.bmat(key,frame.f_globals,frame.f_locals) return mymat if type(key) is not tuple: key = (key,) objs = [] scalars = [] final_dtypedescr = None for k in range(len(key)): scalar = False if type(key[k]...
if trans1d: newobj = newobj.T
if trans1d != -1: newobj = newobj.swapaxes(-1,trans1d)
def __getitem__(self,key): trans1d = False ndmin = 1 if isinstance(key, str): frame = sys._getframe().f_back mymat = matrix.bmat(key,frame.f_globals,frame.f_locals) return mymat if type(key) is not tuple: key = (key,) objs = [] scalars = [] final_dtypedescr = None for k in range(len(key)): scalar = False if type(key[k]...
if len(vec) == 3 and vec[2] == 't': trans1d = True
if len(vec) == 3: trans1d = int(vec[2])
def __getitem__(self,key): trans1d = False ndmin = 1 if isinstance(key, str): frame = sys._getframe().f_back mymat = matrix.bmat(key,frame.f_globals,frame.f_locals) return mymat if type(key) is not tuple: key = (key,) objs = [] scalars = [] final_dtypedescr = None for k in range(len(key)): scalar = False if type(key[k]...
if trans1d and tempobj.ndim == 1: newobj = newobj.T
if trans1d != -1 and tempobj.ndim < ndmin: k2 = ndmin-tempobj.ndim if (trans1d < 0): trans1d += k2 + 1 defaxes = range(ndmin) k1 = trans1d axes = defaxes[:k1] + defaxes[k2:] + \ defaxes[k1:k2] newobj = newobj.transpose(axes)
def __getitem__(self,key): trans1d = False ndmin = 1 if isinstance(key, str): frame = sys._getframe().f_back mymat = matrix.bmat(key,frame.f_globals,frame.f_locals) return mymat if type(key) is not tuple: key = (key,) objs = [] scalars = [] final_dtypedescr = None for k in range(len(key)): scalar = False if type(key[k]...
return {double : double, cdouble : double}
try: return {double : double, cdouble : double}[t] except KeyError: return double
def _realType(t): return {double : double, cdouble : double}
if mod_name == '__main__': d = os.path.abspath('.') elif mod_name == '__builtin__':
if mod_name == '__builtin__':
def get_path(mod_name, parent_path=None): """ Return path of the module. Returned path is relative to parent_path when given, otherwise it is absolute path. """ if mod_name == '__main__': d = os.path.abspath('.') elif mod_name == '__builtin__': #builtin if/then added by Pearu for use in core.run_setup. d = os.path.dir...