rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
perm = numpy.argsort( ar ) aux = numpy.take( ar, perm )
ar = numpy.array(ar1).ravel() perm = ar.argsort() aux = ar.take(perm)
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.""" ar = numpy.array( ar1 ).ravel() if retindx: perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) flag = ediff1d( aux, 1 ) !=...
return numpy.compress( flag, perm ), numpy.compress( flag, aux )
return perm.compress(flag), aux.compress(flag)
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.""" ar = numpy.array( ar1 ).ravel() if retindx: perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) flag = ediff1d( aux, 1 ) !=...
aux = numpy.sort( ar ) return numpy.compress( ediff1d( aux, 1 ) != 0, aux )
ar = numpy.array( ar1 ).flatten() ar.sort() 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.""" ar = numpy.array( ar1 ).ravel() if retindx: perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) flag = ediff1d( aux, 1 ) !=...
aux = numpy.sort( numpy.concatenate( (ar1, ar2 ) ) ) return numpy.compress( (aux[1:] - aux[:-1]) == 0, aux )
aux = numpy.concatenate((ar1,ar2)) aux.sort() return aux.compress( (aux[1:] - aux[:-1]) == 0)
def intersect1d( ar1, ar2 ): """Intersection of 1D arrays with unique elements.""" aux = numpy.sort( numpy.concatenate( (ar1, ar2 ) ) ) return numpy.compress( (aux[1:] - aux[:-1]) == 0, aux )
aux = numpy.sort( numpy.concatenate( (unique1d( ar1 ), unique1d( ar2 )) ) ) return numpy.compress( (aux[1:] - aux[:-1]) == 0, aux )
aux = numpy.concatenate((unique1d(ar1), unique1d(ar2))) aux.sort() return aux.compress( (aux[1:] - aux[:-1]) == 0)
def intersect1d_nu( ar1, ar2 ): """Intersection of 1D arrays with any elements.""" # Might be faster then unique1d( intersect1d( ar1, ar2 ) )? aux = numpy.sort( numpy.concatenate( (unique1d( ar1 ), unique1d( ar2 )) ) ) return numpy.compress( (aux[1:] - aux[:-1]) == 0, aux )
aux = numpy.sort( numpy.concatenate( (ar1, ar2 ) ) )
aux = numpy.concatenate( (ar1, ar2 ) ) aux.sort()
def setxor1d( ar1, ar2 ): """Set exclusive-or of 1D arrays with unique elements.""" aux = numpy.sort( numpy.concatenate( (ar1, ar2 ) ) ) flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0 flag2 = ediff1d( flag, 0 ) == 0 return numpy.compress( flag2, aux )
return numpy.compress( flag2, aux )
return aux.compress( flag2 )
def setxor1d( ar1, ar2 ): """Set exclusive-or of 1D arrays with unique elements.""" aux = numpy.sort( numpy.concatenate( (ar1, ar2 ) ) ) flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0 flag2 = ediff1d( flag, 0 ) == 0 return numpy.compress( flag2, aux )
ar = numpy.concatenate( (ar1, ar2 ) ) tt = numpy.concatenate( (numpy.zeros_like( ar1 ), numpy.zeros_like( ar2 ) + 1) ) perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) aux2 = numpy.take( tt, perm )
concat = numpy.concatenate zlike = numpy.zeros_like ar = concat( (ar1, ar2 ) ) tt = concat( (zlike( ar1 ), zlike( ar2 ) + 1) ) perm = ar.argsort() aux = ar.take(perm) aux2 = tt.take(perm)
def setmember1d( ar1, ar2 ): """Return an array of shape of ar1 containing 1 where the elements of ar1 are in ar2 and 0 otherwise.""" ar = numpy.concatenate( (ar1, ar2 ) ) tt = numpy.concatenate( (numpy.zeros_like( ar1 ), numpy.zeros_like( ar2 ) + 1) ) perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) aux2 = nump...
indx = numpy.argsort( perm )[:len( ar1 )] return numpy.take( flag, indx )
indx = perm.argsort()[:len( ar1 )] return flag.take( indx )
def setmember1d( ar1, ar2 ): """Return an array of shape of ar1 containing 1 where the elements of ar1 are in ar2 and 0 otherwise.""" ar = numpy.concatenate( (ar1, ar2 ) ) tt = numpy.concatenate( (numpy.zeros_like( ar1 ), numpy.zeros_like( ar2 ) + 1) ) perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) aux2 = nump...
return numpy.compress( aux == 0, ar1 )
return ar1.compress(aux == 0)
def setdiff1d( ar1, ar2 ): """Set difference of 1D arrays with unique elements.""" aux = setmember1d( ar1, ar2 ) return numpy.compress( aux == 0, ar1 )
log.info('Disabled',self.__class__.__name__,'(%s is None)' \ % (self.dir_env_var))
log.info('Disabled %s: %s',self.__class__.__name__,'(%s is None)' \ % (env_var,))
def get_paths(self, section, key): dirs = self.cp.get(section, key).split(os.pathsep) env_var = self.dir_env_var if env_var: if is_sequence(env_var): e0 = env_var[-1] for e in env_var: if os.environ.has_key(e): e0 = e break if not env_var[0]==e0: log.info('Setting %s=%s' % (env_var[0],e0)) env_var = e0 if env_var and o...
a = array(a,copy=False)
def put (a, ind, v): """put(a, ind, v) results in a[n] = v[n] for all n in ind If v is shorter than mask it will be repeated as necessary. In particular v can be a scalar or length 1 array. The routine put is the equivalent of the following (although the loop is in C for speed): ind = array(indices, copy=False) v = ar...
a = array(a,copy=False)
def putmask (a, mask, v): """putmask(a, mask, v) results in a = v for all places mask is true. If v is shorter than mask it will be repeated as necessary. In particular v can be a scalar or length 1 array. """ a = array(a,copy=False) return a.putmask(v, mask)
as = a.shape
as_ = a.shape
def tensordot(a, b, axes=2): """tensordot returns the product for any (ndim >= 1) arrays. r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where the axes to be summed over are given by the axes argument. the first element of the sequence determines the axis or axes in arr1 to sum over, and the second element in axes argumen...
if as[axes_a[k]] != bs[axes_b[k]]:
if as_[axes_a[k]] != bs[axes_b[k]]:
def tensordot(a, b, axes=2): """tensordot returns the product for any (ndim >= 1) arrays. r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where the axes to be summed over are given by the axes argument. the first element of the sequence determines the axis or axes in arr1 to sum over, and the second element in axes argumen...
N2 *= as[axis]
N2 *= as_[axis]
def tensordot(a, b, axes=2): """tensordot returns the product for any (ndim >= 1) arrays. r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where the axes to be summed over are given by the axes argument. the first element of the sequence determines the axis or axes in arr1 to sum over, and the second element in axes argumen...
olda = [as[axis] for axis in notin]
olda = [as_[axis] for axis in notin]
def tensordot(a, b, axes=2): """tensordot returns the product for any (ndim >= 1) arrays. r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where the axes to be summed over are given by the axes argument. the first element of the sequence determines the axis or axes in arr1 to sum over, and the second element in axes argumen...
f_ext = fn+s
f_ext = os.path.realpath(fn+s)
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) suffices = [''] if os.name in ['nt','dos','os2']: fn,ext = os.path.splitext(exe) extra_suffices = ['.exe','.com','.bat'] if ext.lower() not in ...
if os.name in ['nt','dos']: argv = [os.environ['COMSPEC'],'/C']+argv using_command = 1
argv[0] = quote_arg(argv[0]) if os.name in ['nt','dos']: argv = [os.environ['COMSPEC'],'/C']+argv using_command = 1
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,...
argv0 = quote_arg(argv[0])
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,...
status = spawn_command(os.P_WAIT,argv0,argv,os.environ)
status = spawn_command(os.P_WAIT,argv[0],argv,os.environ)
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 indices(dimensions, dtype=intp): """indices(dimensions,dtype=intp) returns an array representing a grid
def indices(dimensions, dtype=int_): """indices(dimensions,dtype=int_) returns an array representing a grid
def indices(dimensions, dtype=intp): """indices(dimensions,dtype=intp) returns an array representing a grid of indices with row-only, and column-only variation. """ tmp = ones(dimensions, dtype) lst = [] for i in range(len(dimensions)): lst.append( add.accumulate(tmp, i, )-1 ) return array(lst)
def ones(shape, dtype=intp, fortran=0): """ones(shape, dtype=intp) returns an array of the given
def ones(shape, dtype=int_, fortran=0): """ones(shape, dtype=int_) returns an array of the given
def ones(shape, dtype=intp, fortran=0): """ones(shape, dtype=intp) returns an array of the given dimensions which is initialized to all ones. """ a=zeros(shape, dtype, fortran) a+=1 ### a[...]=1 -- slower? return a
def identity(n,dtype=intp):
def identity(n,dtype=int_):
def identity(n,dtype=intp): """identity(n) returns the identity matrix of shape n x n. """ a = array([1]+n*[0],dtype=dtype) b = empty((n,n),dtype=dtype) b.flat = a return b
results = [string.replace(file,base,'') for file in files]
results = [file[len(base):] for file in files]
def remove_common_base(files): """ Remove the greatest common base directory from all the absolute file paths in the list of files. files in the list without a parent directory are not affected. """ rel_files = filter(lambda x: not os.path.dirname(x),files) abs_files = filter(os.path.dirname,files) base = find_common_...
a = 1
a = 3
def check_exceptions(self): a = 1 code = """ if (a < 2) Py::ValueError("the variable 'a' should not be less than 2"); return_val = Py::new_reference_to(Py::Int(a+1)); """ result = inline_tools.inline(code,['a']) assert(result == 2) try: a = 3 result = inline_tools.inline(code,['a']) assert(1) # should've thrown a Valu...
return_val = Py::new_reference_to(Py::Int(a+1));
else return_val = Py::new_reference_to(Py::Int(a+1));
def check_exceptions(self): a = 1 code = """ if (a < 2) Py::ValueError("the variable 'a' should not be less than 2"); return_val = Py::new_reference_to(Py::Int(a+1)); """ result = inline_tools.inline(code,['a']) assert(result == 2) try: a = 3 result = inline_tools.inline(code,['a']) assert(1) # should've thrown a Valu...
assert(result == 2)
assert(result == 4)
def check_exceptions(self): a = 1 code = """ if (a < 2) Py::ValueError("the variable 'a' should not be less than 2"); return_val = Py::new_reference_to(Py::Int(a+1)); """ result = inline_tools.inline(code,['a']) assert(result == 2) try: a = 3 result = inline_tools.inline(code,['a']) assert(1) # should've thrown a Valu...
a = 3
a = 1
def check_exceptions(self): a = 1 code = """ if (a < 2) Py::ValueError("the variable 'a' should not be less than 2"); return_val = Py::new_reference_to(Py::Int(a+1)); """ result = inline_tools.inline(code,['a']) assert(result == 2) try: a = 3 result = inline_tools.inline(code,['a']) assert(1) # should've thrown a Valu...
'prod', 'std', 'ctypes'
'prod', 'std', 'ctypes', 'itemset'
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'...
if len(a.shape) == 0: a = a.reshape((1,))
if a.ndim == 0: a.shape = (1,)
def _frz(a): """fix rank-0 --> rank-1""" if len(a.shape) == 0: a = a.reshape((1,)) return a
return format % x
if (x < _MAXINT) and (x > _MININT): return format % x else: return "%s" % x
def _formatInteger(x, format): return format % x
return ["-Wl,shared"]
return ["-Wl,-shared"]
def get_flags_linker_so(self): if sys.platform=='darwin': return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress'] return ["-Wl,shared"]
raise ValueError("This machine doesn't have NaNs, "
if NAN != NAN: def isnan(x): return x!= x else: raise ValueError("This machine doesn't have NaNs, "
def isnan(x): """x -> true iff x is a NaN.""" # multiply by 1.0 to create a distinct object (x < x *always* # false in Python, due to object identity forcing equality) if x * 1.0 < x: # it's a NaN and this is MS C on a Pentium return 1 # Else it's non-NaN, or NaN on a non-MS+Pentium combo. # If it's non-NaN, then x == ...
if cpu.has_sse2(): opt = opt + ' -msse2 '
if self.version > '3.2.2': if cpu.has_sse2(): opt = opt + ' -msse2 '
def get_opt(self): import cpuinfo cpu = cpuinfo.cpuinfo() opt = ' -O3 -funroll-loops '
return ','.join([x.strip().lower() for x in b])
return ','.join([x.strip() for x in b])
def conv(astr): b = astr.split(',') return ','.join([x.strip().lower() for x in b])
name = rep[0].strip().lower()
name = rep[0].strip()
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 = conv(rep[1]) _names[name] = thelist substr = named_re.sub(r"<\1>",substr) # get rid o...
maxre = re.compile(r"max[(](.+),(.+)[)]") minre = re.compile(r"min[(](.+),(.+)[)]") def fix_capitals(astr): astr = maxre.sub(r"MAX(\g<1>,\g<2>)",astr) astr = minre.sub(r"MIN(\g<1>,\g<2>)",astr) return astr
def get_line_header(str,beg): extra = [] ind = beg-1 char = str[ind] while (ind > 0) and (char != '\n'): extra.insert(0,char) ind = ind - 1 char = str[ind] return ''.join(extra)
newstr = allstr.lower()
newstr = allstr
def process_str(allstr): newstr = allstr.lower() writestr = _head struct = parse_structure(newstr) # return a (sorted) list of tuples for each function or subroutine # each tuple is the start and end of a subroutine or function to be expanded oldend = 0 for sub in struct: writestr += fix_capitals(newstr[oldend:sub[...
writestr += fix_capitals(newstr[oldend:sub[0]])
writestr += newstr[oldend:sub[0]]
def process_str(allstr): newstr = allstr.lower() writestr = _head struct = parse_structure(newstr) # return a (sorted) list of tuples for each function or subroutine # each tuple is the start and end of a subroutine or function to be expanded oldend = 0 for sub in struct: writestr += fix_capitals(newstr[oldend:sub[...
writestr += fix_capitals(expanded)
writestr += expanded
def process_str(allstr): newstr = allstr.lower() writestr = _head struct = parse_structure(newstr) # return a (sorted) list of tuples for each function or subroutine # each tuple is the start and end of a subroutine or function to be expanded oldend = 0 for sub in struct: writestr += fix_capitals(newstr[oldend:sub[...
writestr += fix_capitals(newstr[oldend:])
writestr += newstr[oldend:]
def process_str(allstr): newstr = allstr.lower() writestr = _head struct = parse_structure(newstr) # return a (sorted) list of tuples for each function or subroutine # each tuple is the start and end of a subroutine or function to be expanded oldend = 0 for sub in struct: writestr += fix_capitals(newstr[oldend:sub[...
>>> deletefrom(arr, 1, 1)
>>> delete(arr, 1, 1)
def delete(arr, obj, axis=None): """Return a new array with sub-arrays along an axis deleted. Return a new array with the sub-arrays (i.e. rows or columns) deleted along the given axis as specified by obj obj may be a slice_object (s_[3:5:2]) or an integer or an array of integers indicated which sub-arrays to remove....
>>> deletefrom(arr, 1, 0)
>>> delete(arr, 1, 0)
def delete(arr, obj, axis=None): """Return a new array with sub-arrays along an axis deleted. Return a new array with the sub-arrays (i.e. rows or columns) deleted along the given axis as specified by obj obj may be a slice_object (s_[3:5:2]) or an integer or an array of integers indicated which sub-arrays to remove....
def check_large(self): x = linspace(-3,2,10000) f = vectorize(lambda x: x) y = f(x) assert_array_equal(y, x)
def addsubtract(a,b): if a > b: return a - b else: return a + b
class test_vectorize( ScipyTestCase ): def check_vectorize( self ): x = linspace(-3,2,10000) f = vectorize(lambda x: x) y = f(x) assert_array_equal(y, x)
def check_simple(self): n=100 v=rand(n) (a,b)=histogram(v) #check if the sum of the bins equals the number of samples assert(sum(a)==n) #check that the bin counts are evenly spaced when the data is from a linear function (a,b)=histogram(linspace(0,10,100)) assert(all(a==10))
def create_dir(p): """ Create a directory and any necessary intermediate directories.""" if not os.path.exists(p): try: os.mkdir(p) except OSError: base,dir = os.path.split(p) create_dir(base) os.mkdir(p) def is_writable(dir): dummy = os.path.join(dir, "dummy") try: open(dummy, 'w') except IOError: return 0 os.unl...
def unique_file(d,expr): """ Generate a unqiue file name based on expr in directory d This is meant for use with building extension modules, so a file name is considered unique if none of the following extension '.cpp','.o','.so','module.so','.py', or '.pyd' exists in directory d. The fully qualified path to the new ...
import tempfile
def default_dir(): """ Return a default location to store compiled files and catalogs. XX is the Python version number in all paths listed below On windows, the default location is the temporary directory returned by gettempdir()/pythonXX. On Unix, ~/.pythonXX_compiled is the default location. If it doesn't exist, i...
path = os.path.join(tempfile.gettempdir(),python_name)
path = os.path.join(tempfile.gettempdir(),"%s"%whoami(),python_name)
def default_dir(): """ Return a default location to store compiled files and catalogs. XX is the Python version number in all paths listed below On windows, the default location is the temporary directory returned by gettempdir()/pythonXX. On Unix, ~/.pythonXX_compiled is the default location. If it doesn't exist, i...
os.mkdir(path)
create_dir(path)
def default_dir(): """ Return a default location to store compiled files and catalogs. XX is the Python version number in all paths listed below On windows, the default location is the temporary directory returned by gettempdir()/pythonXX. On Unix, ~/.pythonXX_compiled is the default location. If it doesn't exist, i...
if not os.access(path,os.W_OK):
if not is_writable(path):
def default_dir(): """ Return a default location to store compiled files and catalogs. XX is the Python version number in all paths listed below On windows, the default location is the temporary directory returned by gettempdir()/pythonXX. On Unix, ~/.pythonXX_compiled is the default location. If it doesn't exist, i...
print 'defualt:', path
print 'default:', path
def default_dir(): """ Return a default location to store compiled files and catalogs. XX is the Python version number in all paths listed below On windows, the default location is the temporary directory returned by gettempdir()/pythonXX. On Unix, ~/.pythonXX_compiled is the default location. If it doesn't exist, i...
import tempfile
def intermediate_dir(): """ Location in temp dir for storing .cpp and .o files during builds. """ import tempfile python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2]) path = os.path.join(tempfile.gettempdir(),python_name) if not os.path.exists(path): os.mkdir(path) return path
path = os.path.join(tempfile.gettempdir(),python_name)
path = os.path.join(tempfile.gettempdir(),"%s"%whoami(),python_name)
def intermediate_dir(): """ Location in temp dir for storing .cpp and .o files during builds. """ import tempfile python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2]) path = os.path.join(tempfile.gettempdir(),python_name) if not os.path.exists(path): os.mkdir(path) return path
os.mkdir(path)
create_dir(path)
def intermediate_dir(): """ Location in temp dir for storing .cpp and .o files during builds. """ import tempfile python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2]) path = os.path.join(tempfile.gettempdir(),python_name) if not os.path.exists(path): os.mkdir(path) return path
os.mkdir(path)
create_dir(path)
def default_temp_dir(): path = os.path.join(default_dir(),'temp') if not os.path.exists(path): os.mkdir(path) os.chmod(path,0700) # make it only accessible by this user. if not os.access(path,os.W_OK): print 'warning: default directory is not write accessible.' print 'defualt:', path return path
if not os.access(path,os.W_OK):
if not is_writable(path):
def default_temp_dir(): path = os.path.join(default_dir(),'temp') if not os.path.exists(path): os.mkdir(path) os.chmod(path,0700) # make it only accessible by this user. if not os.access(path,os.W_OK): print 'warning: default directory is not write accessible.' print 'defualt:', path return path
print 'defualt:', path
print 'default:', path
def default_temp_dir(): path = os.path.join(default_dir(),'temp') if not os.path.exists(path): os.mkdir(path) os.chmod(path,0700) # make it only accessible by this user. if not os.access(path,os.W_OK): print 'warning: default directory is not write accessible.' print 'defualt:', path return path
print sys.path
def generate_array_api(ext,build_dir): target = join(build_dir,'__multiarray_api.h') script = join(codegen_dir,'generate_array_api.py') if newer(script,target): old_sys_path = sys.path try: sys.path.insert(0, codegen_dir) print sys.path import generate_array_api print 'executing',script generate_array_api.generate_api(...
self.f90_fixed_switch = ''
def __init__(self,verbose=0,dry_run=0,force=0): # Default initialization. Constructors of derived classes MUST # call this function. CCompiler.__init__(self,verbose,dry_run,force)
files = string.join(dirty_files) f90_files = get_f90_files(dirty_files) f77_files = get_f77_files(dirty_files) if f90_files != []: obj1 = self.f90_compile(f90_files,module_dirs,temp_dir = temp_dir) else: obj1 = [] if f77_files != []: obj2 = self.f77_compile(f77_files, temp_dir = temp_dir) else: obj2 = [] return obj1 + ...
f77_files,f90_fixed_files,f90_files = [],[],[] objects = [] for f in dirty_files: if is_f_file(f): f77_files.append(f) elif is_free_format(f): f90_files.append(f) else: f90_fixed_files.append(f) if f77_files: objects.extend(\ self.f77_compile(f77_files,temp_dir=temp_dir)) if f90_fixed_files: objects.extend(\ self....
def to_object(self, dirty_files, module_dirs=None, temp_dir=''): files = string.join(dirty_files) f90_files = get_f90_files(dirty_files) f77_files = get_f77_files(dirty_files) if f90_files != []: obj1 = self.f90_compile(f90_files,module_dirs,temp_dir = temp_dir) else: obj1 = [] if f77_files != []: obj2 = self.f77_compi...
self.f90_switches = '-f fixed -YCFRL=1 -YCOM_NAMES=LCS' \
self.f90_switches = '-YCFRL=1 -YCOM_NAMES=LCS' \
def __init__(self, fc=None, f90c=None, verbose=0): fortran_compiler_base.__init__(self, verbose=verbose)
cmd = self.f90_compiler + ' -dryrun __dummy.f'
dummy_file = self.dummy_fortran_files()[0] cmd = self.f90_compiler + ' -dryrun ' + dummy_file
def find_lib_dir(self): library_dirs = ["/opt/SUNWspro/prod/lib"] lib_match = r'### f90: Note: LD_RUN_PATH\s*= '\ '(?P<lib_paths>[^\s.]*).*' cmd = self.f90_compiler + ' -dryrun __dummy.f' self.announce(yellow_text(cmd)) exit_status, output = run_command(cmd) if not exit_status: libs = re.findall(lib_match,output) if li...
self.f90_switches = ' -n32 -KPIC -fixedform '
self.f90_switches = ' -n32 -KPIC '
def __init__(self, fc=None, f90c=None, verbose=0): fortran_compiler_base.__init__(self, verbose=verbose)
self.f90_switches = gnu.f77_switches self.f90_debug = gnu.f77_debug self.f90_opt = gnu.f77_opt self.f90_fixed_switch = ' -Wv,-ya '
def __init__(self, fc=None, f90c=None, verbose=0): fortran_compiler_base.__init__(self, verbose=verbose)
def match_extension(files,ext): match = re.compile(r'.*[.]('+ext+r')\Z',re.I).match return filter(lambda x,match = match: match(x),files) def get_f77_files(files): return match_extension(files,'for|f77|ftn|f') def get_f90_files(files): return match_extension(files,'f90|f95') def get_fortran_files(files): return matc...
def get_opt(self): # XXX: use also /architecture, see gnu_fortran_compiler return ' /Ox '
for key, value in _flagdict.items():
for key in _flagnames: value = _flagdict[key]
def _flags_fromnum(num): res = [] for key, value in _flagdict.items(): if (num & value): res.append(key) return res
nn = map(lambda x,t: arange(x,typecode=t),size,(typecode,)*len(size))
nn = map(lambda x,t: Numeric.arange(x,typecode=t),size,(typecode,)*len(size))
def __getitem__(self,key): try: size = [] typecode = Numeric.Int for k in range(len(key)): step = key[k].step start = key[k].start if start is None: start = 0 if step is None: step = 1 if type(step) is type(1j): size.append(int(abs(step))) typecode = Numeric.Float else: size.append(int((key[k].stop - start)/(step*1.0))...
slobj = [NewAxis]*len(size)
slobj = [Numeric.NewAxis]*len(size)
def __getitem__(self,key): try: size = [] typecode = Numeric.Int for k in range(len(key)): step = key[k].step start = key[k].start if start is None: start = 0 if step is None: step = 1 if type(step) is type(1j): size.append(int(abs(step))) typecode = Numeric.Float else: size.append(int((key[k].stop - start)/(step*1.0))...
slobj[k] = NewAxis
slobj[k] = Numeric.NewAxis
def __getitem__(self,key): try: size = [] typecode = Numeric.Int for k in range(len(key)): step = key[k].step start = key[k].start if start is None: start = 0 if step is None: step = 1 if type(step) is type(1j): size.append(int(abs(step))) typecode = Numeric.Float else: size.append(int((key[k].stop - start)/(step*1.0))...
zr = NX.zeros(diff, a1)
zr = NX.zeros(diff, a1.dtype)
def polysub(a1, a2): """Subtracts two polynomials represented as sequences """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: return a1 - a2 elif diff > 0: zr = NX.zeros(diff, a1) val = NX.concatenate((zr, a1)) - a2 else: zr =...
zr = NX.zeros(abs(diff), a2)
zr = NX.zeros(abs(diff), a2.dtype)
def polysub(a1, a2): """Subtracts two polynomials represented as sequences """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: return a1 - a2 elif diff > 0: zr = NX.zeros(diff, a1) val = NX.concatenate((zr, a1)) - a2 else: zr =...
if moredefs: target_f = open(target,'a') for d in moredefs: if isinstance(d,str): target_f.write(' else: target_f.write(' if not nosmp: target_f.write(' target_f.close()
target_f = open(target,'a') for d in moredefs: if isinstance(d,str): target_f.write(' else: target_f.write(' if not nosmp: target_f.write(' target_f.close()
def check_func(func_name): return config_cmd.check_func(func_name, libraries=mathlibs, decl=False, headers=['math.h'])
if base != string.split(ext.name,'.')[-1]:
if base != ext_name:
def f2py_sources (self, sources, ext):
pyf_target = os.path.join(target_dir,ext.name+'.pyf') pyf_target_file = os.path.join(target_dir,ext.name+target_ext) pyf_fortran_target_file = os.path.join(target_dir,ext.name+fortran_target_ext) f2py_opts2 = ['-m',ext.name,'-h',pyf_target,'--overwrite-signature']
pyf_target = os.path.join(target_dir,ext_name+'.pyf') pyf_target_file = os.path.join(target_dir,ext_name+target_ext) pyf_fortran_target_file = os.path.join(target_dir,ext_name+fortran_target_ext) f2py_opts2 = ['-m',ext_name,'-h',pyf_target,'--overwrite-signature']
def f2py_sources (self, sources, ext):
self.announce("f2py-opts: %s" % string.join(f2py_opts2,' '))
self.announce("f2py-opts: %s" % \ string.join(f2py_opts2,' '))
def f2py_sources (self, sources, ext):
name = ext.name
ext_name = string.split(ext.name,'.')[-1] name = ext_name
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 = []
def eye(N,M=None, k=0, dtype=float): return asmatrix(N.eye(N,M,k,dtype))
def eye(n,M=None, k=0, dtype=float): return asmatrix(N.eye(n,M,k,dtype))
def eye(N,M=None, k=0, dtype=float): return asmatrix(N.eye(N,M,k,dtype))
md = make_mask(umath.less_equal (fa, 0), flag=1)
md = make_mask(umath.less(fa, 0), flag=1)
def power (a, b, third=None): "a**b" if third is not None: raise MAError, "3-argument power not supported." ma = getmask(a) mb = getmask(b) m = mask_or(ma, mb) fa = filled(a, 1) fb = filled(b, 1) if fb.dtype.char in typecodes["Integer"]: return masked_array(umath.power(fa, fb), m) md = make_mask(umath.less_equal (fa, 0...
config.add_subpackage('numarray')
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numpy',parent_package,top_path) config.add_subpackage('distutils') config.add_subpackage('testing') config.add_subpackage('f2py') config.add_subpackage('core') config.add_subpackage('lib') con...
self.failUnlessRaises(TypeError, assign, a, (), '')
self.failUnlessRaises(ValueError, assign, a, (), '')
def assign(x, i, v): x[i] = v
def add_extra_compile_args(self,compile_arg):
def add_extra_compile_arg(self,compile_arg):
def add_extra_compile_args(self,compile_arg): return self._extra_compile_args.append(compile_arg)
def add_extra_link_args(self,link_arg):
def add_extra_link_arg(self,link_arg):
def add_extra_link_args(self,link_arg): return self._extra_link_args.append(link_arg)
prune_file_pat = re.compile(r'(?:^\..*|[~
prune_file_pat = re.compile(r'(?:[~
def general_source_files(top_path): pruned_directories = {'CVS':1, '.svn':1, 'build':1} prune_file_pat = re.compile(r'(?:^\..*|[~#]|\.py[co]|\.o)$') for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): pruned = [ d for d in dirnames if d not in pruned_directories ] dirnames[:] = pruned for f in filename...
prune_file_pat = re.compile(r'(?:^\..*|[~
prune_file_pat = re.compile(r'(?:[~
def general_source_directories_files(top_path): """ Return a directory name relative to top_path and files contained. """ pruned_directories = ['CVS','.svn','build'] prune_file_pat = re.compile(r'(?:^\..*|[~#]|\.py[co]|\.o)$') for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): pruned = [ d for d in di...
ld_args = (objects + self.objects + lib_opts + o_args)
if type(self.objects) is type(''): ld_args = objects + [self.objects] else: ld_args = objects + self.objects ld_args = ld_args + lib_opts + o_args
def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): objects, output_dir = self._fix_object_args(objects, output_dir) libraries, libr...
dirs.extend([d] + combine_paths(d,['atlas*','ATLAS*']))
dirs.extend(combine_paths(d,['atlas*','ATLAS*']) + [d])
def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + combine_paths(d,['atlas*','ATLAS*'])) return [ d for d in dirs if os.path.isdir(d) ]
if sys.platform == 'win32': self.libraries = ['gcc','g2c'] self.library_dirs = self.find_lib_directories() else: self.libraries = ['g2c']
def __init__(self, fc = None, f90c = None): fortran_compiler_base.__init__(self) if sys.platform == 'win32': self.libraries = ['gcc','g2c'] self.library_dirs = self.find_lib_directories() else: # On linux g77 does not need lib_directories to be specified. self.libraries = ['g2c']
switches = switches + ' -fpic '
switches = switches + ' -fPIC '
def __init__(self, fc = None, f90c = None): fortran_compiler_base.__init__(self) if sys.platform == 'win32': self.libraries = ['gcc','g2c'] self.library_dirs = self.find_lib_directories() else: # On linux g77 does not need lib_directories to be specified. self.libraries = ['g2c']
if self.version[0]=='3':
if self.version >= '0.5.26':
def get_opt(self): import cpuinfo cpu = cpuinfo.cpuinfo() opt = ' -O3 -funroll-loops ' # only check for more optimization if g77 can handle # it. if self.get_version(): if self.version[0]=='3': # is g77 3.x.x if cpu.is_AthlonK6(): opt = opt + ' -march=k6 ' elif cpu.is_AthlonK7(): opt = opt + ' -march=athlon ' if cpu.i...
lib_dir= m return lib_dir
assert len(m)==1,`m` self.gcc_lib_dir = m return self.gcc_lib_dir
def find_lib_directories(self): lib_dir = [] match = r'Reading specs from (.*)/specs'
ver_match = r'f77: (?P<version>[^\s*,]*)'
ver_match = r'f90: Sun (?P<version>[^\s*,]*)'
def get_extra_link_args(self): return [] # Couldn't get this to link for anything using gcc. #dr = "c:\\Absoft62\\lib" #libs = ['fio.lib', 'COMDLG32.lib','fmath.lib', 'f90math.lib','libcomdlg32.a' ] #libs = map(lambda x,dr=dr:os.path.join(dr,x),libs) #return libs
self.libraries = ['f90', 'F77', 'M77', 'sunmath', 'm']
self.ver_cmd = self.f90_compiler + ' -V' self.libraries = ['fsu', 'F77', 'M77', 'sunmath', 'm']
def __init__(self, fc = None, f90c = None): fortran_compiler_base.__init__(self) if fc is None: fc = 'f77' if f90c is None: f90c = 'f90'
self.ver_cmd = self.f77_compiler + ' -V'
def __init__(self, fc = None, f90c = None): fortran_compiler_base.__init__(self) if fc is None: fc = 'f77' if f90c is None: f90c = 'f90'
self.ver_cmd = self.f77_compiler + ' -version'
def __init__(self, fc = None, f90c = None): fortran_compiler_base.__init__(self) if fc is None: fc = 'f77' if f90c is None: f90c = 'f90'
""" Manages loading NumPy packages.
""" Manages loading packages.
def __init__(self, verbose=False): """ Manages loading NumPy packages. """
"""Load one or more packages into numpy's top-level namespace.
"""Load one or more packages into parent package top-level namespace.
def __call__(self,*packages, **options): """Load one or more packages into numpy's top-level namespace.
This function is intended to shorten the need to import many of numpy's submodules constantly with statements such as import numpy.linalg, numpy.dft, numpy.etc...
This function is intended to shorten the need to import many of subpackages, say of scipy, constantly with statements such as import scipy.linalg, scipy.fftpack, scipy.etc...
def __call__(self,*packages, **options): """Load one or more packages into numpy's top-level namespace.
import numpy numpy.pkgload('linalg','dft',...)
import scipy scipy.pkgload('linalg','fftpack',...)
def __call__(self,*packages, **options): """Load one or more packages into numpy's top-level namespace.
numpy.pkgload()
scipy.pkgload()
def __call__(self,*packages, **options): """Load one or more packages into numpy's top-level namespace.