msc_pos = sys.version.find('<STR_LIT>')<EOL>if msc_pos != -<NUM_LIT:1>:<EOL><INDENT>msc_ver = sys.version[msc_pos+<NUM_LIT:6>:msc_pos+<NUM_LIT:10>]<EOL>lib = {'<STR_LIT>': '<STR_LIT>',    <EOL>'<STR_LIT>': '<STR_LIT>',    <EOL>'<STR_LIT>': '<STR_LIT>',    <EOL>'<STR_LIT>': '<STR_LIT>',    <EOL>'<STR_LIT>': '<STR_LIT>',   <EOL>}.get(msc_ver, None)<EOL><DEDENT>else:<EOL><INDENT>lib = None<EOL><DEDENT>return lib<EOL>

Return name of MSVC runtime library if Python was built with MSVC >= 7


if not f90_ext_match(source):<EOL><INDENT>return []<EOL><DEDENT>modules = []<EOL>f = open(source, '<STR_LIT:r>')<EOL>for line in f:<EOL><INDENT>m = f90_module_name_match(line)<EOL>if m:<EOL><INDENT>name = m.group('<STR_LIT:name>')<EOL>modules.append(name)<EOL><DEDENT><DEDENT>f.close()<EOL>return modules<EOL>

Return a list of Fortran f90 module names that
    given source file defines.


for item in lst:<EOL><INDENT>if not is_string(item):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

Return True if all items in lst are string objects.


language = None<EOL>for source in sources:<EOL><INDENT>if isinstance(source, str):<EOL><INDENT>if f90_ext_match(source):<EOL><INDENT>language = '<STR_LIT>'<EOL>break<EOL><DEDENT>elif fortran_ext_match(source):<EOL><INDENT>language = '<STR_LIT>'<EOL><DEDENT><DEDENT><DEDENT>return language<EOL>

Determine language value (c,f77,f90) from sources


for source in sources:<EOL><INDENT>if fortran_ext_match(source):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Return True if sources contains Fortran files


for source in sources:<EOL><INDENT>if cxx_ext_match(source):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Return True if sources contains C++ files


c_sources = []<EOL>cxx_sources = []<EOL>f_sources = []<EOL>fmodule_sources = []<EOL>for source in sources:<EOL><INDENT>if fortran_ext_match(source):<EOL><INDENT>modules = _get_f90_modules(source)<EOL>if modules:<EOL><INDENT>fmodule_sources.append(source)<EOL><DEDENT>else:<EOL><INDENT>f_sources.append(source)<EOL><DEDENT><DEDENT>elif cxx_ext_match(source):<EOL><INDENT>cxx_sources.append(source)<EOL><DEDENT>else:<EOL><INDENT>c_sources.append(source)<EOL><DEDENT><DEDENT>return c_sources, cxx_sources, f_sources, fmodule_sources<EOL>

Return four lists of filenames containing
    C, C++, Fortran, and Fortran 90 module sources,
    respectively.


if not is_string(directory):<EOL><INDENT>return False<EOL><DEDENT>abs_dir = os.path.abspath(directory)<EOL>c = os.path.commonprefix([os.getcwd(), abs_dir])<EOL>new_dir = abs_dir[len(c):].split(os.sep)<EOL>if new_dir and not new_dir[<NUM_LIT:0>]:<EOL><INDENT>new_dir = new_dir[<NUM_LIT:1>:]<EOL><DEDENT>if new_dir and new_dir[<NUM_LIT:0>]=='<STR_LIT>':<EOL><INDENT>return False<EOL><DEDENT>new_dir = os.sep.join(new_dir)<EOL>return os.path.isdir(new_dir)<EOL>

Return true if directory is local directory.


pruned_directories = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>prune_file_pat = re.compile(r'<STR_LIT>')<EOL>for dirpath, dirnames, filenames in os.walk(top_path, topdown=True):<EOL><INDENT>pruned = [ d for d in dirnames if d not in pruned_directories ]<EOL>dirnames[:] = pruned<EOL>for d in dirnames:<EOL><INDENT>dpath = os.path.join(dirpath, d)<EOL>rpath = rel_path(dpath, top_path)<EOL>files = []<EOL>for f in os.listdir(dpath):<EOL><INDENT>fn = os.path.join(dpath, f)<EOL>if os.path.isfile(fn) and not prune_file_pat.search(fn):<EOL><INDENT>files.append(fn)<EOL><DEDENT><DEDENT>yield rpath, files<EOL><DEDENT><DEDENT>dpath = top_path<EOL>rpath = rel_path(dpath, top_path)<EOL>filenames = [os.path.join(dpath, f) for f in os.listdir(dpath)if not prune_file_pat.search(f)]<EOL>files = [f for f in filenames if os.path.isfile(f)]<EOL>yield rpath, files<EOL>

Return a directory name relative to top_path and
    files contained.


confvars = distutils.sysconfig.get_config_vars()<EOL>so_ext = confvars.get('<STR_LIT>', None)<EOL>if so_ext is None:<EOL><INDENT>so_ext = confvars.get('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>if not is_python_ext:<EOL><INDENT>if (sys.platform.startswith('<STR_LIT>') or<EOL>sys.platform.startswith('<STR_LIT>')):<EOL><INDENT>so_ext = '<STR_LIT>'<EOL><DEDENT>elif sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>so_ext = '<STR_LIT>'<EOL><DEDENT>elif sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>so_ext = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>if '<STR_LIT>' in confvars:<EOL><INDENT>so_ext = so_ext.replace('<STR_LIT:.>' + confvars.get('<STR_LIT>'), '<STR_LIT>', <NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>return so_ext<EOL>

Return the correct file extension for shared libraries.

    Parameters
    ----------
    is_python_ext : bool, optional
        Whether the shared library is a Python extension.  Default is False.

    Returns
    -------
    so_ext : str
        The shared library extension.

    Notes
    -----
    For Python shared libs, `so_ext` will typically be '.so' on Linux and OS X,
    and '.pyd' on Windows.  For Python >= 3.2 `so_ext` has a tag prepended on
    POSIX systems according to PEP 3149.  For Python 3.2 this is implemented on
    Linux, but not on OS X.


try:<EOL><INDENT>return sys._getframe(level+<NUM_LIT:1>)<EOL><DEDENT>except AttributeError:<EOL><INDENT>frame = sys.exc_info()[<NUM_LIT:2>].tb_frame<EOL>for _ in range(level+<NUM_LIT:1>):<EOL><INDENT>frame = frame.f_back<EOL><DEDENT>return frame<EOL><DEDENT>

Return frame object from call stack with given level.


<EOL>import numpy<EOL>d = os.path.join(os.path.dirname(numpy.__file__),<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>return d<EOL>

Return the path where to find the npy-pkg-config directory.


from numpy.distutils.npy_pkg_config import read_config<EOL>if dirs:<EOL><INDENT>dirs.append(get_npy_pkg_dir())<EOL><DEDENT>else:<EOL><INDENT>dirs = [get_npy_pkg_dir()]<EOL><DEDENT>return read_config(pkgname, dirs)<EOL>

Return library info for the given package.

Parameters
----------
pkgname : str
    Name of the package (should match the name of the .ini file, without
    the extension, e.g. foo for the file foo.ini).
dirs : sequence, optional
    If given, should be a sequence of additional directories where to look
    for npy-pkg-config files. Those directories are searched prior to the
    NumPy directory.

Returns
-------
pkginfo : class instance
    The `LibraryInfo` instance containing the build information.

Raises
------
PkgNotFound
    If the package is not found.

See Also
--------
Configuration.add_npy_pkg_config, Configuration.add_installed_library,
get_info


from numpy.distutils.npy_pkg_config import parse_flags<EOL>pkg_info = get_pkg_info(pkgname, dirs)<EOL>info = parse_flags(pkg_info.cflags())<EOL>for k, v in parse_flags(pkg_info.libs()).items():<EOL><INDENT>info[k].extend(v)<EOL><DEDENT>info['<STR_LIT>'] = info['<STR_LIT>']<EOL>del info['<STR_LIT>']<EOL>del info['<STR_LIT>']<EOL>return info<EOL>

Return an info dict for a given C library.

The info dict contains the necessary options to use the C library.

Parameters
----------
pkgname : str
    Name of the package (should match the name of the .ini file, without
    the extension, e.g. foo for the file foo.ini).
dirs : sequence, optional
    If given, should be a sequence of additional directories where to look
    for npy-pkg-config files. Those directories are searched prior to the
    NumPy directory.

Returns
-------
info : dict
    The dictionary with build information.

Raises
------
PkgNotFound
    If the package is not found.

See Also
--------
Configuration.add_npy_pkg_config, Configuration.add_installed_library,
get_pkg_info

Examples
--------
To get the necessary information for the npymath library from NumPy:

>>> npymath_info = np.distutils.misc_util.get_info('npymath')
>>> npymath_info                                    #doctest: +SKIP
{'define_macros': [], 'libraries': ['npymath'], 'library_dirs':
['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']}

This info dict can then be used as input to a `Configuration` instance::

  config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)


def default_config_dict(name = None, parent_name = None, local_path=None):

import warnings<EOL>warnings.warn('<STR_LIT>''<STR_LIT>'<EOL>% (name, parent_name, local_path,<EOL>name, parent_name, local_path,<EOL>))<EOL>c = Configuration(name, parent_name, local_path)<EOL>return c.todict()<EOL>

Return a configuration dictionary for usage in
    configuration() function defined in file setup_<name>.py.


from numpy.distutils.system_info import system_info<EOL>from distutils.dir_util import mkpath<EOL>mkpath(os.path.dirname(target))<EOL>f = open(target, '<STR_LIT:w>')<EOL>f.write('<STR_LIT>' % (os.path.abspath(sys.argv[<NUM_LIT:0>])))<EOL>f.write('<STR_LIT>')<EOL>f.write('<STR_LIT>')<EOL>for k, i in system_info.saved_results.items():<EOL><INDENT>f.write('<STR_LIT>' % (k, i))<EOL><DEDENT>f.write(r'''<STR_LIT>''')<EOL>f.close()<EOL>return target<EOL>

Generate config.py file containing system_info information
    used during building the package.

    Usage:
        config['py_modules'].append((packagename, '__config__',generate_config_py))


if not compiler.compiler_type == "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>"% compiler.compiler_type)<EOL><DEDENT>return compiler._MSVCCompiler__version<EOL>

Return version major and minor of compiler instance if it is
    MSVC, raise an exception otherwise.


self.name = dot_join(parent_name, package_name)<EOL>self.version = None<EOL>caller_frame = get_frame(caller_level)<EOL>self.local_path = get_path_from_frame(caller_frame, top_path)<EOL>if top_path is None:<EOL><INDENT>top_path = self.local_path<EOL>self.local_path = '<STR_LIT>'<EOL><DEDENT>if package_path is None:<EOL><INDENT>package_path = self.local_path<EOL><DEDENT>elif os.path.isdir(njoin(self.local_path, package_path)):<EOL><INDENT>package_path = njoin(self.local_path, package_path)<EOL><DEDENT>if not os.path.isdir(package_path or '<STR_LIT:.>'):<EOL><INDENT>raise ValueError("<STR_LIT>" % (package_path,))<EOL><DEDENT>self.top_path = top_path<EOL>self.package_path = package_path<EOL>self.path_in_package = os.path.join(*self.name.split('<STR_LIT:.>'))<EOL>self.list_keys = self._list_keys[:]<EOL>self.dict_keys = self._dict_keys[:]<EOL>for n in self.list_keys:<EOL><INDENT>v = copy.copy(attrs.get(n, []))<EOL>setattr(self, n, as_list(v))<EOL><DEDENT>for n in self.dict_keys:<EOL><INDENT>v = copy.copy(attrs.get(n, {}))<EOL>setattr(self, n, v)<EOL><DEDENT>known_keys = self.list_keys + self.dict_keys<EOL>self.extra_keys = self._extra_keys[:]<EOL>for n in attrs.keys():<EOL><INDENT>if n in known_keys:<EOL><INDENT>continue<EOL><DEDENT>a = attrs[n]<EOL>setattr(self, n, a)<EOL>if isinstance(a, list):<EOL><INDENT>self.list_keys.append(n)<EOL><DEDENT>elif isinstance(a, dict):<EOL><INDENT>self.dict_keys.append(n)<EOL><DEDENT>else:<EOL><INDENT>self.extra_keys.append(n)<EOL><DEDENT><DEDENT>if os.path.exists(njoin(package_path, '<STR_LIT>')):<EOL><INDENT>self.packages.append(self.name)<EOL>self.package_dir[self.name] = package_path<EOL><DEDENT>self.options = dict(<EOL>ignore_setup_xxx_py = False,<EOL>assume_default_configuration = False,<EOL>delegate_options_to_subpackages = False,<EOL>quiet = False,<EOL>)<EOL>caller_instance = None<EOL>for i in range(<NUM_LIT:1>, <NUM_LIT:3>):<EOL><INDENT>try:<EOL><INDENT>f = get_frame(i)<EOL><DEDENT>except ValueError:<EOL><INDENT>break<EOL><DEDENT>try:<EOL><INDENT>caller_instance = eval('<STR_LIT>', f.f_globals, f.f_locals)<EOL>break<EOL><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if isinstance(caller_instance, self.__class__):<EOL><INDENT>if caller_instance.options['<STR_LIT>']:<EOL><INDENT>self.set_options(**caller_instance.options)<EOL><DEDENT><DEDENT>self.setup_name = setup_name<EOL>

Construct configuration instance of a package.

        package_name -- name of the package
                        Ex.: 'distutils'
        parent_name  -- name of the parent package
                        Ex.: 'numpy'
        top_path     -- directory of the toplevel package
                        Ex.: the directory where the numpy package source sits
        package_path -- directory of package. Will be computed by magic from the
                        directory of the caller module if not specified
                        Ex.: the directory where numpy.distutils is
        caller_level -- frame level to caller namespace, internal parameter.


self._optimize_data_files()<EOL>d = {}<EOL>known_keys = self.list_keys + self.dict_keys + self.extra_keys<EOL>for n in known_keys:<EOL><INDENT>a = getattr(self, n)<EOL>if a:<EOL><INDENT>d[n] = a<EOL><DEDENT><DEDENT>return d<EOL>

Return a dictionary compatible with the keyword arguments of distutils
setup function.

Examples
--------
>>> setup(**config.todict())                           #doctest: +SKIP


for key, value in options.items():<EOL><INDENT>if key in self.options:<EOL><INDENT>self.options[key] = value<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'+key)<EOL><DEDENT><DEDENT>

Configure Configuration instance.

The following options are available:
 - ignore_setup_xxx_py
 - assume_default_configuration
 - delegate_options_to_subpackages
 - quiet


from numpy.distutils.core import get_distribution<EOL>return get_distribution()<EOL>

Return the distutils distribution object for self.


if subpackage_name is None:<EOL><INDENT>if subpackage_path is None:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>subpackage_name = os.path.basename(subpackage_path)<EOL><DEDENT>l = subpackage_name.split('<STR_LIT:.>')<EOL>if subpackage_path is None and '<STR_LIT:*>' in subpackage_name:<EOL><INDENT>return self._wildcard_get_subpackage(subpackage_name,<EOL>parent_name,<EOL>caller_level = caller_level+<NUM_LIT:1>)<EOL><DEDENT>assert '<STR_LIT:*>' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name))<EOL>if subpackage_path is None:<EOL><INDENT>subpackage_path = njoin([self.local_path] + l)<EOL><DEDENT>else:<EOL><INDENT>subpackage_path = njoin([subpackage_path] + l[:-<NUM_LIT:1>])<EOL>subpackage_path = self.paths([subpackage_path])[<NUM_LIT:0>]<EOL><DEDENT>setup_py = njoin(subpackage_path, self.setup_name)<EOL>if not self.options['<STR_LIT>']:<EOL><INDENT>if not os.path.isfile(setup_py):<EOL><INDENT>setup_py = njoin(subpackage_path,<EOL>'<STR_LIT>' % (subpackage_name))<EOL><DEDENT><DEDENT>if not os.path.isfile(setup_py):<EOL><INDENT>if not self.options['<STR_LIT>']:<EOL><INDENT>self.warn('<STR_LIT>''<STR_LIT>'% (os.path.dirname(setup_py), subpackage_name))<EOL><DEDENT>config = Configuration(subpackage_name, parent_name,<EOL>self.top_path, subpackage_path,<EOL>caller_level = caller_level+<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>config = self._get_configuration_from_setup_py(<EOL>setup_py,<EOL>subpackage_name,<EOL>subpackage_path,<EOL>parent_name,<EOL>caller_level = caller_level + <NUM_LIT:1>)<EOL><DEDENT>if config:<EOL><INDENT>return [config]<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT>

Return list of subpackage configurations.

        Parameters
        ----------
        subpackage_name : str or None
            Name of the subpackage to get the configuration. '*' in
            subpackage_name is handled as a wildcard.
        subpackage_path : str
            If None, then the path is assumed to be the local path plus the
            subpackage_name. If a setup.py file is not found in the
            subpackage_path, then a default configuration is used.
        parent_name : str
            Parent name.


def add_subpackage(self,subpackage_name,<EOL>subpackage_path=None,<EOL>standalone = False):

if standalone:<EOL><INDENT>parent_name = None<EOL><DEDENT>else:<EOL><INDENT>parent_name = self.name<EOL><DEDENT>config_list = self.get_subpackage(subpackage_name, subpackage_path,<EOL>parent_name = parent_name,<EOL>caller_level = <NUM_LIT:2>)<EOL>if not config_list:<EOL><INDENT>self.warn('<STR_LIT>')<EOL><DEDENT>for config in config_list:<EOL><INDENT>d = config<EOL>if isinstance(config, Configuration):<EOL><INDENT>d = config.todict()<EOL><DEDENT>assert isinstance(d, dict), repr(type(d))<EOL>self.info('<STR_LIT>'% (d.get('<STR_LIT:name>'), self.name))<EOL>self.dict_append(**d)<EOL><DEDENT>dist = self.get_distribution()<EOL>if dist is not None:<EOL><INDENT>self.warn('<STR_LIT>''<STR_LIT>'+ subpackage_name)<EOL><DEDENT>

Add a sub-package to the current Configuration instance.

        This is useful in a setup.py script for adding sub-packages to a
        package.

        Parameters
        ----------
        subpackage_name : str
            name of the subpackage
        subpackage_path : str
            if given, the subpackage path such as the subpackage is in
            subpackage_path / subpackage_name. If None,the subpackage is
            assumed to be located in the local path / subpackage_name.
        standalone : bool


if is_sequence(data_path):<EOL><INDENT>d, data_path = data_path<EOL><DEDENT>else:<EOL><INDENT>d = None<EOL><DEDENT>if is_sequence(data_path):<EOL><INDENT>[self.add_data_dir((d, p)) for p in data_path]<EOL>return<EOL><DEDENT>if not is_string(data_path):<EOL><INDENT>raise TypeError("<STR_LIT>" % (data_path,))<EOL><DEDENT>if d is None:<EOL><INDENT>if os.path.isabs(data_path):<EOL><INDENT>return self.add_data_dir((os.path.basename(data_path), data_path))<EOL><DEDENT>return self.add_data_dir((data_path, data_path))<EOL><DEDENT>paths = self.paths(data_path, include_non_existing=False)<EOL>if is_glob_pattern(data_path):<EOL><INDENT>if is_glob_pattern(d):<EOL><INDENT>pattern_list = allpath(d).split(os.sep)<EOL>pattern_list.reverse()<EOL>rl = list(range(len(pattern_list)-<NUM_LIT:1>)); rl.reverse()<EOL>for i in rl:<EOL><INDENT>if not pattern_list[i]:<EOL><INDENT>del pattern_list[i]<EOL><DEDENT><DEDENT>for path in paths:<EOL><INDENT>if not os.path.isdir(path):<EOL><INDENT>print('<STR_LIT>', path)<EOL>continue<EOL><DEDENT>rpath = rel_path(path, self.local_path)<EOL>path_list = rpath.split(os.sep)<EOL>path_list.reverse()<EOL>target_list = []<EOL>i = <NUM_LIT:0><EOL>for s in pattern_list:<EOL><INDENT>if is_glob_pattern(s):<EOL><INDENT>if i>=len(path_list):<EOL><INDENT>raise ValueError('<STR_LIT>'% (d, path))<EOL><DEDENT>target_list.append(path_list[i])<EOL><DEDENT>else:<EOL><INDENT>assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath))<EOL>target_list.append(s)<EOL><DEDENT>i += <NUM_LIT:1><EOL><DEDENT>if path_list[i:]:<EOL><INDENT>self.warn('<STR_LIT>'% (pattern_list, path_list))<EOL><DEDENT>target_list.reverse()<EOL>self.add_data_dir((os.sep.join(target_list), path))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for path in paths:<EOL><INDENT>self.add_data_dir((d, path))<EOL><DEDENT><DEDENT>return<EOL><DEDENT>assert not is_glob_pattern(d), repr(d)<EOL>dist = self.get_distribution()<EOL>if dist is not None and dist.data_files is not None:<EOL><INDENT>data_files = dist.data_files<EOL><DEDENT>else:<EOL><INDENT>data_files = self.data_files<EOL><DEDENT>for path in paths:<EOL><INDENT>for d1, f in list(general_source_directories_files(path)):<EOL><INDENT>target_path = os.path.join(self.path_in_package, d, d1)<EOL>data_files.append((target_path, f))<EOL><DEDENT><DEDENT>

Recursively add files under data_path to data_files list.

        Recursively add files under data_path to the list of data_files to be
        installed (and distributed). The data_path can be either a relative
        path-name, or an absolute path-name, or a 2-tuple where the first
        argument shows where in the install directory the data directory
        should be installed to.

        Parameters
        ----------
        data_path : seq or str
            Argument can be either

                * 2-sequence (<datadir suffix>, <path to data directory>)
                * path to data directory where python datadir suffix defaults
                  to package dir.

        Notes
        -----
        Rules for installation paths:
          foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar
          (gun, foo/bar) -> parent/gun
          foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b
          (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun
          (gun/*, foo/*) -> parent/gun/a, parent/gun/b
          /foo/bar -> (bar, /foo/bar) -> parent/bar
          (gun, /foo/bar) -> parent/gun
          (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar

        Examples
        --------
        For example suppose the source directory contains fun/foo.dat and
        fun/bar/car.dat::

            >>> self.add_data_dir('fun')                       #doctest: +SKIP
            >>> self.add_data_dir(('sun', 'fun'))              #doctest: +SKIP
            >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP

        Will install data-files to the locations::

            <package install directory>/
              fun/
                foo.dat
                bar/
                  car.dat
              sun/
                foo.dat
                bar/
                  car.dat
              gun/
                foo.dat
                car.dat


if len(files)><NUM_LIT:1>:<EOL><INDENT>for f in files:<EOL><INDENT>self.add_data_files(f)<EOL><DEDENT>return<EOL><DEDENT>assert len(files)==<NUM_LIT:1><EOL>if is_sequence(files[<NUM_LIT:0>]):<EOL><INDENT>d, files = files[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>d = None<EOL><DEDENT>if is_string(files):<EOL><INDENT>filepat = files<EOL><DEDENT>elif is_sequence(files):<EOL><INDENT>if len(files)==<NUM_LIT:1>:<EOL><INDENT>filepat = files[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>for f in files:<EOL><INDENT>self.add_data_files((d, f))<EOL><DEDENT>return<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError(repr(type(files)))<EOL><DEDENT>if d is None:<EOL><INDENT>if hasattr(filepat, '<STR_LIT>'):<EOL><INDENT>d = '<STR_LIT>'<EOL><DEDENT>elif os.path.isabs(filepat):<EOL><INDENT>d = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>d = os.path.dirname(filepat)<EOL><DEDENT>self.add_data_files((d, files))<EOL>return<EOL><DEDENT>paths = self.paths(filepat, include_non_existing=False)<EOL>if is_glob_pattern(filepat):<EOL><INDENT>if is_glob_pattern(d):<EOL><INDENT>pattern_list = d.split(os.sep)<EOL>pattern_list.reverse()<EOL>for path in paths:<EOL><INDENT>path_list = path.split(os.sep)<EOL>path_list.reverse()<EOL>path_list.pop() <EOL>target_list = []<EOL>i = <NUM_LIT:0><EOL>for s in pattern_list:<EOL><INDENT>if is_glob_pattern(s):<EOL><INDENT>target_list.append(path_list[i])<EOL>i += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>target_list.append(s)<EOL><DEDENT><DEDENT>target_list.reverse()<EOL>self.add_data_files((os.sep.join(target_list), path))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.add_data_files((d, paths))<EOL><DEDENT>return<EOL><DEDENT>assert not is_glob_pattern(d), repr((d, filepat))<EOL>dist = self.get_distribution()<EOL>if dist is not None and dist.data_files is not None:<EOL><INDENT>data_files = dist.data_files<EOL><DEDENT>else:<EOL><INDENT>data_files = self.data_files<EOL><DEDENT>data_files.append((os.path.join(self.path_in_package, d), paths))<EOL>

Add data files to configuration data_files.

        Parameters
        ----------
        files : sequence
            Argument(s) can be either

                * 2-sequence (<datadir prefix>,<path to data file(s)>)
                * paths to data files where python datadir prefix defaults
                  to package dir.

        Notes
        -----
        The form of each element of the files sequence is very flexible
        allowing many combinations of where to get the files from the package
        and where they should ultimately be installed on the system. The most
        basic usage is for an element of the files argument sequence to be a
        simple filename. This will cause that file from the local path to be
        installed to the installation path of the self.name package (package
        path). The file argument can also be a relative path in which case the
        entire relative path will be installed into the package directory.
        Finally, the file can be an absolute path name in which case the file
        will be found at the absolute path name but installed to the package
        path.

        This basic behavior can be augmented by passing a 2-tuple in as the
        file argument. The first element of the tuple should specify the
        relative path (under the package install directory) where the
        remaining sequence of files should be installed to (it has nothing to
        do with the file-names in the source distribution). The second element
        of the tuple is the sequence of files that should be installed. The
        files in this sequence can be filenames, relative paths, or absolute
        paths. For absolute paths the file will be installed in the top-level
        package installation directory (regardless of the first argument).
        Filenames and relative path names will be installed in the package
        install directory under the path name given as the first element of
        the tuple.

        Rules for installation paths:

          #. file.txt -> (., file.txt)-> parent/file.txt
          #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt
          #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt
          #. *.txt -> parent/a.txt, parent/b.txt
          #. foo/*.txt -> parent/foo/a.txt, parent/foo/b.txt
          #. */*.txt -> (*, */*.txt) -> parent/c/a.txt, parent/d/b.txt
          #. (sun, file.txt) -> parent/sun/file.txt
          #. (sun, bar/file.txt) -> parent/sun/file.txt
          #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt
          #. (sun, *.txt) -> parent/sun/a.txt, parent/sun/b.txt
          #. (sun, bar/*.txt) -> parent/sun/a.txt, parent/sun/b.txt
          #. (sun/*, */*.txt) -> parent/sun/c/a.txt, parent/d/b.txt

        An additional feature is that the path to a data-file can actually be
        a function that takes no arguments and returns the actual path(s) to
        the data-files. This is useful when the data files are generated while
        building the package.

        Examples
        --------
        Add files to the list of data_files to be included with the package.

            >>> self.add_data_files('foo.dat',
            ...     ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']),
            ...     'bar/cat.dat',
            ...     '/full/path/to/can.dat')                   #doctest: +SKIP

        will install these data files to::

            <package install directory>/
             foo.dat
             fun/
               gun.dat
               nun/
                 pun.dat
             sun.dat
             bar/
               car.dat
             can.dat

        where <package install directory> is the package (or sub-package)
        directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C:
        \\Python2.4 \\Lib \\site-packages \\mypackage') or
        '/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C:
        \\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage').


dist = self.get_distribution()<EOL>if dist is not None:<EOL><INDENT>if not hasattr(dist, '<STR_LIT>'):<EOL><INDENT>dist.define_macros = []<EOL><DEDENT>dist.define_macros.extend(macros)<EOL><DEDENT>else:<EOL><INDENT>self.define_macros.extend(macros)<EOL><DEDENT>

Add define macros to configuration

        Add the given sequence of macro name and value duples to the beginning
        of the define_macros list This list will be visible to all extension
        modules of the current package.


include_dirs = self.paths(paths)<EOL>dist = self.get_distribution()<EOL>if dist is not None:<EOL><INDENT>if dist.include_dirs is None:<EOL><INDENT>dist.include_dirs = []<EOL><DEDENT>dist.include_dirs.extend(include_dirs)<EOL><DEDENT>else:<EOL><INDENT>self.include_dirs.extend(include_dirs)<EOL><DEDENT>

Add paths to configuration include directories.

        Add the given sequence of paths to the beginning of the include_dirs
        list. This list will be visible to all extension modules of the
        current package.


headers = []<EOL>for path in files:<EOL><INDENT>if is_string(path):<EOL><INDENT>[headers.append((self.name, p)) for p in self.paths(path)]<EOL><DEDENT>else:<EOL><INDENT>if not isinstance(path, (tuple, list)) or len(path) != <NUM_LIT:2>:<EOL><INDENT>raise TypeError(repr(path))<EOL><DEDENT>[headers.append((path[<NUM_LIT:0>], p)) for p in self.paths(path[<NUM_LIT:1>])]<EOL><DEDENT><DEDENT>dist = self.get_distribution()<EOL>if dist is not None:<EOL><INDENT>if dist.headers is None:<EOL><INDENT>dist.headers = []<EOL><DEDENT>dist.headers.extend(headers)<EOL><DEDENT>else:<EOL><INDENT>self.headers.extend(headers)<EOL><DEDENT>

Add installable headers to configuration.

        Add the given sequence of files to the beginning of the headers list.
        By default, headers will be installed under <python-
        include>/<self.name.replace('.','/')>/ directory. If an item of files
        is a tuple, then its first argument specifies the actual installation
        location relative to the <python-include> path.

        Parameters
        ----------
        files : str or seq
            Argument(s) can be either:

                * 2-sequence (<includedir suffix>,<path to header file(s)>)
                * path(s) to header file(s) where python includedir suffix will
                  default to package name.


include_non_existing = kws.get('<STR_LIT>', True)<EOL>return gpaths(paths,<EOL>local_path = self.local_path,<EOL>include_non_existing=include_non_existing)<EOL>

Apply glob to paths and prepend local_path if needed.

        Applies glob.glob(...) to each path in the sequence (if needed) and
        pre-pends the local_path if needed. Because this is called on all
        source lists, this allows wildcard characters to be specified in lists
        of sources for extension modules and libraries and scripts and allows
        path-names be relative to the source directory.


ext_args = copy.copy(kw)<EOL>ext_args['<STR_LIT:name>'] = dot_join(self.name, name)<EOL>ext_args['<STR_LIT>'] = sources<EOL>if '<STR_LIT>' in ext_args:<EOL><INDENT>extra_info = ext_args['<STR_LIT>']<EOL>del ext_args['<STR_LIT>']<EOL>if isinstance(extra_info, dict):<EOL><INDENT>extra_info = [extra_info]<EOL><DEDENT>for info in extra_info:<EOL><INDENT>assert isinstance(info, dict), repr(info)<EOL>dict_append(ext_args,**info)<EOL><DEDENT><DEDENT>self._fix_paths_dict(ext_args)<EOL>libraries = ext_args.get('<STR_LIT>', [])<EOL>libnames = []<EOL>ext_args['<STR_LIT>'] = []<EOL>for libname in libraries:<EOL><INDENT>if isinstance(libname, tuple):<EOL><INDENT>self._fix_paths_dict(libname[<NUM_LIT:1>])<EOL><DEDENT>if '<STR_LIT:@>' in libname:<EOL><INDENT>lname, lpath = libname.split('<STR_LIT:@>', <NUM_LIT:1>)<EOL>lpath = os.path.abspath(njoin(self.local_path, lpath))<EOL>if os.path.isdir(lpath):<EOL><INDENT>c = self.get_subpackage(None, lpath,<EOL>caller_level = <NUM_LIT:2>)<EOL>if isinstance(c, Configuration):<EOL><INDENT>c = c.todict()<EOL><DEDENT>for l in [l[<NUM_LIT:0>] for l in c.get('<STR_LIT>', [])]:<EOL><INDENT>llname = l.split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>if llname == lname:<EOL><INDENT>c.pop('<STR_LIT:name>', None)<EOL>dict_append(ext_args,**c)<EOL>break<EOL><DEDENT><DEDENT>continue<EOL><DEDENT><DEDENT>libnames.append(libname)<EOL><DEDENT>ext_args['<STR_LIT>'] = libnames + ext_args['<STR_LIT>']<EOL>ext_args['<STR_LIT>'] =self.define_macros + ext_args.get('<STR_LIT>', [])<EOL>from numpy.distutils.core import Extension<EOL>ext = Extension(**ext_args)<EOL>self.ext_modules.append(ext)<EOL>dist = self.get_distribution()<EOL>if dist is not None:<EOL><INDENT>self.warn('<STR_LIT>''<STR_LIT>'+name)<EOL><DEDENT>return ext<EOL>

Add extension to configuration.

        Create and add an Extension instance to the ext_modules list. This
        method also takes the following optional keyword arguments that are
        passed on to the Extension constructor.

        Parameters
        ----------
        name : str
            name of the extension
        sources : seq
            list of the sources. The list of sources may contain functions
            (called source generators) which must take an extension instance
            and a build directory as inputs and return a source file or list of
            source files or None. If None is returned then no sources are
            generated. If the Extension instance has no sources after
            processing all source generators, then no extension module is
            built.
        include_dirs :
        define_macros :
        undef_macros :
        library_dirs :
        libraries :
        runtime_library_dirs :
        extra_objects :
        extra_compile_args :
        extra_link_args :
        extra_f77_compile_args :
        extra_f90_compile_args :
        export_symbols :
        swig_opts :
        depends :
            The depends list contains paths to files or directories that the
            sources of the extension module depend on. If any path in the
            depends list is newer than the extension module, then the module
            will be rebuilt.
        language :
        f2py_options :
        module_dirs :
        extra_info : dict or list
            dict or list of dict of keywords to be appended to keywords.

        Notes
        -----
        The self.paths(...) method is applied to all lists that may contain
        paths.


self._add_library(name, sources, None, build_info)<EOL>dist = self.get_distribution()<EOL>if dist is not None:<EOL><INDENT>self.warn('<STR_LIT>''<STR_LIT>'+ name)<EOL><DEDENT>

Add library to configuration.

Parameters
----------
name : str
    Name of the extension.
sources : sequence
    List of the sources. The list of sources may contain functions
    (called source generators) which must take an extension instance
    and a build directory as inputs and return a source file or list of
    source files or None. If None is returned then no sources are
    generated. If the Extension instance has no sources after
    processing all source generators, then no extension module is
    built.
build_info : dict, optional
    The following keys are allowed:

        * depends
        * macros
        * include_dirs
        * extra_compiler_args
        * extra_f77_compiler_args
        * extra_f90_compiler_args
        * f2py_options
        * language


def _add_library(self, name, sources, install_dir, build_info):

build_info = copy.copy(build_info)<EOL>name = name <EOL>build_info['<STR_LIT>'] = sources<EOL>if not '<STR_LIT>' in build_info:<EOL><INDENT>build_info['<STR_LIT>'] = []<EOL><DEDENT>self._fix_paths_dict(build_info)<EOL>self.libraries.append((name, build_info))<EOL>

Common implementation for add_library and add_installed_library. Do
        not use directly


def add_installed_library(self, name, sources, install_dir, build_info=None):

if not build_info:<EOL><INDENT>build_info = {}<EOL><DEDENT>install_dir = os.path.join(self.package_path, install_dir)<EOL>self._add_library(name, sources, install_dir, build_info)<EOL>self.installed_libraries.append(InstallableLib(name, build_info, install_dir))<EOL>

Similar to add_library, but the specified library is installed.

Most C libraries used with `distutils` are only used to build python
extensions, but libraries built through this method will be installed
so that they can be reused by third-party packages.

Parameters
----------
name : str
    Name of the installed library.
sources : sequence
    List of the library's source files. See `add_library` for details.
install_dir : str
    Path to install the library, relative to the current sub-package.
build_info : dict, optional
    The following keys are allowed:

        * depends
        * macros
        * include_dirs
        * extra_compiler_args
        * extra_f77_compiler_args
        * extra_f90_compiler_args
        * f2py_options
        * language

Returns
-------
None

See Also
--------
add_library, add_npy_pkg_config, get_info

Notes
-----
The best way to encode the options required to link against the specified
C libraries is to use a "libname.ini" file, and use `get_info` to
retrieve the required options (see `add_npy_pkg_config` for more
information).


def add_npy_pkg_config(self, template, install_dir, subst_dict=None):

if subst_dict is None:<EOL><INDENT>subst_dict = {}<EOL><DEDENT>basename = os.path.splitext(template)[<NUM_LIT:0>]<EOL>template = os.path.join(self.package_path, template)<EOL>if self.name in self.installed_pkg_config:<EOL><INDENT>self.installed_pkg_config[self.name].append((template, install_dir,<EOL>subst_dict))<EOL><DEDENT>else:<EOL><INDENT>self.installed_pkg_config[self.name] = [(template, install_dir,<EOL>subst_dict)]<EOL><DEDENT>

Generate and install a npy-pkg config file from a template.

The config file generated from `template` is installed in the
given install directory, using `subst_dict` for variable substitution.

Parameters
----------
template : str
    The path of the template, relatively to the current package path.
install_dir : str
    Where to install the npy-pkg config file, relatively to the current
    package path.
subst_dict : dict, optional
    If given, any string of the form ``@key@`` will be replaced by
    ``subst_dict[key]`` in the template file when installed. The install
    prefix is always available through the variable ``@prefix@``, since the
    install prefix is not easy to get reliably from setup.py.

See also
--------
add_installed_library, get_info

Notes
-----
This works for both standard installs and in-place builds, i.e. the
``@prefix@`` refer to the source directory for in-place builds.

Examples
--------
::

    config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar})

Assuming the foo.ini.in file has the following content::

    [meta]
    Name=@foo@
    Version=1.0
    Description=dummy description

    [default]
    Cflags=-I@prefix@/include
    Libs=

The generated file will have the following content::

    [meta]
    Name=bar
    Version=1.0
    Description=dummy description

    [default]
    Cflags=-Iprefix_dir/include
    Libs=

and will be installed as foo.ini in the 'lib' subpath.


scripts = self.paths(files)<EOL>dist = self.get_distribution()<EOL>if dist is not None:<EOL><INDENT>if dist.scripts is None:<EOL><INDENT>dist.scripts = []<EOL><DEDENT>dist.scripts.extend(scripts)<EOL><DEDENT>else:<EOL><INDENT>self.scripts.extend(scripts)<EOL><DEDENT>

Add scripts to configuration.

        Add the sequence of files to the beginning of the scripts list.
        Scripts will be installed under the <prefix>/bin/ directory.


cmd = get_cmd('<STR_LIT>')<EOL>cmd.ensure_finalized()<EOL>cmd.dump_source = <NUM_LIT:0><EOL>cmd.noisy = <NUM_LIT:0><EOL>old_path = os.environ.get('<STR_LIT>')<EOL>if old_path:<EOL><INDENT>path = os.pathsep.join(['<STR_LIT:.>', old_path])<EOL>os.environ['<STR_LIT>'] = path<EOL><DEDENT>return cmd<EOL>

Returns the numpy.distutils config command instance.


cmd = get_cmd('<STR_LIT>')<EOL>cmd.ensure_finalized()<EOL>return cmd.build_temp<EOL>

Return a path to a temporary directory where temporary files should be
placed.


simple_fortran_subroutine = '''<STR_LIT>'''<EOL>config_cmd = self.get_config_cmd()<EOL>flag = config_cmd.try_compile(simple_fortran_subroutine, lang='<STR_LIT>')<EOL>return flag<EOL>

Check for availability of Fortran 77 compiler.

        Use it inside source generating function to ensure that
        setup distribution instance has been initialized.

        Notes
        -----
        True if a Fortran 77 compiler is available (because a simple Fortran 77
        code was able to be compiled successfully).


Check for availability of Fortran 90 compiler.

        Use it inside source generating function to ensure that
        setup distribution instance has been initialized.

        Notes
        -----
        True if a Fortran 90 compiler is available (because a simple Fortran
        90 code was able to be compiled successfully)


if is_sequence(extlib):<EOL><INDENT>lib_name, build_info = extlib<EOL>dict_append(build_info,<EOL>libraries=self.libraries,<EOL>include_dirs=self.include_dirs)<EOL><DEDENT>else:<EOL><INDENT>from numpy.distutils.core import Extension<EOL>assert isinstance(extlib, Extension), repr(extlib)<EOL>extlib.libraries.extend(self.libraries)<EOL>extlib.include_dirs.extend(self.include_dirs)<EOL><DEDENT>

Append libraries, include_dirs to extension or library item.


revision = None<EOL>m = None<EOL>cwd =  os.getcwd()<EOL>try:<EOL><INDENT>os.chdir(path or '<STR_LIT:.>')<EOL>p = subprocess.Popen(['<STR_LIT>'], shell=True,<EOL>stdout=subprocess.PIPE, stderr=None,<EOL>close_fds=True)<EOL>sout = p.stdout<EOL>m = re.match(r'<STR_LIT>', sout.read())<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>os.chdir(cwd)<EOL>if m:<EOL><INDENT>revision = int(m.group('<STR_LIT>'))<EOL>return revision<EOL><DEDENT>if sys.platform=='<STR_LIT:win32>' and os.environ.get('<STR_LIT>', None):<EOL><INDENT>entries = njoin(path, '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>entries = njoin(path, '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>if os.path.isfile(entries):<EOL><INDENT>f = open(entries)<EOL>fstr = f.read()<EOL>f.close()<EOL>if fstr[:<NUM_LIT:5>] == '<STR_LIT>':  <EOL><INDENT>m = re.search(r'<STR_LIT>', fstr)<EOL>if m:<EOL><INDENT>revision = int(m.group('<STR_LIT>'))<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>m = re.search(r'<STR_LIT>', fstr)<EOL>if m:<EOL><INDENT>revision = int(m.group('<STR_LIT>'))<EOL><DEDENT><DEDENT><DEDENT>return revision<EOL>


revision = None<EOL>m = None<EOL>cwd =  os.getcwd()<EOL>try:<EOL><INDENT>os.chdir(path or '<STR_LIT:.>')<EOL>p = subprocess.Popen(['<STR_LIT>'], shell=True,<EOL>stdout=subprocess.PIPE, stderr=None,<EOL>close_fds=True)<EOL>sout = p.stdout<EOL>m = re.match(r'<STR_LIT>', sout.read())<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>os.chdir(cwd)<EOL>if m:<EOL><INDENT>revision = int(m.group('<STR_LIT>'))<EOL>return revision<EOL><DEDENT>branch_fn = njoin(path, '<STR_LIT>', '<STR_LIT>')<EOL>branch_cache_fn = njoin(path, '<STR_LIT>', '<STR_LIT>')<EOL>if os.path.isfile(branch_fn):<EOL><INDENT>branch0 = None<EOL>f = open(branch_fn)<EOL>revision0 = f.read().strip()<EOL>f.close()<EOL>branch_map = {}<EOL>for line in file(branch_cache_fn, '<STR_LIT:r>'):<EOL><INDENT>branch1, revision1  = line.split()[:<NUM_LIT:2>]<EOL>if revision1==revision0:<EOL><INDENT>branch0 = branch1<EOL><DEDENT>try:<EOL><INDENT>revision1 = int(revision1)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT>branch_map[branch1] = revision1<EOL><DEDENT>revision = branch_map.get(branch0)<EOL><DEDENT>return revision<EOL>

Return path's Mercurial revision number.


def get_version(self, version_file=None, version_variable=None):

version = getattr(self, '<STR_LIT:version>', None)<EOL>if version is not None:<EOL><INDENT>return version<EOL><DEDENT>if version_file is None:<EOL><INDENT>files = ['<STR_LIT>',<EOL>self.name.split('<STR_LIT:.>')[-<NUM_LIT:1>]+'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>files = [version_file]<EOL><DEDENT>if version_variable is None:<EOL><INDENT>version_vars = ['<STR_LIT:version>',<EOL>'<STR_LIT>',<EOL>self.name.split('<STR_LIT:.>')[-<NUM_LIT:1>]+'<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>version_vars = [version_variable]<EOL><DEDENT>for f in files:<EOL><INDENT>fn = njoin(self.local_path, f)<EOL>if os.path.isfile(fn):<EOL><INDENT>info = (open(fn), fn, ('<STR_LIT>', '<STR_LIT>', <NUM_LIT:1>))<EOL>name = os.path.splitext(os.path.basename(fn))[<NUM_LIT:0>]<EOL>n = dot_join(self.name, name)<EOL>try:<EOL><INDENT>version_module = imp.load_module('<STR_LIT:_>'.join(n.split('<STR_LIT:.>')),*info)<EOL><DEDENT>except ImportError:<EOL><INDENT>msg = get_exception()<EOL>self.warn(str(msg))<EOL>version_module = None<EOL><DEDENT>if version_module is None:<EOL><INDENT>continue<EOL><DEDENT>for a in version_vars:<EOL><INDENT>version = getattr(version_module, a, None)<EOL>if version is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if version is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if version is not None:<EOL><INDENT>self.version = version<EOL>return version<EOL><DEDENT>revision = self._get_svn_revision(self.local_path)<EOL>if revision is None:<EOL><INDENT>revision = self._get_hg_revision(self.local_path)<EOL><DEDENT>if revision is not None:<EOL><INDENT>version = str(revision)<EOL>self.version = version<EOL><DEDENT>return version<EOL>

Try to get version string of a package.

        Return a version string of the current package or None if the version
        information could not be detected.

        Notes
        -----
        This method scans files named
        __version__.py, <packagename>_version.py, version.py, and
        __svn_version__.py for string variables version, __version\__, and
        <packagename>_version, until a version number is found.


target = njoin(self.local_path, '<STR_LIT>')<EOL>revision = self._get_svn_revision(self.local_path)<EOL>if os.path.isfile(target) or revision is None:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>def generate_svn_version_py():<EOL><INDENT>if not os.path.isfile(target):<EOL><INDENT>version = str(revision)<EOL>self.info('<STR_LIT>' % (target, version))<EOL>f = open(target, '<STR_LIT:w>')<EOL>f.write('<STR_LIT>' % (version))<EOL>f.close()<EOL><DEDENT>import atexit<EOL>def rm_file(f=target,p=self.info):<EOL><INDENT>if delete:<EOL><INDENT>try: os.remove(f); p('<STR_LIT>'+f)<EOL>except OSError: pass<EOL>try: os.remove(f+'<STR_LIT:c>'); p('<STR_LIT>'+f+'<STR_LIT:c>')<EOL>except OSError: pass<EOL><DEDENT><DEDENT>atexit.register(rm_file)<EOL>return target<EOL><DEDENT>self.add_data_files(('<STR_LIT>', generate_svn_version_py()))<EOL><DEDENT>

Appends a data function to the data_files list that will generate
        __svn_version__.py file to the current package directory.

        Generate package __svn_version__.py file from SVN revision number,
        it will be removed after python exits but will be available
        when sdist, etc commands are executed.

        Notes
        -----
        If __svn_version__.py existed before, nothing is done.

        This is
        intended for working with source directories that are in an SVN
        repository.


target = njoin(self.local_path, '<STR_LIT>')<EOL>revision = self._get_hg_revision(self.local_path)<EOL>if os.path.isfile(target) or revision is None:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>def generate_hg_version_py():<EOL><INDENT>if not os.path.isfile(target):<EOL><INDENT>version = str(revision)<EOL>self.info('<STR_LIT>' % (target, version))<EOL>f = open(target, '<STR_LIT:w>')<EOL>f.write('<STR_LIT>' % (version))<EOL>f.close()<EOL><DEDENT>import atexit<EOL>def rm_file(f=target,p=self.info):<EOL><INDENT>if delete:<EOL><INDENT>try: os.remove(f); p('<STR_LIT>'+f)<EOL>except OSError: pass<EOL>try: os.remove(f+'<STR_LIT:c>'); p('<STR_LIT>'+f+'<STR_LIT:c>')<EOL>except OSError: pass<EOL><DEDENT><DEDENT>atexit.register(rm_file)<EOL>return target<EOL><DEDENT>self.add_data_files(('<STR_LIT>', generate_hg_version_py()))<EOL><DEDENT>

Appends a data function to the data_files list that will generate
        __hg_version__.py file to the current package directory.

        Generate package __hg_version__.py file from Mercurial revision,
        it will be removed after python exits but will be available
        when sdist, etc commands are executed.

        Notes
        -----
        If __hg_version__.py existed before, nothing is done.

        This is intended for working with source directories that are
        in an Mercurial repository.


self.py_modules.append((self.name, name, generate_config_py))<EOL>

Generate package __config__.py file containing system_info
        information used during building the package.

        This file is installed to the
        package installation directory.


from .system_info import get_info, dict_append<EOL>info_dict = {}<EOL>for a in names:<EOL><INDENT>dict_append(info_dict,**get_info(a))<EOL><DEDENT>return info_dict<EOL>

Get resources information.

        Return information (from system_info.get_info) for all of the names in
        the argument list in a single dictionary.


def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):

<EOL>ccomp = self.compiler_so<EOL>if ccomp[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>if '<STR_LIT>' in ccomp:<EOL><INDENT>ccomp.remove('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in ccomp:<EOL><INDENT>ccomp.remove('<STR_LIT>')<EOL><DEDENT>ccomp += ['<STR_LIT>']<EOL>self.compiler_so = ccomp<EOL><DEDENT>display = '<STR_LIT>' % (os.path.basename(self.compiler_so[<NUM_LIT:0>]), src)<EOL>try:<EOL><INDENT>self.spawn(self.compiler_so + cc_args + [src, '<STR_LIT>', obj] +<EOL>extra_postargs, display = display)<EOL><DEDENT>except DistutilsExecError:<EOL><INDENT>msg = str(get_exception())<EOL>raise CompileError(msg)<EOL><DEDENT>

Compile a single source files with a Unix-style compiler.


def UnixCCompiler_create_static_lib(self, objects, output_libname,<EOL>output_dir=None, debug=<NUM_LIT:0>, target_lang=None):

objects, output_dir = self._fix_object_args(objects, output_dir)<EOL>output_filename =self.library_filename(output_libname, output_dir=output_dir)<EOL>if self._need_link(objects, output_filename):<EOL><INDENT>try:<EOL><INDENT>os.unlink(output_filename)<EOL><DEDENT>except (IOError, OSError):<EOL><INDENT>pass<EOL><DEDENT>self.mkpath(os.path.dirname(output_filename))<EOL>tmp_objects = objects + self.objects<EOL>while tmp_objects:<EOL><INDENT>objects = tmp_objects[:<NUM_LIT:50>]<EOL>tmp_objects = tmp_objects[<NUM_LIT:50>:]<EOL>display = '<STR_LIT>' % (<EOL>os.path.basename(self.archiver[<NUM_LIT:0>]),<EOL>len(objects), output_filename)<EOL>self.spawn(self.archiver + [output_filename] + objects,<EOL>display = display)<EOL><DEDENT>if self.ranlib:<EOL><INDENT>display = '<STR_LIT>' % (os.path.basename(self.ranlib[<NUM_LIT:0>]),<EOL>output_filename)<EOL>try:<EOL><INDENT>self.spawn(self.ranlib + [output_filename],<EOL>display = display)<EOL><DEDENT>except DistutilsExecError:<EOL><INDENT>msg = str(get_exception())<EOL>raise LibError(msg)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>log.debug("<STR_LIT>", output_filename)<EOL><DEDENT>return<EOL>

Build a static library in a separate sub-process.

Parameters
----------
objects : list or tuple of str
    List of paths to object files used to build the static library.
output_libname : str
    The library name as an absolute or relative (if `output_dir` is used)
    path.
output_dir : str, optional
    The path to the output directory. Default is None, in which case
    the ``output_dir`` attribute of the UnixCCompiler instance.
debug : bool, optional
    This parameter is not used.
target_lang : str, optional
    This parameter is not used.

Returns
-------
None


def find_executable(exe, path=None, _cache={}):

key = exe, path<EOL>try:<EOL><INDENT>return _cache[key]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>log.debug('<STR_LIT>' % exe)<EOL>orig_exe = exe<EOL>if path is None:<EOL><INDENT>path = os.environ.get('<STR_LIT>', os.defpath)<EOL><DEDENT>if os.name=='<STR_LIT>':<EOL><INDENT>realpath = os.path.realpath<EOL><DEDENT>else:<EOL><INDENT>realpath = lambda a:a<EOL><DEDENT>if exe.startswith('<STR_LIT:">'):<EOL><INDENT>exe = exe[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL><DEDENT>suffixes = ['<STR_LIT>']<EOL>if os.name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>fn, ext = os.path.splitext(exe)<EOL>extra_suffixes = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if ext.lower() not in extra_suffixes:<EOL><INDENT>suffixes = extra_suffixes<EOL><DEDENT><DEDENT>if os.path.isabs(exe):<EOL><INDENT>paths = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]<EOL><DEDENT>for path in paths:<EOL><INDENT>fn = os.path.join(path, exe)<EOL>for s in suffixes:<EOL><INDENT>f_ext = fn+s<EOL>if not os.path.islink(f_ext):<EOL><INDENT>f_ext = realpath(f_ext)<EOL><DEDENT>if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):<EOL><INDENT>log.info('<STR_LIT>' % f_ext)<EOL>_cache[key] = f_ext<EOL>return f_ext<EOL><DEDENT><DEDENT><DEDENT>log.warn('<STR_LIT>' % orig_exe)<EOL>return None<EOL>

Return full path of a executable or None.

    Symbolic links are not followed.


if hasattr(stream, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>r = stream.fileno()<EOL>return True<EOL><DEDENT>except IOError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Returns True if 'stream' supports the file descriptor and allows fileno().


def exec_command( command,<EOL>execute_in='<STR_LIT>', use_shell=None, use_tee = None,<EOL>_with_python = <NUM_LIT:1>,<EOL>**env ):

log.debug('<STR_LIT>' % (command,'<STR_LIT:U+002C>'.join(['<STR_LIT>'%kv for kv in env.items()])))<EOL>if use_tee is None:<EOL><INDENT>use_tee = os.name=='<STR_LIT>'<EOL><DEDENT>if use_shell is None:<EOL><INDENT>use_shell = os.name=='<STR_LIT>'<EOL><DEDENT>execute_in = os.path.abspath(execute_in)<EOL>oldcwd = os.path.abspath(os.getcwd())<EOL>if __name__[-<NUM_LIT:12>:] == '<STR_LIT>':<EOL><INDENT>exec_dir = os.path.dirname(os.path.abspath(__file__))<EOL><DEDENT>elif os.path.isfile('<STR_LIT>'):<EOL><INDENT>exec_dir = os.path.abspath('<STR_LIT:.>')<EOL><DEDENT>else:<EOL><INDENT>exec_dir = os.path.abspath(sys.argv[<NUM_LIT:0>])<EOL>if os.path.isfile(exec_dir):<EOL><INDENT>exec_dir = os.path.dirname(exec_dir)<EOL><DEDENT><DEDENT>if oldcwd!=execute_in:<EOL><INDENT>os.chdir(execute_in)<EOL>log.debug('<STR_LIT>' % execute_in)<EOL><DEDENT>else:<EOL><INDENT>log.debug('<STR_LIT>' % oldcwd)<EOL><DEDENT>oldenv = _preserve_environment( list(env.keys()) )<EOL>_update_environment( **env )<EOL>try:<EOL><INDENT>if (_with_python and _supports_fileno(sys.stdout) and<EOL>sys.stdout.fileno() == -<NUM_LIT:1>):<EOL><INDENT>st = _exec_command_python(command,<EOL>exec_command_dir = exec_dir,<EOL>**env)<EOL><DEDENT>elif os.name=='<STR_LIT>':<EOL><INDENT>st = _exec_command_posix(command,<EOL>use_shell=use_shell,<EOL>use_tee=use_tee,<EOL>**env)<EOL><DEDENT>else:<EOL><INDENT>st = _exec_command(command, use_shell=use_shell,<EOL>use_tee=use_tee,**env)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if oldcwd!=execute_in:<EOL><INDENT>os.chdir(oldcwd)<EOL>log.debug('<STR_LIT>' % oldcwd)<EOL><DEDENT>_update_environment(**oldenv)<EOL><DEDENT>return st<EOL>

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:
      use_shell - execute `sh -c command`
      use_tee   - pipe the output of command through tee
      execute_in - before run command `cd execute_in` and after `cd -`.

    On NT, DOS systems the returned status is correct for external commands.
    Wild cards will not work for non-posix systems or when use_shell=0.


if len(sys.argv) == <NUM_LIT:3>:<EOL><INDENT>if sys.argv[<NUM_LIT:1>][-<NUM_LIT:4>:] == '<STR_LIT>' and sys.argv[<NUM_LIT:2>][-<NUM_LIT:4>:] == '<STR_LIT>':<EOL><INDENT>libfile, deffile = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>elif sys.argv[<NUM_LIT:1>][-<NUM_LIT:4>:] == '<STR_LIT>' and sys.argv[<NUM_LIT:2>][-<NUM_LIT:4>:] == '<STR_LIT>':<EOL><INDENT>deffile, libfile = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL><DEDENT><DEDENT>elif len(sys.argv) == <NUM_LIT:2>:<EOL><INDENT>if sys.argv[<NUM_LIT:1>][-<NUM_LIT:4>:] == '<STR_LIT>':<EOL><INDENT>deffile = sys.argv[<NUM_LIT:1>]<EOL>libfile = '<STR_LIT>' % py_ver<EOL><DEDENT>elif sys.argv[<NUM_LIT:1>][-<NUM_LIT:4>:] == '<STR_LIT>':<EOL><INDENT>deffile = None<EOL>libfile = sys.argv[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>libfile = '<STR_LIT>' % py_ver<EOL>deffile = None<EOL><DEDENT>return libfile, deffile<EOL>

Parses the command-line arguments.

libfile, deffile = parse_cmd()


def getnm(nm_cmd = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>' % py_ver]):

f = subprocess.Popen(nm_cmd, shell=True, stdout=subprocess.PIPE)<EOL>nm_output = f.stdout.read()<EOL>f.stdout.close()<EOL>return nm_output<EOL>

Returns the output of nm_cmd via a pipe.

nm_output = getnam(nm_cmd = 'nm -Cs py_lib')


data = DATA_RE.findall(nm_output)<EOL>func = FUNC_RE.findall(nm_output)<EOL>flist = []<EOL>for sym in data:<EOL><INDENT>if sym in func and (sym[:<NUM_LIT:2>] == '<STR_LIT>' or sym[:<NUM_LIT:3>] == '<STR_LIT>' or sym[:<NUM_LIT:4>] == '<STR_LIT>'):<EOL><INDENT>flist.append(sym)<EOL><DEDENT><DEDENT>dlist = []<EOL>for sym in data:<EOL><INDENT>if sym not in flist and (sym[:<NUM_LIT:2>] == '<STR_LIT>' or sym[:<NUM_LIT:3>] == '<STR_LIT>'):<EOL><INDENT>dlist.append(sym)<EOL><DEDENT><DEDENT>dlist.sort()<EOL>flist.sort()<EOL>return dlist, flist<EOL>

Returns a tuple of lists: dlist for the list of data
symbols and flist for the list of function symbols.

dlist, flist = parse_nm(nm_output)


def output_def(dlist, flist, header, file = sys.stdout):

for data_sym in dlist:<EOL><INDENT>header = header + '<STR_LIT>' % data_sym<EOL><DEDENT>header = header + '<STR_LIT:\n>' <EOL>for func_sym in flist:<EOL><INDENT>header = header + '<STR_LIT>' % func_sym<EOL><DEDENT>file.write(header)<EOL>

Outputs the final DEF file to a file defaulting to stdout.

output_def(dlist, flist, header, file = sys.stdout)


def empty(shape, dtype=None, order='<STR_LIT:C>'):

return ndarray.__new__(matrix, shape, dtype, order=order)<EOL>

Return a new matrix of given shape and type, without initializing entries.

Parameters
----------
shape : int or tuple of int
    Shape of the empty matrix.
dtype : data-type, optional
    Desired output data-type.
order : {'C', 'F'}, optional
    Whether to store multi-dimensional data in C (row-major) or
    Fortran (column-major) order in memory.

See Also
--------
empty_like, zeros

Notes
-----
`empty`, unlike `zeros`, does not set the matrix values to zero,
and may therefore be marginally faster.  On the other hand, it requires
the user to manually set all the values in the array, and should be
used with caution.

Examples
--------
>>> import numpy.matlib
>>> np.matlib.empty((2, 2))    # filled with random data
matrix([[  6.76425276e-320,   9.79033856e-307],
        [  7.39337286e-309,   3.22135945e-309]])        #random
>>> np.matlib.empty((2, 2), dtype=int)
matrix([[ 6600475,        0],
        [ 6586976, 22740995]])                          #random


def ones(shape, dtype=None, order='<STR_LIT:C>'):

a = ndarray.__new__(matrix, shape, dtype, order=order)<EOL>a.fill(<NUM_LIT:1>)<EOL>return a<EOL>

Matrix of ones.

Return a matrix of given shape and type, filled with ones.

Parameters
----------
shape : {sequence of ints, int}
    Shape of the matrix
dtype : data-type, optional
    The desired data-type for the matrix, default is np.float64.
order : {'C', 'F'}, optional
    Whether to store matrix in C- or Fortran-contiguous order,
    default is 'C'.

Returns
-------
out : matrix
    Matrix of ones of given shape, dtype, and order.

See Also
--------
ones : Array of ones.
matlib.zeros : Zero matrix.

Notes
-----
If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
`out` becomes a single row matrix of shape ``(1,N)``.

Examples
--------
>>> np.matlib.ones((2,3))
matrix([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.]])

>>> np.matlib.ones(2)
matrix([[ 1.,  1.]])


def zeros(shape, dtype=None, order='<STR_LIT:C>'):

a = ndarray.__new__(matrix, shape, dtype, order=order)<EOL>a.fill(<NUM_LIT:0>)<EOL>return a<EOL>

Return a matrix of given shape and type, filled with zeros.

Parameters
----------
shape : int or sequence of ints
    Shape of the matrix
dtype : data-type, optional
    The desired data-type for the matrix, default is float.
order : {'C', 'F'}, optional
    Whether to store the result in C- or Fortran-contiguous order,
    default is 'C'.

Returns
-------
out : matrix
    Zero matrix of given shape, dtype, and order.

See Also
--------
numpy.zeros : Equivalent array function.
matlib.ones : Return a matrix of ones.

Notes
-----
If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``,
`out` becomes a single row matrix of shape ``(1,N)``.

Examples
--------
>>> import numpy.matlib
>>> np.matlib.zeros((2, 3))
matrix([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])

>>> np.matlib.zeros(2)
matrix([[ 0.,  0.]])


a = array([<NUM_LIT:1>]+n*[<NUM_LIT:0>], dtype=dtype)<EOL>b = empty((n, n), dtype=dtype)<EOL>b.flat = a<EOL>return b<EOL>

Returns the square identity matrix of given size.

Parameters
----------
n : int
    Size of the returned identity matrix.
dtype : data-type, optional
    Data-type of the output. Defaults to ``float``.

Returns
-------
out : matrix
    `n` x `n` matrix with its main diagonal set to one,
    and all other elements zero.

See Also
--------
numpy.identity : Equivalent array function.
matlib.eye : More general matrix identity function.

Examples
--------
>>> import numpy.matlib
>>> np.matlib.identity(3, dtype=int)
matrix([[1, 0, 0],
        [0, 1, 0],
        [0, 0, 1]])


def eye(n,M=None, k=<NUM_LIT:0>, dtype=float):

return asmatrix(np.eye(n, M, k, dtype))<EOL>

Return a matrix with ones on the diagonal and zeros elsewhere.

Parameters
----------
n : int
    Number of rows in the output.
M : int, optional
    Number of columns in the output, defaults to `n`.
k : int, optional
    Index of the diagonal: 0 refers to the main diagonal,
    a positive value refers to an upper diagonal,
    and a negative value to a lower diagonal.
dtype : dtype, optional
    Data-type of the returned matrix.

Returns
-------
I : matrix
    A `n` x `M` matrix where all elements are equal to zero,
    except for the `k`-th diagonal, whose values are equal to one.

See Also
--------
numpy.eye : Equivalent array function.
identity : Square identity matrix.

Examples
--------
>>> import numpy.matlib
>>> np.matlib.eye(3, k=1, dtype=float)
matrix([[ 0.,  1.,  0.],
        [ 0.,  0.,  1.],
        [ 0.,  0.,  0.]])


if isinstance(args[<NUM_LIT:0>], tuple):<EOL><INDENT>args = args[<NUM_LIT:0>]<EOL><DEDENT>return asmatrix(np.random.rand(*args))<EOL>

Return a matrix of random values with given shape.

Create a matrix of the given shape and propagate it with
random samples from a uniform distribution over ``[0, 1)``.

Parameters
----------
\\*args : Arguments
    Shape of the output.
    If given as N integers, each integer specifies the size of one
    dimension.
    If given as a tuple, this tuple gives the complete shape.

Returns
-------
out : ndarray
    The matrix of random values with shape given by `\\*args`.

See Also
--------
randn, numpy.random.rand

Examples
--------
>>> import numpy.matlib
>>> np.matlib.rand(2, 3)
matrix([[ 0.68340382,  0.67926887,  0.83271405],
        [ 0.00793551,  0.20468222,  0.95253525]])       #random
>>> np.matlib.rand((2, 3))
matrix([[ 0.84682055,  0.73626594,  0.11308016],
        [ 0.85429008,  0.3294825 ,  0.89139555]])       #random

If the first argument is a tuple, other arguments are ignored:

>>> np.matlib.rand((2, 3), 4)
matrix([[ 0.46898646,  0.15163588,  0.95188261],
        [ 0.59208621,  0.09561818,  0.00583606]])       #random


if isinstance(args[<NUM_LIT:0>], tuple):<EOL><INDENT>args = args[<NUM_LIT:0>]<EOL><DEDENT>return asmatrix(np.random.randn(*args))<EOL>

Return a random matrix with data from the "standard normal" distribution.

`randn` generates a matrix filled with random floats sampled from a
univariate "normal" (Gaussian) distribution of mean 0 and variance 1.

Parameters
----------
\\*args : Arguments
    Shape of the output.
    If given as N integers, each integer specifies the size of one
    dimension. If given as a tuple, this tuple gives the complete shape.

Returns
-------
Z : matrix of floats
    A matrix of floating-point samples drawn from the standard normal
    distribution.

See Also
--------
rand, random.randn

Notes
-----
For random samples from :math:`N(\\mu, \\sigma^2)`, use:

``sigma * np.matlib.randn(...) + mu``

Examples
--------
>>> import numpy.matlib
>>> np.matlib.randn(1)
matrix([[-0.09542833]])                                 #random
>>> np.matlib.randn(1, 2, 3)
matrix([[ 0.16198284,  0.0194571 ,  0.18312985],
        [-0.7509172 ,  1.61055   ,  0.45298599]])       #random

Two-by-four matrix of samples from :math:`N(3, 6.25)`:

>>> 2.5 * np.matlib.randn((2, 4)) + 3
matrix([[ 4.74085004,  8.89381862,  4.09042411,  4.83721922],
        [ 7.52373709,  5.07933944, -2.64043543,  0.45610557]])  #random


a = asanyarray(a)<EOL>ndim = a.ndim<EOL>if ndim == <NUM_LIT:0>:<EOL><INDENT>origrows, origcols = (<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>elif ndim == <NUM_LIT:1>:<EOL><INDENT>origrows, origcols = (<NUM_LIT:1>, a.shape[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>origrows, origcols = a.shape<EOL><DEDENT>rows = origrows * m<EOL>cols = origcols * n<EOL>c = a.reshape(<NUM_LIT:1>, a.size).repeat(m, <NUM_LIT:0>).reshape(rows, origcols).repeat(n, <NUM_LIT:0>)<EOL>return c.reshape(rows, cols)<EOL>

Repeat a 0-D to 2-D array or matrix MxN times.

Parameters
----------
a : array_like
    The array or matrix to be repeated.
m, n : int
    The number of times `a` is repeated along the first and second axes.

Returns
-------
out : ndarray
    The result of repeating `a`.

Examples
--------
>>> import numpy.matlib
>>> a0 = np.array(1)
>>> np.matlib.repmat(a0, 2, 3)
array([[1, 1, 1],
       [1, 1, 1]])

>>> a1 = np.arange(4)
>>> np.matlib.repmat(a1, 2, 2)
array([[0, 1, 2, 3, 0, 1, 2, 3],
       [0, 1, 2, 3, 0, 1, 2, 3]])

>>> a2 = np.asmatrix(np.arange(6).reshape(2, 3))
>>> np.matlib.repmat(a2, 2, 3)
matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2],
        [3, 4, 5, 3, 4, 5, 3, 4, 5],
        [0, 1, 2, 0, 1, 2, 0, 1, 2],
        [3, 4, 5, 3, 4, 5, 3, 4, 5]])


nrows, ncols = a.shape<EOL>ml = <NUM_LIT:0><EOL>for k in range(-nrows+<NUM_LIT:1>, <NUM_LIT:0>):<EOL><INDENT>if np.diag(a, k).any():<EOL><INDENT>ml = -k<EOL>break<EOL><DEDENT><DEDENT>mu = <NUM_LIT:0><EOL>for k in range(nrows-<NUM_LIT:1>, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>if np.diag(a, k).any():<EOL><INDENT>mu = k<EOL>break<EOL><DEDENT><DEDENT>return ml, mu<EOL>

Returns ml and mu, the lower and upper band sizes of a.


return a.dot(y)<EOL>


return a<EOL>


ml, mu = _band_count(a)<EOL>bjac = []<EOL>for k in range(mu, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>bjac.append(np.r_[[<NUM_LIT:0>] * k, np.diag(a, k)])<EOL><DEDENT>bjac.append(np.diag(a))<EOL>for k in range(-<NUM_LIT:1>, -ml-<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>bjac.append(np.r_[np.diag(a, k), [<NUM_LIT:0>] * (-k)])<EOL><DEDENT>return bjac<EOL>


def _solve_linear_sys(a, y0, tend=<NUM_LIT:1>, dt=<NUM_LIT:0.1>,<EOL>solver=None, method='<STR_LIT>', use_jac=True,<EOL>with_jacobian=False, banded=False):

if banded:<EOL><INDENT>lband, uband = _band_count(a)<EOL><DEDENT>else:<EOL><INDENT>lband = None<EOL>uband = None<EOL><DEDENT>if use_jac:<EOL><INDENT>if banded:<EOL><INDENT>r = ode(_linear_func, _linear_banded_jac)<EOL><DEDENT>else:<EOL><INDENT>r = ode(_linear_func, _linear_jac)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>r = ode(_linear_func)<EOL><DEDENT>if solver is None:<EOL><INDENT>if np.iscomplexobj(a):<EOL><INDENT>solver = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>solver = "<STR_LIT>"<EOL><DEDENT><DEDENT>r.set_integrator(solver,<EOL>with_jacobian=with_jacobian,<EOL>method=method,<EOL>lband=lband, uband=uband,<EOL>rtol=<NUM_LIT>, atol=<NUM_LIT>,<EOL>)<EOL>t0 = <NUM_LIT:0><EOL>r.set_initial_value(y0, t0)<EOL>r.set_f_params(a)<EOL>r.set_jac_params(a)<EOL>t = [t0]<EOL>y = [y0]<EOL>while r.successful() and r.t < tend:<EOL><INDENT>r.integrate(r.t + dt)<EOL>t.append(r.t)<EOL>y.append(r.y)<EOL><DEDENT>t = np.array(t)<EOL>y = np.array(y)<EOL>return t, y<EOL>

Use scipy.integrate.ode to solve a linear system of ODEs.

    a : square ndarray
        Matrix of the linear system to be solved.
    y0 : ndarray
        Initial condition
    tend : float
        Stop time.
    dt : float
        Step size of the output.
    solver : str
        If not None, this must be "vode", "lsoda" or "zvode".
    method : str
        Either "bdf" or "adams".
    use_jac : bool
        Determines if the jacobian function is passed to ode().
    with_jacobian : bool
        Passed to ode.set_integrator().
    banded : bool
        Determines whether a banded or full jacobian is used.
        If `banded` is True, `lband` and `uband` are determined by the
        values in `a`.


lam, v = np.linalg.eig(a)<EOL>c = np.linalg.solve(v, y0)<EOL>e = c * np.exp(lam * t.reshape(-<NUM_LIT:1>, <NUM_LIT:1>))<EOL>sol = e.dot(v.T)<EOL>return sol<EOL>

Analytical solution to the linear differential equations dy/dt = a*y.

The solution is only valid if `a` is diagonalizable.

Returns a 2-d array with shape (len(t), len(y0)).


<EOL>newjac = zeros((bjac.shape[<NUM_LIT:0>] + <NUM_LIT:1>, bjac.shape[<NUM_LIT:1>]))<EOL>newjac[<NUM_LIT:1>:,::<NUM_LIT:2>] = bjac[:, ::<NUM_LIT:2>]<EOL>newjac[:-<NUM_LIT:1>, <NUM_LIT:1>::<NUM_LIT:2>] = bjac[:, <NUM_LIT:1>::<NUM_LIT:2>]<EOL>return newjac<EOL>

Convert a real matrix of the form (for example)

    [0 0 A B]        [0 0 0 B]
    [0 0 C D]        [0 0 A D]
    [E F G H]   to   [0 F C H]
    [I J K L]        [E J G L]
                     [I 0 K 0]

That is, every other column is shifted up one.


def _vode_banded_jac_wrapper(jacfunc, ml, jac_params):

def jac_wrapper(t, y):<EOL><INDENT>jac = asarray(jacfunc(t, y, *jac_params))<EOL>padded_jac = vstack((jac, zeros((ml, jac.shape[<NUM_LIT:1>]))))<EOL>return padded_jac<EOL><DEDENT>return jac_wrapper<EOL>

Wrap a banded Jacobian function with a function that pads
the Jacobian with `ml` rows of zeros.


def set_initial_value(self, y, t=<NUM_LIT:0.0>):

if isscalar(y):<EOL><INDENT>y = [y]<EOL><DEDENT>n_prev = len(self._y)<EOL>if not n_prev:<EOL><INDENT>self.set_integrator('<STR_LIT>')  <EOL><DEDENT>self._y = asarray(y, self._integrator.scalar)<EOL>self.t = t<EOL>self._integrator.reset(len(self._y), self.jac is not None)<EOL>return self<EOL>


def set_integrator(self, name, **integrator_params):

integrator = find_integrator(name)<EOL>if integrator is None:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>' % name)<EOL><DEDENT>else:<EOL><INDENT>self._integrator = integrator(**integrator_params)<EOL>if not len(self._y):<EOL><INDENT>self.t = <NUM_LIT:0.0><EOL>self._y = array([<NUM_LIT:0.0>], self._integrator.scalar)<EOL><DEDENT>self._integrator.reset(len(self._y), self.jac is not None)<EOL><DEDENT>return self<EOL>

Set integrator by name.

Parameters
----------
name : str
    Name of the integrator.
integrator_params :
    Additional parameters for the integrator.


def integrate(self, t, step=<NUM_LIT:0>, relax=<NUM_LIT:0>):

if step and self._integrator.supports_step:<EOL><INDENT>mth = self._integrator.step<EOL><DEDENT>elif relax and self._integrator.supports_run_relax:<EOL><INDENT>mth = self._integrator.run_relax<EOL><DEDENT>else:<EOL><INDENT>mth = self._integrator.run<EOL><DEDENT>try:<EOL><INDENT>self._y, self.t = mth(self.f, self.jac or (lambda: None),<EOL>self._y, self.t, t,<EOL>self.f_params, self.jac_params)<EOL><DEDENT>except SystemError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return self._y<EOL>

Find y=y(t), set y as an initial condition, and return y.


try:<EOL><INDENT>self._integrator<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.set_integrator('<STR_LIT>')<EOL><DEDENT>return self._integrator.success == <NUM_LIT:1><EOL>


self.f_params = args<EOL>return self<EOL>

Set extra parameters for user-supplied function f.


self.jac_params = args<EOL>return self<EOL>

Set extra parameters for user-supplied function jac.


if self._integrator.supports_solout:<EOL><INDENT>self._integrator.set_solout(solout)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL><DEDENT>

Set callable to be called at every successful integration step.

Parameters
----------
solout : callable
    ``solout(t, y)`` is called at each internal integrator step,
    t is a scalar providing the current independent position
    y is the current soloution ``y.shape == (n,)``
    solout should return -1 to stop integration
    otherwise it should return None or 0


if name == '<STR_LIT>':<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>lband = integrator_params.get('<STR_LIT>')<EOL>uband = integrator_params.get('<STR_LIT>')<EOL>if lband is not None or uband is not None:<EOL><INDENT>integrator_params['<STR_LIT>'] = <NUM_LIT:2>*(lband or <NUM_LIT:0>) + <NUM_LIT:1><EOL>integrator_params['<STR_LIT>'] = <NUM_LIT:2>*(uband or <NUM_LIT:0>) + <NUM_LIT:1><EOL><DEDENT>return ode.set_integrator(self, name, **integrator_params)<EOL>

Set integrator by name.

Parameters
----------
name : str
    Name of the integrator
integrator_params :
    Additional parameters for the integrator.


y = asarray(y)<EOL>self.tmp = zeros(y.size * <NUM_LIT:2>, '<STR_LIT:float>')<EOL>self.tmp[::<NUM_LIT:2>] = real(y)<EOL>self.tmp[<NUM_LIT:1>::<NUM_LIT:2>] = imag(y)<EOL>return ode.set_initial_value(self, self.tmp, t)<EOL>


y = ode.integrate(self, t, step, relax)<EOL>return y[::<NUM_LIT:2>] + <NUM_LIT> * y[<NUM_LIT:1>::<NUM_LIT:2>]<EOL>


if self._integrator.supports_solout:<EOL><INDENT>self._integrator.set_solout(solout, complex=True)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL><DEDENT>


Prepare integrator for call: allocate memory, set flags, etc.
        n - number of equations.
        has_jac - if user has supplied function for evaluating Jacobian.


def run(self, f, jac, y0, t0, t1, f_params, jac_params):

raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>

Integrate from t=t0 to t=t1 using y0 as an initial condition.
        Return 2-tuple (y1,t1) where y1 is the result and t=t1
        defines the stoppage coordinate of the result.


def step(self, f, jac, y0, t0, t1, f_params, jac_params):

raise NotImplementedError('<STR_LIT>' %<EOL>self.__class__.__name__)<EOL>

Make one integration step and return (y1,t1).


def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params):

Integrate from t=t0 to t>=t1 and return (y1,t).


jac_is_banded = self.mu is not None or self.ml is not None<EOL>if jac_is_banded:<EOL><INDENT>if self.mu is None:<EOL><INDENT>self.mu = <NUM_LIT:0><EOL><DEDENT>if self.ml is None:<EOL><INDENT>self.ml = <NUM_LIT:0><EOL><DEDENT><DEDENT>if has_jac:<EOL><INDENT>if jac_is_banded:<EOL><INDENT>miter = <NUM_LIT:4><EOL><DEDENT>else:<EOL><INDENT>miter = <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>if jac_is_banded:<EOL><INDENT>if self.ml == self.mu == <NUM_LIT:0>:<EOL><INDENT>miter = <NUM_LIT:3>  <EOL><DEDENT>else:<EOL><INDENT>miter = <NUM_LIT:5>  <EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self.with_jacobian:<EOL><INDENT>miter = <NUM_LIT:2>  <EOL><DEDENT>else:<EOL><INDENT>miter = <NUM_LIT:0>  <EOL><DEDENT><DEDENT><DEDENT>mf = <NUM_LIT:10> * self.meth + miter<EOL>return mf<EOL>

Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`.

In the Fortran code, the legal values of `MF` are:
    10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25,
    -11, -12, -14, -15, -21, -22, -24, -25
but this python wrapper does not use negative values.

Returns

    mf  = 10*self.meth + miter

self.meth is the linear multistep method:
    self.meth == 1:  method="adams"
    self.meth == 2:  method="bdf"

miter is the correction iteration method:
    miter == 0:  Functional iteraton; no Jacobian involved.
    miter == 1:  Chord iteration with user-supplied full Jacobian
    miter == 2:  Chord iteration with internally computed full Jacobian
    miter == 3:  Chord iteration with internally computed diagonal Jacobian
    miter == 4:  Chord iteration with user-supplied banded Jacobian
    miter == 5:  Chord iteration with internally computed banded Jacobian

Side effects: If either self.mu or self.ml is not None and the other is None,
then the one that is None is set to 0.


if n in _cached_p_roots.cache:<EOL><INDENT>return _cached_p_roots.cache[n]<EOL><DEDENT>_cached_p_roots.cache[n] = p_roots(n)<EOL>return _cached_p_roots.cache[n]<EOL>

Cache p_roots results for speeding up multiple calls of the fixed_quad function.


[x,w] = _cached_p_roots(n)<EOL>x = real(x)<EOL>ainf, binf = map(isinf,(a,b))<EOL>if ainf or binf:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>y = (b-a)*(x+<NUM_LIT:1>)/<NUM_LIT> + a<EOL>return (b-a)/<NUM_LIT>*sum(w*func(y,*args),<NUM_LIT:0>), None<EOL>

Compute a definite integral using fixed-order Gaussian quadrature.

Integrate `func` from `a` to `b` using Gaussian quadrature of
order `n`.

Parameters
----------
func : callable
    A Python function or method to integrate (must accept vector inputs).
a : float
    Lower limit of integration.
b : float
    Upper limit of integration.
args : tuple, optional
    Extra arguments to pass to function, if any.
n : int, optional
    Order of quadrature integration. Default is 5.

Returns
-------
val : float
    Gaussian quadrature approximation to the integral

See Also
--------
quad : adaptive quadrature using QUADPACK
dblquad : double integrals
tplquad : triple integrals
romberg : adaptive Romberg quadrature
quadrature : adaptive Gaussian quadrature
romb : integrators for sampled data
simps : integrators for sampled data
cumtrapz : cumulative integration for sampled data
ode : ODE integrator
odeint : ODE integrator


def vectorize1(func, args=(), vec_func=False):

if vec_func:<EOL><INDENT>def vfunc(x):<EOL><INDENT>return func(x, *args)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>def vfunc(x):<EOL><INDENT>if isscalar(x):<EOL><INDENT>return func(x, *args)<EOL><DEDENT>x = asarray(x)<EOL>y0 = func(x[<NUM_LIT:0>], *args)<EOL>n = len(x)<EOL>if hasattr(y0, '<STR_LIT>'):<EOL><INDENT>output = empty((n,), dtype=y0.dtype)<EOL><DEDENT>else:<EOL><INDENT>output = empty((n,), dtype=type(y0))<EOL><DEDENT>output[<NUM_LIT:0>] = y0<EOL>for i in xrange(<NUM_LIT:1>, n):<EOL><INDENT>output[i] = func(x[i], *args)<EOL><DEDENT>return output<EOL><DEDENT><DEDENT>return vfunc<EOL>

Vectorize the call to a function.

    This is an internal utility function used by `romberg` and
    `quadrature` to create a vectorized version of a function.

    If `vec_func` is True, the function `func` is assumed to take vector
    arguments.

    Parameters
    ----------
    func : callable
        User defined function.
    args : tuple
        Extra arguments for the function.
    vec_func : bool
        True if the function func takes vector arguments.

    Returns
    -------
    vfunc : callable
        A function that will take a vector argument and return the
        result.


def quadrature(func, a, b, args=(), tol=<NUM_LIT>, rtol=<NUM_LIT>, maxiter=<NUM_LIT:50>,<EOL>vec_func=True, miniter=<NUM_LIT:1>):

if not isinstance(args, tuple):<EOL><INDENT>args = (args,)<EOL><DEDENT>vfunc = vectorize1(func, args, vec_func=vec_func)<EOL>val = np.inf<EOL>err = np.inf<EOL>maxiter = max(miniter+<NUM_LIT:1>, maxiter)<EOL>for n in xrange(miniter, maxiter+<NUM_LIT:1>):<EOL><INDENT>newval = fixed_quad(vfunc, a, b, (), n)[<NUM_LIT:0>]<EOL>err = abs(newval-val)<EOL>val = newval<EOL>if err < tol or err < rtol*abs(val):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>" % (maxiter, err),<EOL>AccuracyWarning)<EOL><DEDENT>return val, err<EOL>

Compute a definite integral using fixed-tolerance Gaussian quadrature.

Integrate `func` from `a` to `b` using Gaussian quadrature
with absolute tolerance `tol`.

Parameters
----------
func : function
    A Python function or method to integrate.
a : float
    Lower limit of integration.
b : float
    Upper limit of integration.
args : tuple, optional
    Extra arguments to pass to function.
tol, rol : float, optional
    Iteration stops when error between last two iterates is less than
    `tol` OR the relative change is less than `rtol`.
maxiter : int, optional
    Maximum order of Gaussian quadrature.
vec_func : bool, optional
    True or False if func handles arrays as arguments (is
    a "vector" function). Default is True.
miniter : int, optional
    Minimum order of Gaussian quadrature.

Returns
-------
val : float
    Gaussian quadrature approximation (within tolerance) to integral.
err : float
    Difference between last two estimates of the integral.

See also
--------
romberg: adaptive Romberg quadrature
fixed_quad: fixed-order Gaussian quadrature
quad: adaptive quadrature using QUADPACK
dblquad: double integrals
tplquad: triple integrals
romb: integrator for sampled data
simps: integrator for sampled data
cumtrapz: cumulative integration for sampled data
ode: ODE integrator
odeint: ODE integrator


def cumtrapz(y, x=None, dx=<NUM_LIT:1.0>, axis=-<NUM_LIT:1>, initial=None):

y = asarray(y)<EOL>if x is None:<EOL><INDENT>d = dx<EOL><DEDENT>else:<EOL><INDENT>x = asarray(x)<EOL>if x.ndim == <NUM_LIT:1>:<EOL><INDENT>d = diff(x)<EOL>shape = [<NUM_LIT:1>] * y.ndim<EOL>shape[axis] = -<NUM_LIT:1><EOL>d = d.reshape(shape)<EOL><DEDENT>elif len(x.shape) != len(y.shape):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>d = diff(x, axis=axis)<EOL><DEDENT>if d.shape[axis] != y.shape[axis] - <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>nd = len(y.shape)<EOL>slice1 = tupleset((slice(None),)*nd, axis, slice(<NUM_LIT:1>, None))<EOL>slice2 = tupleset((slice(None),)*nd, axis, slice(None, -<NUM_LIT:1>))<EOL>res = add.accumulate(d * (y[slice1] + y[slice2]) / <NUM_LIT>, axis)<EOL>if initial is not None:<EOL><INDENT>if not np.isscalar(initial):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>shape = list(res.shape)<EOL>shape[axis] = <NUM_LIT:1><EOL>res = np.concatenate([np.ones(shape, dtype=res.dtype) * initial, res],<EOL>axis=axis)<EOL><DEDENT>return res<EOL>

Cumulatively integrate y(x) using the composite trapezoidal rule.

Parameters
----------
y : array_like
    Values to integrate.
x : array_like, optional
    The coordinate to integrate along.  If None (default), use spacing `dx`
    between consecutive elements in `y`.
dx : int, optional
    Spacing between elements of `y`.  Only used if `x` is None.
axis : int, optional
    Specifies the axis to cumulate.  Default is -1 (last axis).
initial : scalar, optional
    If given, uses this value as the first value in the returned result.
    Typically this value should be 0.  Default is None, which means no
    value at ``x[0]`` is returned and `res` has one element less than `y`
    along the axis of integration.

Returns
-------
res : ndarray
    The result of cumulative integration of `y` along `axis`.
    If `initial` is None, the shape is such that the axis of integration
    has one less value than `y`.  If `initial` is given, the shape is equal
    to that of `y`.

See Also
--------
numpy.cumsum, numpy.cumprod
quad: adaptive quadrature using QUADPACK
romberg: adaptive Romberg quadrature
quadrature: adaptive Gaussian quadrature
fixed_quad: fixed-order Gaussian quadrature
dblquad: double integrals
tplquad: triple integrals
romb: integrators for sampled data
ode: ODE integrators
odeint: ODE integrators

Examples
--------
>>> from scipy import integrate
>>> import matplotlib.pyplot as plt

>>> x = np.linspace(-2, 2, num=20)
>>> y = x
>>> y_int = integrate.cumtrapz(y, x, initial=0)
>>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')
>>> plt.show()


def simps(y, x=None, dx=<NUM_LIT:1>, axis=-<NUM_LIT:1>, even='<STR_LIT>'):

y = asarray(y)<EOL>nd = len(y.shape)<EOL>N = y.shape[axis]<EOL>last_dx = dx<EOL>first_dx = dx<EOL>returnshape = <NUM_LIT:0><EOL>if x is not None:<EOL><INDENT>x = asarray(x)<EOL>if len(x.shape) == <NUM_LIT:1>:<EOL><INDENT>shapex = ones(nd)<EOL>shapex[axis] = x.shape[<NUM_LIT:0>]<EOL>saveshape = x.shape<EOL>returnshape = <NUM_LIT:1><EOL>x = x.reshape(tuple(shapex))<EOL><DEDENT>elif len(x.shape) != len(y.shape):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if x.shape[axis] != N:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>if N % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>val = <NUM_LIT:0.0><EOL>result = <NUM_LIT:0.0><EOL>slice1 = (slice(None),)*nd<EOL>slice2 = (slice(None),)*nd<EOL>if even not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if even in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>slice1 = tupleset(slice1, axis, -<NUM_LIT:1>)<EOL>slice2 = tupleset(slice2, axis, -<NUM_LIT:2>)<EOL>if x is not None:<EOL><INDENT>last_dx = x[slice1] - x[slice2]<EOL><DEDENT>val += <NUM_LIT:0.5>*last_dx*(y[slice1]+y[slice2])<EOL>result = _basic_simps(y,<NUM_LIT:0>,N-<NUM_LIT:3>,x,dx,axis)<EOL><DEDENT>if even in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>slice1 = tupleset(slice1, axis, <NUM_LIT:0>)<EOL>slice2 = tupleset(slice2, axis, <NUM_LIT:1>)<EOL>if x is not None:<EOL><INDENT>first_dx = x[tuple(slice2)] - x[tuple(slice1)]<EOL><DEDENT>val += <NUM_LIT:0.5>*first_dx*(y[slice2]+y[slice1])<EOL>result += _basic_simps(y,<NUM_LIT:1>,N-<NUM_LIT:2>,x,dx,axis)<EOL><DEDENT>if even == '<STR_LIT>':<EOL><INDENT>val /= <NUM_LIT><EOL>result /= <NUM_LIT><EOL><DEDENT>result = result + val<EOL><DEDENT>else:<EOL><INDENT>result = _basic_simps(y,<NUM_LIT:0>,N-<NUM_LIT:2>,x,dx,axis)<EOL><DEDENT>if returnshape:<EOL><INDENT>x = x.reshape(saveshape)<EOL><DEDENT>return result<EOL>

Integrate y(x) using samples along the given axis and the composite
Simpson's rule.  If x is None, spacing of dx is assumed.

If there are an even number of samples, N, then there are an odd
number of intervals (N-1), but Simpson's rule requires an even number
of intervals.  The parameter 'even' controls how this is handled.

Parameters
----------
y : array_like
    Array to be integrated.
x : array_like, optional
    If given, the points at which `y` is sampled.
dx : int, optional
    Spacing of integration points along axis of `y`. Only used when
    `x` is None. Default is 1.
axis : int, optional
    Axis along which to integrate. Default is the last axis.
even : {'avg', 'first', 'str'}, optional
    'avg' : Average two results:1) use the first N-2 intervals with
              a trapezoidal rule on the last interval and 2) use the last
              N-2 intervals with a trapezoidal rule on the first interval.

    'first' : Use Simpson's rule for the first N-2 intervals with
            a trapezoidal rule on the last interval.

    'last' : Use Simpson's rule for the last N-2 intervals with a
           trapezoidal rule on the first interval.

See Also
--------
quad: adaptive quadrature using QUADPACK
romberg: adaptive Romberg quadrature
quadrature: adaptive Gaussian quadrature
fixed_quad: fixed-order Gaussian quadrature
dblquad: double integrals
tplquad: triple integrals
romb: integrators for sampled data
cumtrapz: cumulative integration for sampled data
ode: ODE integrators
odeint: ODE integrators

Notes
-----
For an odd number of samples that are equally spaced the result is
exact if the function is a polynomial of order 3 or less.  If
the samples are not equally spaced, then the result is exact only
if the function is a polynomial of order 2 or less.


def romb(y, dx=<NUM_LIT:1.0>, axis=-<NUM_LIT:1>, show=False):

y = asarray(y)<EOL>nd = len(y.shape)<EOL>Nsamps = y.shape[axis]<EOL>Ninterv = Nsamps-<NUM_LIT:1><EOL>n = <NUM_LIT:1><EOL>k = <NUM_LIT:0><EOL>while n < Ninterv:<EOL><INDENT>n <<= <NUM_LIT:1><EOL>k += <NUM_LIT:1><EOL><DEDENT>if n != Ninterv:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>R = {}<EOL>all = (slice(None),) * nd<EOL>slice0 = tupleset(all, axis, <NUM_LIT:0>)<EOL>slicem1 = tupleset(all, axis, -<NUM_LIT:1>)<EOL>h = Ninterv*asarray(dx)*<NUM_LIT:1.0><EOL>R[(<NUM_LIT:0>,<NUM_LIT:0>)] = (y[slice0] + y[slicem1])/<NUM_LIT>*h<EOL>slice_R = all<EOL>start = stop = step = Ninterv<EOL>for i in range(<NUM_LIT:1>,k+<NUM_LIT:1>):<EOL><INDENT>start >>= <NUM_LIT:1><EOL>slice_R = tupleset(slice_R, axis, slice(start,stop,step))<EOL>step >>= <NUM_LIT:1><EOL>R[(i,<NUM_LIT:0>)] = <NUM_LIT:0.5>*(R[(i-<NUM_LIT:1>,<NUM_LIT:0>)] + h*add.reduce(y[slice_R],axis))<EOL>for j in range(<NUM_LIT:1>,i+<NUM_LIT:1>):<EOL><INDENT>R[(i,j)] = R[(i,j-<NUM_LIT:1>)] +(R[(i,j-<NUM_LIT:1>)]-R[(i-<NUM_LIT:1>,j-<NUM_LIT:1>)]) / ((<NUM_LIT:1> << (<NUM_LIT:2>*j))-<NUM_LIT:1>)<EOL><DEDENT>h = h / <NUM_LIT><EOL><DEDENT>if show:<EOL><INDENT>if not isscalar(R[(<NUM_LIT:0>,<NUM_LIT:0>)]):<EOL><INDENT>print("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>precis = show[<NUM_LIT:0>]<EOL><DEDENT>except (TypeError, IndexError):<EOL><INDENT>precis = <NUM_LIT:5><EOL><DEDENT>try:<EOL><INDENT>width = show[<NUM_LIT:1>]<EOL><DEDENT>except (TypeError, IndexError):<EOL><INDENT>width = <NUM_LIT:8><EOL><DEDENT>formstr = "<STR_LIT:%>" + str(width) + '<STR_LIT:.>' + str(precis)+'<STR_LIT:f>'<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>for i in range(<NUM_LIT:0>,k+<NUM_LIT:1>):<EOL><INDENT>for j in range(<NUM_LIT:0>,i+<NUM_LIT:1>):<EOL><INDENT>print(formstr % R[(i,j)], end='<STR_LIT:U+0020>')<EOL><DEDENT>print()<EOL><DEDENT>print("<STR_LIT>")<EOL><DEDENT><DEDENT>return R[(k,k)]<EOL>

Romberg integration using samples of a function.

Parameters
----------
y : array_like
    A vector of ``2**k + 1`` equally-spaced samples of a function.
dx : float, optional
    The sample spacing. Default is 1.
axis : int, optional
    The axis along which to integrate. Default is -1 (last axis).
show : bool, optional
    When `y` is a single 1-D array, then if this argument is True
    print the table showing Richardson extrapolation from the
    samples. Default is False.

Returns
-------
romb : ndarray
    The integrated result for `axis`.

See also
--------
quad : adaptive quadrature using QUADPACK
romberg : adaptive Romberg quadrature
quadrature : adaptive Gaussian quadrature
fixed_quad : fixed-order Gaussian quadrature
dblquad : double integrals
tplquad : triple integrals
simps : integrators for sampled data
cumtrapz : cumulative integration for sampled data
ode : ODE integrators
odeint : ODE integrators


def _difftrap(function, interval, numtraps):

if numtraps <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif numtraps == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0.5>*(function(interval[<NUM_LIT:0>])+function(interval[<NUM_LIT:1>]))<EOL><DEDENT>else:<EOL><INDENT>numtosum = numtraps/<NUM_LIT:2><EOL>h = float(interval[<NUM_LIT:1>]-interval[<NUM_LIT:0>])/numtosum<EOL>lox = interval[<NUM_LIT:0>] + <NUM_LIT:0.5> * h<EOL>points = lox + h * arange(<NUM_LIT:0>, numtosum)<EOL>s = sum(function(points),<NUM_LIT:0>)<EOL>return s<EOL><DEDENT>

Perform part of the trapezoidal rule to integrate a function.
Assume that we had called difftrap with all lower powers-of-2
starting with 1.  Calling difftrap only returns the summation
of the new ordinates.  It does _not_ multiply by the width
of the trapezoids.  This must be performed by the caller.
    'function' is the function to evaluate (must accept vector arguments).
    'interval' is a sequence with lower and upper limits
               of integration.
    'numtraps' is the number of trapezoids to use (must be a
               power-of-2).


tmp = <NUM_LIT>**k<EOL>return (tmp * c - b)/(tmp - <NUM_LIT:1.0>)<EOL>

Compute the differences for the Romberg quadrature corrections.
See Forman Acton's "Real Computing Made Real," p 143.


def romberg(function, a, b, args=(), tol=<NUM_LIT>, rtol=<NUM_LIT>, show=False,<EOL>divmax=<NUM_LIT:10>, vec_func=False):

if isinf(a) or isinf(b):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>vfunc = vectorize1(function, args, vec_func=vec_func)<EOL>n = <NUM_LIT:1><EOL>interval = [a,b]<EOL>intrange = b-a<EOL>ordsum = _difftrap(vfunc, interval, n)<EOL>result = intrange * ordsum<EOL>resmat = [[result]]<EOL>err = np.inf<EOL>for i in xrange(<NUM_LIT:1>, divmax+<NUM_LIT:1>):<EOL><INDENT>n = n * <NUM_LIT:2><EOL>ordsum = ordsum + _difftrap(vfunc, interval, n)<EOL>resmat.append([])<EOL>resmat[i].append(intrange * ordsum / n)<EOL>for k in range(i):<EOL><INDENT>resmat[i].append(_romberg_diff(resmat[i-<NUM_LIT:1>][k], resmat[i][k], k+<NUM_LIT:1>))<EOL><DEDENT>result = resmat[i][i]<EOL>lastresult = resmat[i-<NUM_LIT:1>][i-<NUM_LIT:1>]<EOL>err = abs(result - lastresult)<EOL>if err < tol or err < rtol*abs(result):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>" % (divmax, err),<EOL>AccuracyWarning)<EOL><DEDENT>if show:<EOL><INDENT>_printresmat(vfunc, interval, resmat)<EOL><DEDENT>return result<EOL>

Romberg integration of a callable function or method.

Returns the integral of `function` (a function of one variable)
over the interval (`a`, `b`).

If `show` is 1, the triangular array of the intermediate results
will be printed.  If `vec_func` is True (default is False), then
`function` is assumed to support vector arguments.

Parameters
----------
function : callable
    Function to be integrated.
a : float
    Lower limit of integration.
b : float
    Upper limit of integration.

Returns
-------
results  : float
    Result of the integration.

Other Parameters
----------------
args : tuple, optional
    Extra arguments to pass to function. Each element of `args` will
    be passed as a single argument to `func`. Default is to pass no
    extra arguments.
tol, rtol : float, optional
    The desired absolute and relative tolerances. Defaults are 1.48e-8.
show : bool, optional
    Whether to print the results. Default is False.
divmax : int, optional
    Maximum order of extrapolation. Default is 10.
vec_func : bool, optional
    Whether `func` handles arrays as arguments (i.e whether it is a
    "vector" function). Default is False.

See Also
--------
fixed_quad : Fixed-order Gaussian quadrature.
quad : Adaptive quadrature using QUADPACK.
dblquad : Double integrals.
tplquad : Triple integrals.
romb : Integrators for sampled data.
simps : Integrators for sampled data.
cumtrapz : Cumulative integration for sampled data.
ode : ODE integrator.
odeint : ODE integrator.

References
----------
.. [1] 'Romberg's method' http://en.wikipedia.org/wiki/Romberg%27s_method

Examples
--------
Integrate a gaussian from 0 to 1 and compare to the error function.

>>> from scipy import integrate
>>> from scipy.special import erf
>>> gaussian = lambda x: 1/np.sqrt(np.pi) * np.exp(-x**2)
>>> result = integrate.romberg(gaussian, 0, 1, show=True)
Romberg integration of <function vfunc at ...> from [0, 1]

::

   Steps  StepSize  Results
       1  1.000000  0.385872
       2  0.500000  0.412631  0.421551
       4  0.250000  0.419184  0.421368  0.421356
       8  0.125000  0.420810  0.421352  0.421350  0.421350
      16  0.062500  0.421215  0.421350  0.421350  0.421350  0.421350
      32  0.031250  0.421317  0.421350  0.421350  0.421350  0.421350  0.421350

The final result is 0.421350396475 after 33 function evaluations.

>>> print("%g %g" % (2*result, erf(1)))
0.842701 0.842701


try:<EOL><INDENT>N = len(rn)-<NUM_LIT:1><EOL>if equal:<EOL><INDENT>rn = np.arange(N+<NUM_LIT:1>)<EOL><DEDENT>elif np.all(np.diff(rn) == <NUM_LIT:1>):<EOL><INDENT>equal = <NUM_LIT:1><EOL><DEDENT><DEDENT>except:<EOL><INDENT>N = rn<EOL>rn = np.arange(N+<NUM_LIT:1>)<EOL>equal = <NUM_LIT:1><EOL><DEDENT>if equal and N in _builtincoeffs:<EOL><INDENT>na, da, vi, nb, db = _builtincoeffs[N]<EOL>return na*np.array(vi,float)/da, float(nb)/db<EOL><DEDENT>if (rn[<NUM_LIT:0>] != <NUM_LIT:0>) or (rn[-<NUM_LIT:1>] != N):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>yi = rn / float(N)<EOL>ti = <NUM_LIT>*yi - <NUM_LIT:1><EOL>nvec = np.arange(<NUM_LIT:0>,N+<NUM_LIT:1>)<EOL>C = ti**nvec[:,np.newaxis]<EOL>Cinv = np.linalg.inv(C)<EOL>for i in range(<NUM_LIT:2>):<EOL><INDENT>Cinv = <NUM_LIT:2>*Cinv - Cinv.dot(C).dot(Cinv)<EOL><DEDENT>vec = <NUM_LIT> / (nvec[::<NUM_LIT:2>]+<NUM_LIT:1>)<EOL>ai = np.dot(Cinv[:,::<NUM_LIT:2>],vec) * N/<NUM_LIT:2><EOL>if (N % <NUM_LIT:2> == <NUM_LIT:0>) and equal:<EOL><INDENT>BN = N/(N+<NUM_LIT>)<EOL>power = N+<NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>BN = N/(N+<NUM_LIT>)<EOL>power = N+<NUM_LIT:1><EOL><DEDENT>BN = BN - np.dot(yi**power, ai)<EOL>p1 = power+<NUM_LIT:1><EOL>fac = power*math.log(N) - gammaln(p1)<EOL>fac = math.exp(fac)<EOL>return ai, BN*fac<EOL>

Return weights and error coefficient for Newton-Cotes integration.

Suppose we have (N+1) samples of f at the positions
x_0, x_1, ..., x_N.  Then an N-point Newton-Cotes formula for the
integral between x_0 and x_N is:

:math:`\\int_{x_0}^{x_N} f(x)dx = \\Delta x \\sum_{i=0}^{N} a_i f(x_i)
+ B_N (\\Delta x)^{N+2} f^{N+1} (\\xi)`

where :math:`\\xi \\in [x_0,x_N]` and :math:`\\Delta x = \\frac{x_N-x_0}{N}`
is the averages samples spacing.

If the samples are equally-spaced and N is even, then the error
term is :math:`B_N (\\Delta x)^{N+3} f^{N+2}(\\xi)`.

Parameters
----------
rn : int
    The integer order for equally-spaced data or the relative positions of
    the samples with the first sample at 0 and the last at N, where N+1 is
    the length of `rn`.  N is the order of the Newton-Cotes integration.
equal : int, optional
    Set to 1 to enforce equally spaced data.

Returns
-------
an : ndarray
    1-D array of weights to apply to the function at the provided sample
    positions.
B : float
    Error coefficient.

Notes
-----
Normally, the Newton-Cotes rules are used on smaller integration
regions and a composite rule is used to return the total integral.


Print extra information about integrate.quad() parameters and returns.

Parameters
----------
output : instance with "write" method
    Information about `quad` is passed to ``output.write()``.
    Default is ``sys.stdout``.

Returns
-------
None