from hashlib import sha256<EOL>base = '<STR_LIT>'<EOL>return base + sha256(expr).hexdigest()[:<NUM_LIT:32>]<EOL>

Convert an arbitrary expr string to a valid file name.

        The name is based on the SHA-256 check sum for the string and
        Something that was a little more human readable would be
        nice, but the computer doesn't seem to care.


files = os.listdir(d)<EOL>base = expr_to_filename(expr)<EOL>for i in xrange(<NUM_LIT>):<EOL><INDENT>fname = base + repr(i)<EOL>if not (fname+'<STR_LIT>' in files or<EOL>fname+'<STR_LIT>' in files or<EOL>fname+'<STR_LIT>' in files or<EOL>fname+'<STR_LIT>' in files or<EOL>fname+'<STR_LIT>' in files or<EOL>fname+'<STR_LIT>' in files):<EOL><INDENT>break<EOL><DEDENT><DEDENT>return os.path.join(d,fname)<EOL>

Generate a unqiue file name based on expr in directory d

        This is meant for use with building extension modules, so
        a file name is considered unique if none of the following
        extension '.cpp','.o','.so','module.so','.py', or '.pyd'
        exists in directory d.  The fully qualified path to the
        new name is returned.  You'll need to append your own
        extension to it before creating files.


if not os.path.isdir(dir):<EOL><INDENT>return False<EOL><DEDENT>prefix = '<STR_LIT>' % (socket.gethostname(),os.getpid())<EOL>try:<EOL><INDENT>tmp = tempfile.TemporaryFile(prefix=prefix,dir=dir)<EOL><DEDENT>except OSError:<EOL><INDENT>return False<EOL><DEDENT>tmp.close()<EOL>return True<EOL>

Determine whether a given directory is writable in a portable manner.

    Parameters
    ----------
    dir : str
        A string represeting a path to a directory on the filesystem.

    Returns
    -------
    res : bool
        True or False.


return os.environ.get("<STR_LIT>") or os.environ.get("<STR_LIT>") or "<STR_LIT>"<EOL>


try:<EOL><INDENT>os.makedirs(path, mode=<NUM_LIT>)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>


path_candidates = []<EOL>python_name = "<STR_LIT>" % tuple(sys.version_info[:<NUM_LIT:2>])<EOL>if tmp_dir:<EOL><INDENT>home_dir = tmp_dir<EOL><DEDENT>else:<EOL><INDENT>home_dir = os.path.expanduser('<STR_LIT>')<EOL><DEDENT>tmp_dir = tmp_dir or tempfile.gettempdir()<EOL>xdg_cache = (os.environ.get("<STR_LIT>", None) or<EOL>os.path.join(home_dir, '<STR_LIT>'))<EOL>xdg_temp_dir = os.path.join(xdg_cache, '<STR_LIT>', python_name)<EOL>path_candidates.append(xdg_temp_dir)<EOL>home_temp_dir_name = '<STR_LIT:.>' + python_name<EOL>home_temp_dir = os.path.join(home_dir, home_temp_dir_name)<EOL>path_candidates.append(home_temp_dir)<EOL>temp_dir_name = repr(os.getuid()) + '<STR_LIT:_>' + python_name<EOL>temp_dir_path = os.path.join(tmp_dir, temp_dir_name)<EOL>path_candidates.append(temp_dir_path)<EOL>for path in path_candidates:<EOL><INDENT>_create_dirs(path)<EOL>if check_dir(path):<EOL><INDENT>return path<EOL><DEDENT><DEDENT>tmp_dir_path = find_valid_temp_dir(temp_dir_name, tmp_dir)<EOL>if not tmp_dir_path:<EOL><INDENT>tmp_dir_path = create_temp_dir(temp_dir_name, tmp_dir=tmp_dir)<EOL><DEDENT>return tmp_dir_path<EOL>

Create or find default catalog store for posix systems

purpose of 'tmp_dir' is to enable way how to test this function easily


def create_win_temp_dir(prefix, inner_dir=None, tmp_dir=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>tmp_dir_path = find_valid_temp_dir(prefix, tmp_dir)<EOL>if tmp_dir_path:<EOL><INDENT>if inner_dir:<EOL><INDENT>tmp_dir_path = os.path.join(tmp_dir_path, inner_dir)<EOL>if not os.path.isdir(tmp_dir_path):<EOL><INDENT>os.mkdir(tmp_dir_path, <NUM_LIT>)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>tmp_dir_path = create_temp_dir(prefix, inner_dir, tmp_dir)<EOL><DEDENT>return tmp_dir_path<EOL><DEDENT>python_name = "<STR_LIT>" % tuple(sys.version_info[:<NUM_LIT:2>])<EOL>tmp_dir = tmp_dir or tempfile.gettempdir()<EOL>temp_dir_name = "<STR_LIT:%s>" % whoami()<EOL>temp_root_dir = os.path.join(tmp_dir, temp_dir_name)<EOL>temp_dir_path = os.path.join(temp_root_dir, python_name)<EOL>_create_dirs(temp_dir_path)<EOL>if check_dir(temp_dir_path) and check_dir(temp_root_dir):<EOL><INDENT>return temp_dir_path<EOL><DEDENT>else:<EOL><INDENT>if check_dir(temp_root_dir):<EOL><INDENT>return create_win_temp_dir(python_name, tmp_dir=temp_root_dir)<EOL><DEDENT>else:<EOL><INDENT>return create_win_temp_dir(temp_dir_name, python_name, tmp_dir)<EOL><DEDENT><DEDENT>

Create or find default catalog store for Windows systems

purpose of 'tmp_dir' is to enable way how to test this function easily


<EOL>if hasattr(default_dir, "<STR_LIT>") andcheck_dir(default_dir.cached_path):<EOL><INDENT>return default_dir.cached_path<EOL><DEDENT>if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>path = default_dir_win()<EOL><DEDENT>else:<EOL><INDENT>path = default_dir_posix()<EOL><DEDENT>default_dir.cached_path = path<EOL>return path<EOL>

Return a default location to store compiled files and catalogs.

        XX is the Python version number in all paths listed below
        On windows, the default location is the temporary directory
        returned by gettempdir()/pythonXX.

        On Unix, ~/.pythonXX_compiled is the default location.  If it doesn't
        exist, it is created.  The directory is marked rwx------.

        If for some reason it isn't possible to build a default directory
        in the user's home, /tmp/<uid>_pythonXX_compiled is used.  If it
        doesn't exist, it is created.  The directory is marked rwx------
        to try and keep people from being able to sneak a bad module
        in on you. If the directory already exists in /tmp/ and is not
        secure, new one is created.


def check_is_dir():<EOL><INDENT>return os.path.isdir(im_dir)<EOL><DEDENT>def check_permissions():<EOL><INDENT>"""<STR_LIT>"""<EOL>writable = is_writable(im_dir)<EOL>if sys.platform != '<STR_LIT:win32>':<EOL><INDENT>try:<EOL><INDENT>im_dir_stat = os.stat(im_dir)<EOL><DEDENT>except OSError:<EOL><INDENT>return False<EOL><DEDENT>writable &= stat.S_IMODE(im_dir_stat.st_mode) == <NUM_LIT><EOL><DEDENT>return writable<EOL><DEDENT>def check_ownership():<EOL><INDENT>"""<STR_LIT>"""<EOL>if sys.platform != '<STR_LIT:win32>':<EOL><INDENT>try:<EOL><INDENT>im_dir_stat = os.stat(im_dir)<EOL><DEDENT>except OSError:<EOL><INDENT>return False<EOL><DEDENT>proc_uid = os.getuid()<EOL>return proc_uid == im_dir_stat.st_uid<EOL><DEDENT>return True<EOL><DEDENT>def check_is_symlink():<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>return not os.path.islink(im_dir)<EOL><DEDENT>except OSError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>checks = [check_is_dir, check_permissions,<EOL>check_ownership, check_is_symlink]<EOL>for check in checks:<EOL><INDENT>if not check():<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

Check if dir is safe; if it is, return True.
These checks make sense only on posix:
 * directory has correct owner
 * directory has correct permissions (0700)
 * directory is not a symlink


def create_temp_dir(prefix, inner_dir=None, tmp_dir=None):

if not tmp_dir:<EOL><INDENT>tmp_dir_path = tempfile.mkdtemp(prefix=prefix)<EOL><DEDENT>else:<EOL><INDENT>tmp_dir_path = tempfile.mkdtemp(prefix=prefix, dir=tmp_dir)<EOL><DEDENT>if inner_dir:<EOL><INDENT>tmp_dir_path = os.path.join(tmp_dir_path, inner_dir)<EOL>os.mkdir(tmp_dir_path, <NUM_LIT>)<EOL><DEDENT>return tmp_dir_path<EOL>

Create intermediate dirs <tmp>/<prefix+random suffix>/<inner_dir>/

argument 'tmp_dir' is used in unit tests


return "<STR_LIT>" % ("<STR_LIT>", whoami())<EOL>

Prefix of root intermediate dir (<tmp>/<root_im_dir>).


matches = []<EOL>tmp_dir = tmp_dir or tempfile.gettempdir()<EOL>for tmp_file in os.listdir(tmp_dir):<EOL><INDENT>if tmp_file.startswith(prefix):<EOL><INDENT>matches.append(os.path.join(tmp_dir, tmp_file))<EOL><DEDENT><DEDENT>return matches<EOL>

Find temp dirs in 'tmp_dir' starting with 'prefix


matches = find_temp_dir(prefix, tmp_dir)<EOL>for match in matches:<EOL><INDENT>if check_dir(match):<EOL><INDENT>return match<EOL><DEDENT><DEDENT>

Try to look for existing temp dirs.
If there is one suitable found, return it, otherwise return None.


name = "<STR_LIT>" % tuple(sys.version_info[:<NUM_LIT:2>])<EOL>return name<EOL>

Name of intermediate dir for current python interpreter:
<temp dir>/<name>/pythonXY_intermediate/


im_dir = find_valid_temp_dir(intermediate_dir_prefix(), tmp_dir)<EOL>py_im_dir = py_intermediate_dir()<EOL>if im_dir is None:<EOL><INDENT>py_im_dir = py_intermediate_dir()<EOL>im_dir = create_intermediate_dir(tmp_dir)<EOL><DEDENT>else:<EOL><INDENT>im_dir = os.path.join(im_dir, py_im_dir)<EOL>if not os.path.isdir(im_dir):<EOL><INDENT>os.mkdir(im_dir, <NUM_LIT>)<EOL><DEDENT><DEDENT>return im_dir<EOL>

Temporary directory for storing .cpp and .o files during builds.

First, try to find the dir and if it exists, verify it is safe.
Otherwise, create it.


version = '<STR_LIT>' % sys.version_info[:<NUM_LIT:2>]<EOL>return sys.platform+version+'<STR_LIT>'<EOL>

Generate catalog name dependent on OS and Python version being used.

        This allows multiple platforms to have catalog files in the
        same directory without stepping on each other.  For now, it
        bases the name of the value returned by sys.platform and the
        version of python being run.  If this isn't enough to descriminate
        on some platforms, we can try to add other info.  It has
        occurred to me that if we get fancy enough to optimize for different
        architectures, then chip type might be added to the catalog name also.


module_path = os.path.expanduser(module_path)<EOL>module_path = os.path.expandvars(module_path)<EOL>module_path = os.path.abspath(module_path)<EOL>if not os.path.exists(module_path):<EOL><INDENT>catalog_file = None<EOL><DEDENT>elif not os.path.isdir(module_path):<EOL><INDENT>module_path,dummy = os.path.split(module_path)<EOL>catalog_file = os.path.join(module_path,os_dependent_catalog_name())<EOL><DEDENT>else:<EOL><INDENT>catalog_file = os.path.join(module_path,os_dependent_catalog_name())<EOL><DEDENT>return catalog_file<EOL>

Return the full path name for the catalog file in the given directory.

        module_path can either be a file name or a path name.  If it is a
        file name, the catalog file name in its parent directory is returned.
        If it is a directory, the catalog file in that directory is returned.

        If module_path doesn't exist, None is returned.  Note though, that the
        catalog file does *not* have to exist, only its parent.  '~', shell
        variables, and relative ('.' and '..') paths are all acceptable.

        catalog file names are os dependent (based on sys.platform), so this
        should support multiple platforms sharing the same disk space
        (NFS mounts). See os_dependent_catalog_name() for more info.


if mode not in ['<STR_LIT:c>','<STR_LIT:r>','<STR_LIT:w>','<STR_LIT:n>']:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>catalog_file = catalog_path(module_path)<EOL>if (catalog_file is not None)and ((dumb and os.path.exists(catalog_file+'<STR_LIT>'))<EOL>or os.path.exists(catalog_file)):<EOL><INDENT>sh = shelve.open(catalog_file,mode)<EOL><DEDENT>else:<EOL><INDENT>if mode == '<STR_LIT:r>':<EOL><INDENT>sh = None<EOL><DEDENT>else:<EOL><INDENT>sh = shelve.open(catalog_file,mode)<EOL><DEDENT><DEDENT>return sh<EOL>

Return a function catalog (shelve object) from the path module_path

        If module_path is a directory, the function catalog returned is
        from that directory.  If module_path is an actual module_name,
        then the function catalog returned is from its parent directory.
        mode uses the standard 'c' = create, 'n' = new, 'r' = read,
        'w' = write file open modes available for anydbm databases.

        Well... it should be.  Stuck with dumbdbm for now and the modes
        almost don't matter.  We do some checking for 'r' mode, but that
        is about it.

        See catalog_path() for more information on module_path.


if isinstance(user_path_list, str):<EOL><INDENT>self.user_path_list = [user_path_list]<EOL><DEDENT>elif user_path_list:<EOL><INDENT>self.user_path_list = user_path_list<EOL><DEDENT>else:<EOL><INDENT>self.user_path_list = []<EOL><DEDENT>self.cache = {}<EOL>self.module_dir = None<EOL>self.paths_added = <NUM_LIT:0><EOL>sys.path.append(default_dir())<EOL>

Create a catalog for storing/searching for compiled functions.

            user_path_list contains directories that should be searched
            first for function catalogs.  They will come before the path
            entries in the PYTHONCOMPILED environment varilable.


self.module_dir = module_dir<EOL>

Set the path that will replace 'MODULE' in catalog searches.

            You should call clear_module_directory() when your finished
            working with it.


return self.module_dir<EOL>

Return the path used to replace the 'MODULE' in searches.


self.module_dir = None<EOL>

Reset 'MODULE' path to None so that it is ignored in searches.


paths = []<EOL>if '<STR_LIT>' in os.environ:<EOL><INDENT>path_string = os.environ['<STR_LIT>']<EOL>paths = path_string.split(os.path.pathsep)<EOL><DEDENT>return paths<EOL>

Return list of paths from 'PYTHONCOMPILED' environment variable.

            On Unix the path in PYTHONCOMPILED is a ':' separated list of
            directories.  On Windows, a ';' separated list is used.


paths = self.user_path_list + self.get_environ_path()<EOL>search_order = []<EOL>for path in paths:<EOL><INDENT>if path == '<STR_LIT>':<EOL><INDENT>if self.module_dir:<EOL><INDENT>search_order.append(self.module_dir)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>search_order.append(path)<EOL><DEDENT><DEDENT>search_order.append(default_dir())<EOL>return search_order<EOL>

Returns a list of paths that are searched for catalogs.

            Values specified in the catalog constructor are searched first,
            then values found in the PYTHONCOMPILED environment variable.
            The directory returned by default_dir() is always returned at
            the end of the list.

            There is a 'magic' path name called 'MODULE' that is replaced
            by the directory defined by set_module_directory().  If the
            module directory hasn't been set, 'MODULE' is ignored.


files = map(catalog_path,self.build_search_order())<EOL>files = filter(lambda x: x is not None,files)<EOL>return files<EOL>

Returns catalog file list in correct search order.

            Some of the catalog files may not currently exists.
            However, all will be valid locations for a catalog
            to be created (if you have write permission).


files = self.get_catalog_files()<EOL>existing_files = []<EOL>for file in files:<EOL><INDENT>cat = get_catalog(os.path.dirname(file),'<STR_LIT:r>')<EOL>if cat is not None:<EOL><INDENT>existing_files.append(file)<EOL>cat.close()<EOL><DEDENT><DEDENT>return existing_files<EOL>

Returns all existing catalog file list in correct search order.


<EOL>if existing_only:<EOL><INDENT>files = self.get_existing_files()<EOL><DEDENT>else:<EOL><INDENT>files = self.get_catalog_files()<EOL><DEDENT>def file_test(x):<EOL><INDENT>from os import access, F_OK, W_OK<EOL>return (access(x,F_OK) and access(x,W_OK) or<EOL>access(os.path.dirname(x),W_OK))<EOL><DEDENT>writable = filter(file_test,files)<EOL>if writable:<EOL><INDENT>file = writable[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>file = None<EOL><DEDENT>return file<EOL>

Return the name of the first writable catalog file.

            Its parent directory must also be writable.  This is so that
            compiled modules can be written to the same directory.


return os.path.dirname(self.get_writable_file())<EOL>

Return the parent directory of first writable catalog file.

            The returned directory has write access.


if module_dir is not None:<EOL><INDENT>self.set_module_directory(module_dir)<EOL><DEDENT>try:<EOL><INDENT>d = self.get_writable_dir()<EOL><DEDENT>finally:<EOL><INDENT>if module_dir is not None:<EOL><INDENT>self.clear_module_directory()<EOL><DEDENT><DEDENT>return unique_file(d, code)<EOL>

Return full path to unique file name that in writable location.

            The directory for the file is the first writable directory in
            the catalog search path.  The unique file name is derived from
            the code fragment.  If, module_dir is specified, it is used
            to replace 'MODULE' in the search path.


return '<STR_LIT>' + code<EOL>

Return key for path information for functions associated with code.


try:<EOL><INDENT>paths = cat[self.path_key(code)]<EOL>self.paths_added = len(paths)<EOL>sys.path = paths + sys.path<EOL><DEDENT>except:<EOL><INDENT>self.paths_added = <NUM_LIT:0><EOL><DEDENT>

Add the python path for the given code to the sys.path

            unconfigure_path() should be called as soon as possible after
            imports associated with code are finished so that sys.path
            is restored to normal.


sys.path = sys.path[self.paths_added:]<EOL>self.paths_added = <NUM_LIT:0><EOL>

Restores sys.path to normal after calls to configure_path()

            Remove the previously added paths from sys.path


mode = '<STR_LIT:r>'<EOL>cat = None<EOL>function_list = []<EOL>for path in self.build_search_order():<EOL><INDENT>cat = get_catalog(path,mode)<EOL>if cat is not None and code in cat:<EOL><INDENT>self.configure_path(cat,code)<EOL>try:<EOL><INDENT>function_list += cat[code]<EOL><DEDENT>except:  <EOL><INDENT>cat.close()<EOL>self.repair_catalog(path,code)<EOL><DEDENT>self.unconfigure_path()<EOL><DEDENT>if cat is not None:<EOL><INDENT>cat.close()<EOL><DEDENT><DEDENT>return function_list<EOL>

Load all functions associated with code from catalog search path.

            Sometimes there can be trouble loading a function listed in a
            catalog file because the actual module that holds the function
            has been moved or deleted.  When this happens, that catalog file
            is "repaired", meaning the entire entry for this function is
            removed from the file.  This only affects the catalog file that
            has problems -- not the others in the search path.

            The "repair" behavior may not be needed, but I'll keep it for now.


writable_cat = None<EOL>if (catalog_path is not None) and (not os.path.exists(catalog_path)):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>writable_cat = get_catalog(catalog_path,'<STR_LIT:w>')<EOL><DEDENT>except:<EOL><INDENT>warnings.warn('<STR_LIT>' %<EOL>(code, catalog_path))<EOL>writable_cat.close()<EOL>return<EOL><DEDENT>if code in writable_cat:<EOL><INDENT>del writable_cat[code]<EOL><DEDENT>path_key = self.path_key(code)<EOL>if path_key in writable_cat:<EOL><INDENT>del writable_cat[path_key]<EOL><DEDENT>writable_cat.close()<EOL>

Remove entry for code from catalog_path

            Occasionally catalog entries could get corrupted. An example
            would be when a module that had functions in the catalog was
            deleted or moved on the disk.  The best current repair method is
            just to trash the entire catalog entry for this piece of code.
            This may loose function entries that are valid, but thats life.

            catalog_path must be writable for repair.  If it isn't, the
            function exists with a warning.


return self.cache.get(code,[])<EOL>

Return list of functions for code from the cache.

            Return an empty list if the code entry is not found.


<EOL>if code in self.cache:<EOL><INDENT>return self.cache[code]<EOL><DEDENT>try:<EOL><INDENT>self.set_module_directory(module_dir)<EOL>function_list = self.get_cataloged_functions(code)<EOL>if function_list:<EOL><INDENT>self.cache[code] = function_list<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self.clear_module_directory()<EOL><DEDENT>return function_list<EOL>

Return the list of functions associated with this code fragment.

            The cache is first searched for the function.  If an entry
            in the cache is not found, then catalog files on disk are
            searched for the entry.  This is slooooow, but only happens
            once per code object.  All the functions found in catalog files
            on a cache miss are loaded into the cache to speed up future calls.
            The search order is as follows:

                1. user specified path (from catalog initialization)
                2. directories from the PYTHONCOMPILED environment variable
                3. The temporary directory on your platform.

            The path specified by module_dir will replace the 'MODULE'
            place holder in the catalog search path. See build_search_order()
            for more info on the search path.


<EOL>if code in self.cache:<EOL><INDENT>if function not in self.cache[code]:<EOL><INDENT>self.cache[code].insert(<NUM_LIT:0>,function)<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.cache[code] = self.get_functions(code)<EOL>self.fast_cache(code,function)<EOL><DEDENT>try:<EOL><INDENT>self.set_module_directory(module_dir)<EOL>self.add_function_persistent(code,function)<EOL><DEDENT>finally:<EOL><INDENT>self.clear_module_directory()<EOL><DEDENT>

Adds a function to the catalog.

            The function is added to the cache as well as the first
            writable file catalog found in the search path.  If no
            code entry exists in the cache, the on disk catalogs
            are loaded into the cache and function is added to the
            beginning of the function list.

            The path specified by module_dir will replace the 'MODULE'
            place holder in the catalog search path. See build_search_order()
            for more info on the search path.


<EOL>mode = '<STR_LIT:c>'  <EOL>cat_dir = self.get_writable_dir()<EOL>cat = get_catalog(cat_dir,mode)<EOL>if cat is None:<EOL><INDENT>cat_dir = default_dir()<EOL>cat = get_catalog(cat_dir,mode)<EOL><DEDENT>if cat is None:<EOL><INDENT>cat_dir = default_dir()<EOL>cat_file = catalog_path(cat_dir)<EOL>warnings.warn('<STR_LIT>')<EOL>import glob<EOL>files = glob.glob(cat_file+'<STR_LIT:*>')<EOL>for f in files:<EOL><INDENT>os.remove(f)<EOL><DEDENT>cat = get_catalog(cat_dir,mode)<EOL><DEDENT>if cat is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>function_list = [function]<EOL>try:<EOL><INDENT>function_list = function_list + cat.get(code,[])<EOL><DEDENT>except pickle.UnpicklingError:<EOL><INDENT>pass<EOL><DEDENT>cat[code] = function_list<EOL>module = getmodule(function)<EOL>try:<EOL><INDENT>mod_path,f = os.path.split(os.path.abspath(module.__file__))<EOL>pkey = self.path_key(code)<EOL>cat[pkey] = [mod_path] + cat.get(pkey,[])<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>cat.close()<EOL>

Store the code->function relationship to disk.

            Two pieces of information are needed for loading functions
            from disk -- the function pickle (which conveniently stores
            the module name, etc.) and the path to its module's directory.
            The latter is needed so that the function can be loaded no
            matter what the user's Python path is.


try:<EOL><INDENT>if self.cache[code][<NUM_LIT:0>] == function:<EOL><INDENT>return<EOL><DEDENT><DEDENT>except:  <EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>self.cache[code].remove(function)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>self.cache[code].insert(<NUM_LIT:0>,function)<EOL>

Move function to the front of the cache entry for code

            If future calls to the function have the same type signature,
            this will speed up access significantly because the first
            function call is correct.

            Note:  The cache added to the inline_tools module is significantly
                   faster than always calling get_functions, so this isn't
                   as necessary as it used to be.  Still, it's probably worth
                   doing.


length = len(s)<EOL>i = <NUM_LIT:0><EOL>answer = []<EOL>while i < length:<EOL><INDENT>bytecode = ord(s[i])<EOL>name = byOpcode[bytecode]<EOL>if bytecode >= haveArgument:<EOL><INDENT>argument = <NUM_LIT>*ord(s[i+<NUM_LIT:2>])+ord(s[i+<NUM_LIT:1>])<EOL>i += <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>argument = None<EOL>i += <NUM_LIT:1><EOL><DEDENT>answer.append((bytecode,argument,name))<EOL><DEDENT>return answer<EOL>


assert_(inspect.isfunction(f))<EOL>filename = f.func_code.co_filename<EOL>try:<EOL><INDENT>lines = open(filename).readlines()<EOL><DEDENT>except:<EOL><INDENT>lines = None<EOL><DEDENT>pc = <NUM_LIT:0><EOL>s = '<STR_LIT>'<EOL>lastLine = None<EOL>for op,arg,name in opcodize(f.func_code.co_code):<EOL><INDENT>if lines and name == '<STR_LIT>':<EOL><INDENT>source = lines[arg-<NUM_LIT:1>][:-<NUM_LIT:1>]<EOL>while lastLine and lastLine < arg-<NUM_LIT:1>:<EOL><INDENT>nonEmittingSource = lines[lastLine][:-<NUM_LIT:1>]<EOL>lastLine += <NUM_LIT:1><EOL>s += '<STR_LIT>' % (<EOL>'<STR_LIT>','<STR_LIT>','<STR_LIT>',nonEmittingSource)<EOL><DEDENT>lastLine = arg<EOL><DEDENT>else:<EOL><INDENT>source = '<STR_LIT>'<EOL><DEDENT>if arg is None:<EOL><INDENT>arg = '<STR_LIT>'<EOL><DEDENT>s += '<STR_LIT>' % (pc,name,arg,source)<EOL>if op >= haveArgument:<EOL><INDENT>pc += <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>pc += <NUM_LIT:1><EOL><DEDENT><DEDENT>return s<EOL>

Pretty print the internals of your function


raise NotImplementedError<EOL>

Indicates end-of-code to the compiler, not used by the interpreter.


raise NotImplementedError<EOL>


raise NotImplementedError<EOL>

Lifts second and third stack item one position up, moves top down to position three.


raise NotImplementedError<EOL>

Lifts second, third and forth stack item one position up, moves top down to position four.


raise NotImplementedError<EOL>

Duplicates the reference on top of the stack.


raise NotImplementedError<EOL>

Implements the expression statement for the interactive mode. TOS is removed from the stack and printed. In non-interactive mode, an expression statement is terminated with POP_STACK.


raise NotImplementedError<EOL>

Prints TOS to the file-like object bound to sys.stdout. There is one such instruction for each item in the print statement.


raise NotImplementedError<EOL>

Like PRINT_ITEM, but prints the item second from TOS to the file-like object at TOS. This is used by the extended print statement.


raise NotImplementedError<EOL>

Prints a new line on sys.stdout. This is generated as the last operation of a print statement, unless the statement ends with a comma.


raise NotImplementedError<EOL>

Like PRINT_NEWLINE, but prints the new line on the file-like object on the TOS. This is used by the extended print statement.


raise NotImplementedError<EOL>

Terminates a loop due to a break statement.


raise NotImplementedError<EOL>

Pushes a reference to the locals of the current scope on the stack. This is used in the code for a class definition: After the class body is evaluated, the locals are passed to the class definition.


raise NotImplementedError<EOL>

Returns with TOS to the caller of the function.


raise NotImplementedError<EOL>

Loads all symbols not starting with _ directly from the module TOS to the local namespace. The module is popped after loading all names. This opcode implements from module import *.


raise NotImplementedError<EOL>

Implements exec TOS2,TOS1,TOS. The compiler fills missing optional parameters with None.


raise NotImplementedError<EOL>

Removes one block from the block stack. Per frame, there is a stack of blocks, denoting nested loops, try statements, and such.


raise NotImplementedError<EOL>

Terminates a finally clause. The interpreter recalls whether the exception has to be re-raised, or whether the function returns, and continues with the outer-next block.


raise NotImplementedError<EOL>

Creates a new class object. TOS is the methods dictionary, TOS1 the tuple of the names of the base classes, and TOS2 the class name.


raise NotImplementedError<EOL>

Implements name = TOS. namei is the index of name in the attribute co_names of the code object. The compiler tries to use STORE_LOCAL or STORE_GLOBAL if possible.


raise NotImplementedError<EOL>

Implements del name, where namei is the index into co_names attribute of the code object.


raise NotImplementedError<EOL>

Unpacks TOS into count individual values, which are put onto the stack right-to-left.


raise NotImplementedError<EOL>

Duplicate count items, keeping them in the same order. Due to implementation limits, count should be between 1 and 5 inclusive.


raise NotImplementedError<EOL>

Implements TOS.name = TOS1, where namei is the index of name in co_names.


raise NotImplementedError<EOL>

Implements del TOS.name, using namei as index into co_names.


raise NotImplementedError<EOL>

Works as STORE_NAME, but stores the name as a global.


raise NotImplementedError<EOL>

Works as DELETE_NAME, but deletes a global name.


raise NotImplementedError<EOL>

Pushes co_consts[consti] onto the stack.


raise NotImplementedError<EOL>

Pushes the value associated with co_names[namei] onto the stack.


raise NotImplementedError<EOL>

Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack.


raise NotImplementedError<EOL>

Works as BUILD_TUPLE, but creates a list.


raise NotImplementedError<EOL>

Pushes a new empty dictionary object onto the stack. The argument is ignored and set to zero by the compiler.


raise NotImplementedError<EOL>

Replaces TOS with getattr(TOS, co_names[namei].


raise NotImplementedError<EOL>

Performs a Boolean operation. The operation name can be found in cmp_op[opname].


raise NotImplementedError<EOL>

Imports the module co_names[namei]. The module object is pushed onto the stack. The current namespace is not affected: for a proper import statement, a subsequent STORE_FAST instruction modifies the namespace.


raise NotImplementedError<EOL>

Loads the attribute co_names[namei] from the module found in TOS. The resulting object is pushed onto the stack, to be subsequently stored by a STORE_FAST instruction.


raise NotImplementedError<EOL>


raise NotImplementedError<EOL>

If TOS is true, increment the byte code counter by delta. TOS is left on the stack.


raise NotImplementedError<EOL>

If TOS is false, increment the byte code counter by delta. TOS is not changed.


raise NotImplementedError<EOL>

Iterate over a sequence. TOS is the current index, TOS1 the sequence. First, the next element is computed. If the sequence is exhausted, increment byte code counter by delta. Otherwise, push the sequence, the incremented counter, and the current item onto the stack.


raise NotImplementedError<EOL>

Loads the global named co_names[namei] onto the stack.


raise NotImplementedError<EOL>

Pushes a block for a loop onto the block stack. The block spans from the current instruction with a size of delta bytes.


raise NotImplementedError<EOL>

Pushes a try block from a try-except clause onto the block stack. delta points to the first except block.


raise NotImplementedError<EOL>

Pushes a try block from a try-except clause onto the block stack. delta points to the finally block.


raise NotImplementedError<EOL>

Pushes a reference to the local co_varnames[var_num] onto the stack.


raise NotImplementedError<EOL>

Stores TOS into the local co_varnames[var_num].


raise NotImplementedError<EOL>

Pushes a reference to the cell contained in slot i of the cell and free variable storage. The name of the variable is co_cellvars[i] if i is less than the length of co_cellvars. Otherwise it is co_freevars[i - len(co_cellvars)].


raise NotImplementedError<EOL>

Loads the cell contained in slot i of the cell and free variable storage. Pushes a reference to the object the cell contains on the stack.


raise NotImplementedError<EOL>

Stores TOS into the cell contained in slot i of the cell and free variable storage.


raise NotImplementedError<EOL>

Raises an exception. argc indicates the number of parameters to the raise statement, ranging from 0 to 3. The handler will find the traceback as TOS2, the parameter as TOS1, and the exception as TOS.


raise NotImplementedError<EOL>

Calls a function. The low byte of argc indicates the number of positional parameters, the high byte the number of keyword parameters. On the stack, the opcode finds the keyword parameters first. For each keyword argument, the value is on top of the key. Below the keyword parameters, the positional parameters are on the stack, with the right-most parameter on top. Below the parameters, the function object to call is on the stack.


raise NotImplementedError<EOL>

Pushes a new function object on the stack. TOS is the code associated with the function. The function object is defined to have argc default parameters, which are found below TOS.


raise NotImplementedError<EOL>

Creates a new function object, sets its func_closure slot, and pushes it on the stack. TOS is the code associated with the function. If the code object has N free variables, the next N items on the stack are the cells for these variables. The function also has argc default parameters, where are found before the cells.


raise NotImplementedError<EOL>

Pushes a slice object on the stack. argc must be 2 or 3. If it is 2, slice(TOS1, TOS) is pushed; if it is 3, slice(TOS2, TOS1, TOS) is pushed. See the slice() built-in function for more information.


raise NotImplementedError<EOL>

Prefixes any opcode which has an argument too big to fit into the default two bytes. ext holds two additional bytes which, taken together with the subsequent opcode's argument, comprise a four-byte argument, ext being the two most-significant bytes.


raise NotImplementedError<EOL>

Calls a function. argc is interpreted as in CALL_FUNCTION. The top element on the stack contains the variable argument list, followed by keyword and positional arguments.


raise NotImplementedError<EOL>

Calls a function. argc is interpreted as in CALL_FUNCTION. The top element on the stack contains the keyword arguments dictionary, followed by explicit keyword and positional arguments.


raise NotImplementedError<EOL>

Calls a function. argc is interpreted as in CALL_FUNCTION. The top element on the stack contains the keyword arguments dictionary, followed by the variable-arguments tuple, followed by explicit keyword and positional arguments.


V = []<EOL>T = []<EOL>for i in range(count):<EOL><INDENT>v,t = self.pop()<EOL>V.append(v)<EOL>T.append(t)<EOL><DEDENT>V.reverse()<EOL>T.reverse()<EOL>self.pushTuple(tuple(V),tuple(T))<EOL>return<EOL>

Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack.


return<EOL>

Pushes a block for a loop onto the block stack. The block spans from the current instruction with a size of delta bytes.


<EOL>v2,t2 = self.pop()<EOL>v1,t1 = self.pop()<EOL>self.emit('<STR_LIT>' % (<EOL>v2,v1,v2,v1,v2,v1))<EOL>self.push(v2,t2)<EOL>return<EOL>

Iterate over a sequence. TOS is the current index, TOS1 the sequence. First, the next element is computed. If the sequence is exhausted, increment byte code counter by delta. Otherwise, push the sequence, the incremented counter, and the current item onto the stack.


self.emit('<STR_LIT:}>')<EOL>return<EOL>


return<EOL>

Removes one block from the block stack. Per frame, there is a stack of blocks, denoting nested loops, try statements, and such.


file_changed = <NUM_LIT:1><EOL>if os.path.exists(module_file):<EOL><INDENT>f = open(module_file,'<STR_LIT:r>')<EOL>old_string = f.read()<EOL>f.close()<EOL>if old_string == module_string:<EOL><INDENT>file_changed = <NUM_LIT:0><EOL><DEDENT><DEDENT>if file_changed:<EOL><INDENT>f = open(module_file,'<STR_LIT:w>')<EOL>f.write(module_string)<EOL>f.close()<EOL><DEDENT>return module_file<EOL>

generate the source code file.  Only overwrite
        the existing file if the actual source has changed.


numeric_types = []<EOL>for var in var_specs:<EOL><INDENT>if hasattr(var,'<STR_LIT>'):<EOL><INDENT>numeric_types.append(var.numeric_type)<EOL><DEDENT><DEDENT>if (('<STR_LIT:f>' in numeric_types or '<STR_LIT:F>' in numeric_types) and not (<EOL>'<STR_LIT:d>' in numeric_types or '<STR_LIT:D>' in numeric_types)):<EOL><INDENT>for var in var_specs:<EOL><INDENT>if hasattr(var,'<STR_LIT>'):<EOL><INDENT>if issubclass(var.numeric_type, complex):<EOL><INDENT>var.numeric_type = '<STR_LIT:F>'<EOL><DEDENT>elif issubclass(var.numeric_type, float):<EOL><INDENT>var.numeric_type = '<STR_LIT:f>'<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return var_specs<EOL>

Cast python scalars down to most common type of
         arrays used.

         Right now, focus on complex and float types. Ignore int types.
         Require all arrays to have same type before forcing downcasts.

         Note: var_specs are currently altered in place (horrors...!)


declare_return = '<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL>arg_string_list = self.arg_specs.variable_as_strings() + ['<STR_LIT>']<EOL>arg_strings = '<STR_LIT:U+002C>'.join(arg_string_list)<EOL>if arg_strings:<EOL><INDENT>arg_strings += '<STR_LIT:U+002C>'<EOL><DEDENT>declare_kwlist = '<STR_LIT>' %arg_strings<EOL>py_objects = '<STR_LIT:U+002CU+0020>'.join(self.arg_specs.py_pointers())<EOL>init_flags = '<STR_LIT:U+002CU+0020>'.join(self.arg_specs.init_flags())<EOL>init_flags_init = '<STR_LIT>'.join(self.arg_specs.init_flags())<EOL>py_vars = '<STR_LIT>'.join(self.arg_specs.py_variables())<EOL>if py_objects:<EOL><INDENT>declare_py_objects = '<STR_LIT>' + py_objects + '<STR_LIT>'<EOL>declare_py_objects += '<STR_LIT>' + init_flags + '<STR_LIT>'<EOL>init_values = py_vars + '<STR_LIT>'<EOL>init_values += init_flags_init + '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>declare_py_objects = '<STR_LIT>'<EOL>init_values = '<STR_LIT>'<EOL><DEDENT>ref_string = '<STR_LIT:U+002CU+0020>'.join(self.arg_specs.py_references())<EOL>if ref_string:<EOL><INDENT>ref_string += '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>ref_string = '<STR_LIT>'<EOL><DEDENT>format = "<STR_LIT:O>" * len(self.arg_specs) + "<STR_LIT>" + '<STR_LIT::>' + self.name<EOL>parse_tuple = '<STR_LIT>''<STR_LIT>' %(format,ref_string)<EOL>parse_tuple += '<STR_LIT>'<EOL>return declare_return + declare_kwlist + declare_py_objects+ init_values + parse_tuple<EOL>

Create code block for PyArg_ParseTuple.  Variable declarations
            for all PyObjects are done also.

            This code got a lot uglier when I added local_dict...


def check_discrete_chisquare(distfn, arg, rvs, alpha, msg):

n = len(rvs)<EOL>nsupp = <NUM_LIT:20><EOL>wsupp = <NUM_LIT:1.0>/nsupp<EOL>distsupport = xrange(max(distfn.a, -<NUM_LIT:1000>), min(distfn.b, <NUM_LIT:1000>) + <NUM_LIT:1>)<EOL>last = <NUM_LIT:0><EOL>distsupp = [max(distfn.a, -<NUM_LIT:1000>)]<EOL>distmass = []<EOL>for ii in distsupport:<EOL><INDENT>current = distfn.cdf(ii,*arg)<EOL>if current - last >= wsupp-<NUM_LIT>:<EOL><INDENT>distsupp.append(ii)<EOL>distmass.append(current - last)<EOL>last = current<EOL>if current > (<NUM_LIT:1>-wsupp):<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if distsupp[-<NUM_LIT:1>] < distfn.b:<EOL><INDENT>distsupp.append(distfn.b)<EOL>distmass.append(<NUM_LIT:1>-last)<EOL><DEDENT>distsupp = np.array(distsupp)<EOL>distmass = np.array(distmass)<EOL>histsupp = distsupp+<NUM_LIT><EOL>histsupp[<NUM_LIT:0>] = distfn.a<EOL>freq,hsupp = np.histogram(rvs,histsupp)<EOL>cdfs = distfn.cdf(distsupp,*arg)<EOL>(chis,pval) = stats.chisquare(np.array(freq),n*distmass)<EOL>npt.assert_(pval > alpha, '<STR_LIT>'<EOL>'<STR_LIT>' % (msg,str(arg),str(pval)))<EOL>

Perform chisquare test for random sample of a discrete distribution

    Parameters
    ----------
    distname : string
        name of distribution function
    arg : sequence
        parameters of distribution
    alpha : float
        significance level, threshold for p-value

    Returns
    -------
    result : bool
        0 if test passes, 1 if test fails

    uses global variable debug for printing results


return [<NUM_LIT:1000>, <NUM_LIT:100>, <NUM_LIT:10>, <NUM_LIT:5>]<EOL>

Returns list of sample sizes to be used for comparison.


data = np.ravel(data)<EOL>mu = data.mean()<EOL>m2 = ((data - mu)**<NUM_LIT:2>).mean()<EOL>m3 = ((data - mu)**<NUM_LIT:3>).mean()<EOL>return m3 / np.power(m2, <NUM_LIT>)<EOL>

skew is third central moment / variance**(1.5)


data = np.ravel(data)<EOL>mu = data.mean()<EOL>m2 = ((data - mu)**<NUM_LIT:2>).mean()<EOL>m4 = ((data - mu)**<NUM_LIT:4>).mean()<EOL>return m4 / m2**<NUM_LIT:2> - <NUM_LIT:3><EOL>

kurtosis is fourth central moment / variance**2 - 3


def valarray(shape, value=nan, typecode=None):

out = ones(shape, dtype=bool) * value<EOL>if typecode is not None:<EOL><INDENT>out = out.astype(typecode)<EOL><DEDENT>if not isinstance(out, ndarray):<EOL><INDENT>out = asarray(out)<EOL><DEDENT>return out<EOL>


def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):

if fillvalue is None:<EOL><INDENT>if f2 is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>fillvalue = np.nan<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if f2 is not None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>arrays = np.broadcast_arrays(*arrays)<EOL>temp = tuple(np.extract(cond, arr) for arr in arrays)<EOL>out = valarray(shape(arrays[<NUM_LIT:0>]), value=fillvalue)<EOL>np.place(out, cond, f(*temp))<EOL>if f2 is not None:<EOL><INDENT>temp = tuple(np.extract(~cond, arr) for arr in arrays)<EOL>np.place(out, ~cond, f2(*temp))<EOL><DEDENT>return out<EOL>

np.where(cond, x, fillvalue) always evaluates x even where cond is False.
This one only evaluates f(arr1[cond], arr2[cond], ...).
For example,
>>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
>>> def f(a, b):
    return a*b
>>> _lazywhere(a > 2, (a, b), f, np.nan)
array([ nan,  nan,  21.,  32.])

Notice it assumes that all `arrays` are of the same shape, or can be
broadcasted together.


newargs = np.atleast_1d(*args)<EOL>if not isinstance(newargs, list):<EOL><INDENT>newargs = [newargs, ]<EOL><DEDENT>expand_arr = (cond == cond)<EOL>return [np.extract(cond, arr1 * expand_arr) for arr1 in newargs]<EOL>

Return the sequence of ravel(args[i]) where ravel(condition) is
    True in 1D.

    Examples
    --------
    >>> import numpy as np
    >>> rand = np.random.random_sample
    >>> A = rand((4, 5))
    >>> B = 2
    >>> C = rand((1, 5))
    >>> cond = np.ones(A.shape)
    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
    >>> B1.shape
    (20,)
    >>> cond[2,:] = 0
    >>> [A2, B2, C2] = argsreduce(cond, A, B, C)
    >>> B2.shape
    (15,)


<EOL>tot = <NUM_LIT:0.0><EOL>diff = <NUM_LIT><EOL>pos = max(<NUM_LIT:0.0>, <NUM_LIT:1.0>*self.a)<EOL>count = <NUM_LIT:0><EOL>ulimit = max(<NUM_LIT:1000>, (min(self.b, <NUM_LIT:1000>) + max(self.a, -<NUM_LIT:1000>))/<NUM_LIT>)<EOL>llimit = min(-<NUM_LIT:1000>, (min(self.b, <NUM_LIT:1000>) + max(self.a, -<NUM_LIT:1000>))/<NUM_LIT>)<EOL>while (pos <= self.b) and ((pos <= ulimit) or<EOL>(diff > self.moment_tol)):<EOL><INDENT>diff = np.power(pos, n) * self.pmf(pos, *args)<EOL>tot += diff<EOL>pos += self.inc<EOL>count += <NUM_LIT:1><EOL><DEDENT>if self.a < <NUM_LIT:0>:  <EOL><INDENT>diff = <NUM_LIT><EOL>pos = -self.inc<EOL>while (pos >= self.a) and ((pos >= llimit) or<EOL>(diff > self.moment_tol)):<EOL><INDENT>diff = np.power(pos, n) * self.pmf(pos, *args)<EOL>tot += diff<EOL>pos -= self.inc<EOL>count += <NUM_LIT:1><EOL><DEDENT><DEDENT>return tot<EOL>

Non-central moment of discrete distribution.


pk = asarray(pk)<EOL>pk = <NUM_LIT:1.0>*pk / sum(pk, axis=<NUM_LIT:0>)<EOL>if qk is None:<EOL><INDENT>vec = entr(pk)<EOL><DEDENT>else:<EOL><INDENT>qk = asarray(qk)<EOL>if len(qk) != len(pk):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>qk = <NUM_LIT:1.0>*qk / sum(qk, axis=<NUM_LIT:0>)<EOL>vec = kl_div(pk, qk)<EOL><DEDENT>S = sum(vec, axis=<NUM_LIT:0>)<EOL>if base is not None:<EOL><INDENT>S /= log(base)<EOL><DEDENT>return S<EOL>

Calculate the entropy of a distribution for given probability values.

    If only probabilities `pk` are given, the entropy is calculated as
    ``S = -sum(pk * log(pk), axis=0)``.

    If `qk` is not None, then compute the Kullback-Leibler divergence
    ``S = sum(pk * log(pk / qk), axis=0)``.

    This routine will normalize `pk` and `qk` if they don't sum to 1.

    Parameters
    ----------
    pk : sequence
        Defines the (discrete) distribution. ``pk[i]`` is the (possibly
        unnormalized) probability of event ``i``.
    qk : sequence, optional
        Sequence against which the relative entropy is computed. Should be in
        the same format as `pk`.
    base : float, optional
        The logarithmic base to use, defaults to ``e`` (natural logarithm).

    Returns
    -------
    S : float
        The calculated entropy.


distn_names = []<EOL>distn_gen_names = []<EOL>for name, value in namespace_pairs:<EOL><INDENT>if name.startswith('<STR_LIT:_>'):<EOL><INDENT>continue<EOL><DEDENT>if name.endswith('<STR_LIT>') and issubclass(value, rv_base_class):<EOL><INDENT>distn_gen_names.append(name)<EOL><DEDENT>if isinstance(value, rv_base_class):<EOL><INDENT>distn_names.append(name)<EOL><DEDENT><DEDENT>return distn_names, distn_gen_names<EOL>

Collect names of statistical distributions and their generators.

Parameters
----------
namespace_pairs : sequence
    A snapshot of (name, value) pairs in the namespace of a module.
rv_base_class : class
    The base class of random variable generator classes in a module.

Returns
-------
distn_names : list of strings
    Names of the statistical distributions.
distn_gen_names : list of strings
    Names of the generators of the statistical distributions.
    Note that these are not simply the names of the statistical
    distributions, with a _gen suffix added.


def _construct_argparser(<EOL>self, meths_to_inspect, locscale_in, locscale_out):

if self.shapes:<EOL><INDENT>if not isinstance(self.shapes, string_types):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>shapes = self.shapes.replace('<STR_LIT:U+002C>', '<STR_LIT:U+0020>').split()<EOL>for field in shapes:<EOL><INDENT>if keyword.iskeyword(field):<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>if not re.match('<STR_LIT>', field):<EOL><INDENT>raise SyntaxError(<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>shapes_list = []<EOL>for meth in meths_to_inspect:<EOL><INDENT>shapes_args = inspect.getargspec(meth)<EOL>shapes_list.append(shapes_args.args)<EOL>if len(shapes_args.args) > <NUM_LIT:2>:<EOL><INDENT>if shapes_args.varargs is not None:<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>')<EOL><DEDENT>if shapes_args.keywords is not None:<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>')<EOL><DEDENT>if shapes_args.defaults is not None:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>shapes = max(shapes_list, key=lambda x: len(x))<EOL>shapes = shapes[<NUM_LIT:2>:]  <EOL>for item in shapes_list:<EOL><INDENT>if len(item) > <NUM_LIT:2> and item[<NUM_LIT:2>:] != shapes:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>shapes_str = '<STR_LIT:U+002CU+0020>'.join(shapes) + '<STR_LIT:U+002CU+0020>' if shapes else '<STR_LIT>'  <EOL>dct = dict(shape_arg_str=shapes_str,<EOL>locscale_in=locscale_in,<EOL>locscale_out=locscale_out,<EOL>)<EOL>ns = {}<EOL>exec_(parse_arg_template % dct, ns)<EOL>for name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>setattr(self, name,<EOL>instancemethod(ns[name], self, self.__class__)<EOL>)<EOL><DEDENT>self.shapes = '<STR_LIT:U+002CU+0020>'.join(shapes) if shapes else None<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.numargs = len(shapes)<EOL><DEDENT>

Construct the parser for the shape arguments.

        Generates the argument-parsing functions dynamically and attaches
        them to the instance.
        Is supposed to be called in __init__ of a class for each distribution.

        If self.shapes is a non-empty string, interprets it as a
        comma-separated list of shape parameters.

        Otherwise inspects the call signatures of `meths_to_inspect`
        and constructs the argument-parsing functions from these.
        In this case also sets `shapes` and `numargs`.


def _construct_doc(self, docdict, shapes_vals=None):

tempdict = docdict.copy()<EOL>tempdict['<STR_LIT:name>'] = self.name or '<STR_LIT>'<EOL>tempdict['<STR_LIT>'] = self.shapes or '<STR_LIT>'<EOL>if shapes_vals is None:<EOL><INDENT>shapes_vals = ()<EOL><DEDENT>vals = '<STR_LIT:U+002CU+0020>'.join(str(_) for _ in shapes_vals)<EOL>tempdict['<STR_LIT>'] = vals<EOL>if self.shapes:<EOL><INDENT>tempdict['<STR_LIT>'] = '<STR_LIT>' % (self.shapes, vals)<EOL><DEDENT>else:<EOL><INDENT>tempdict['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if self.shapes is None:<EOL><INDENT>for item in ['<STR_LIT>', '<STR_LIT:default>', '<STR_LIT>']:<EOL><INDENT>tempdict[item] = tempdict[item].replace(<EOL>"<STR_LIT>", "<STR_LIT>")<EOL><DEDENT><DEDENT>for i in range(<NUM_LIT:2>):<EOL><INDENT>if self.shapes is None:<EOL><INDENT>self.__doc__ = self.__doc__.replace("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT>self.__doc__ = doccer.docformat(self.__doc__, tempdict)<EOL><DEDENT>self.__doc__ = self.__doc__.replace('<STR_LIT>', '<STR_LIT:(>').replace('<STR_LIT>', '<STR_LIT:)>')<EOL>

Construct the instance docstring with string substitutions.


return rv_frozen(self, *args, **kwds)<EOL>

Freeze the distribution for the given arguments.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution.  Should include all
            the non-optional arguments, may include ``loc`` and ``scale``.

        Returns
        -------
        rv_frozen : rv_frozen instance
            The frozen distribution.


cond = <NUM_LIT:1><EOL>for arg in args:<EOL><INDENT>cond = logical_and(cond, (asarray(arg) > <NUM_LIT:0>))<EOL><DEDENT>return cond<EOL>

Default check for correct values on args and keywords.

        Returns condition array of 1's where arguments are correct and
         0's where they are not.


discrete = kwds.pop('<STR_LIT>', None)<EOL>args, loc, scale, size = self._parse_args_rvs(*args, **kwds)<EOL>cond = logical_and(self._argcheck(*args), (scale >= <NUM_LIT:0>))<EOL>if not np.all(cond):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._size = product(size, axis=<NUM_LIT:0>)<EOL>if self._size is not None and self._size > <NUM_LIT:1>:<EOL><INDENT>size = np.array(size, ndmin=<NUM_LIT:1>)<EOL><DEDENT>if np.all(scale == <NUM_LIT:0>):<EOL><INDENT>return loc*ones(size, '<STR_LIT:d>')<EOL><DEDENT>vals = self._rvs(*args)<EOL>if self._size is not None:<EOL><INDENT>vals = reshape(vals, size)<EOL><DEDENT>vals = vals * scale + loc<EOL>if discrete:<EOL><INDENT>if np.isscalar(vals):<EOL><INDENT>vals = int(vals)<EOL><DEDENT>else:<EOL><INDENT>vals = vals.astype(int)<EOL><DEDENT><DEDENT>return vals<EOL>

Random variates of given type.

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).
scale : array_like, optional
    Scale parameter (default=1).
size : int or tuple of ints, optional
    Defining number of random variates (default=1).

Returns
-------
rvs : ndarray or scalar
    Random variates of given `size`.


args, loc, scale, moments = self._parse_args_stats(*args, **kwds)<EOL>loc, scale = map(asarray, (loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>cond = self._argcheck(*args) & (scale > <NUM_LIT:0>) & (loc == loc)<EOL>output = []<EOL>default = valarray(shape(cond), self.badvalue)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *(args+(scale, loc)))<EOL>scale, loc, goodargs = goodargs[-<NUM_LIT:2>], goodargs[-<NUM_LIT:1>], goodargs[:-<NUM_LIT:2>]<EOL>if self._stats_has_moments:<EOL><INDENT>mu, mu2, g1, g2 = self._stats(*goodargs,<EOL>**{'<STR_LIT>': moments})<EOL><DEDENT>else:<EOL><INDENT>mu, mu2, g1, g2 = self._stats(*goodargs)<EOL><DEDENT>if g1 is None:<EOL><INDENT>mu3 = None<EOL><DEDENT>else:<EOL><INDENT>if mu2 is None:<EOL><INDENT>mu2 = self._munp(<NUM_LIT:2>, *goodargs)<EOL><DEDENT>mu3 = g1 * np.power(mu2, <NUM_LIT>)<EOL><DEDENT>if '<STR_LIT:m>' in moments:<EOL><INDENT>if mu is None:<EOL><INDENT>mu = self._munp(<NUM_LIT:1>, *goodargs)<EOL><DEDENT>out0 = default.copy()<EOL>place(out0, cond, mu * scale + loc)<EOL>output.append(out0)<EOL><DEDENT>if '<STR_LIT:v>' in moments:<EOL><INDENT>if mu2 is None:<EOL><INDENT>mu2p = self._munp(<NUM_LIT:2>, *goodargs)<EOL>if mu is None:<EOL><INDENT>mu = self._munp(<NUM_LIT:1>, *goodargs)<EOL><DEDENT>mu2 = mu2p - mu * mu<EOL>if np.isinf(mu):<EOL><INDENT>mu2 = np.inf<EOL><DEDENT><DEDENT>out0 = default.copy()<EOL>place(out0, cond, mu2 * scale * scale)<EOL>output.append(out0)<EOL><DEDENT>if '<STR_LIT:s>' in moments:<EOL><INDENT>if g1 is None:<EOL><INDENT>mu3p = self._munp(<NUM_LIT:3>, *goodargs)<EOL>if mu is None:<EOL><INDENT>mu = self._munp(<NUM_LIT:1>, *goodargs)<EOL><DEDENT>if mu2 is None:<EOL><INDENT>mu2p = self._munp(<NUM_LIT:2>, *goodargs)<EOL>mu2 = mu2p - mu * mu<EOL><DEDENT>mu3 = mu3p - <NUM_LIT:3> * mu * mu2 - mu**<NUM_LIT:3><EOL>g1 = mu3 / np.power(mu2, <NUM_LIT>)<EOL><DEDENT>out0 = default.copy()<EOL>place(out0, cond, g1)<EOL>output.append(out0)<EOL><DEDENT>if '<STR_LIT:k>' in moments:<EOL><INDENT>if g2 is None:<EOL><INDENT>mu4p = self._munp(<NUM_LIT:4>, *goodargs)<EOL>if mu is None:<EOL><INDENT>mu = self._munp(<NUM_LIT:1>, *goodargs)<EOL><DEDENT>if mu2 is None:<EOL><INDENT>mu2p = self._munp(<NUM_LIT:2>, *goodargs)<EOL>mu2 = mu2p - mu * mu<EOL><DEDENT>if mu3 is None:<EOL><INDENT>mu3p = self._munp(<NUM_LIT:3>, *goodargs)<EOL>mu3 = mu3p - <NUM_LIT:3> * mu * mu2 - mu**<NUM_LIT:3><EOL><DEDENT>mu4 = mu4p - <NUM_LIT:4> * mu * mu3 - <NUM_LIT:6> * mu * mu * mu2 - mu**<NUM_LIT:4><EOL>g2 = mu4 / mu2**<NUM_LIT> - <NUM_LIT><EOL><DEDENT>out0 = default.copy()<EOL>place(out0, cond, g2)<EOL>output.append(out0)<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>output = []<EOL>for _ in moments:<EOL><INDENT>out0 = default.copy()<EOL>output.append(out0)<EOL><DEDENT><DEDENT>if len(output) == <NUM_LIT:1>:<EOL><INDENT>return output[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return tuple(output)<EOL><DEDENT>

Some statistics of the given RV

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional (discrete RVs only)
    scale parameter (default=1)
moments : str, optional
    composed of letters ['mvsk'] defining which moments to compute:
    'm' = mean,
    'v' = variance,
    's' = (Fisher's) skew,
    'k' = (Fisher's) kurtosis.
    (default='mv')

Returns
-------
stats : sequence
    of requested moments.


args, loc, scale = self._parse_args(*args, **kwds)<EOL>args = tuple(map(asarray, args))<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>) & (loc == loc)<EOL>output = zeros(shape(cond0), '<STR_LIT:d>')<EOL>place(output, (<NUM_LIT:1>-cond0), self.badvalue)<EOL>goodargs = argsreduce(cond0, *args)<EOL>if self.numargs == <NUM_LIT:0>:<EOL><INDENT>place(output, cond0, self._entropy() + log(scale))<EOL><DEDENT>else:<EOL><INDENT>place(output, cond0, self.vecentropy(*goodargs) + log(scale))<EOL><DEDENT>return output<EOL>

Differential entropy of the RV.

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).
scale : array_like, optional  (continuous distributions only).
    Scale parameter (default=1).

Notes
-----
Entropy is defined base `e`:

>>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
>>> np.allclose(drv.entropy(), np.log(2.0))
True


args, loc, scale = self._parse_args(*args, **kwds)<EOL>if not (self._argcheck(*args) and (scale > <NUM_LIT:0>)):<EOL><INDENT>return nan<EOL><DEDENT>if (floor(n) != n):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (n < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>mu, mu2, g1, g2 = None, None, None, None<EOL>if (n > <NUM_LIT:0>) and (n < <NUM_LIT:5>):<EOL><INDENT>if self._stats_has_moments:<EOL><INDENT>mdict = {'<STR_LIT>': {<NUM_LIT:1>: '<STR_LIT:m>', <NUM_LIT:2>: '<STR_LIT:v>', <NUM_LIT:3>: '<STR_LIT>', <NUM_LIT:4>: '<STR_LIT>'}[n]}<EOL><DEDENT>else:<EOL><INDENT>mdict = {}<EOL><DEDENT>mu, mu2, g1, g2 = self._stats(*args, **mdict)<EOL><DEDENT>val = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, args)<EOL>if loc == <NUM_LIT:0>:<EOL><INDENT>return scale**n * val<EOL><DEDENT>else:<EOL><INDENT>result = <NUM_LIT:0><EOL>fac = float(scale) / float(loc)<EOL>for k in range(n):<EOL><INDENT>valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp, args)<EOL>result += comb(n, k, exact=True)*(fac**k) * valk<EOL><DEDENT>result += fac**n * val<EOL>return result * loc**n<EOL><DEDENT>

n'th order non-central moment of distribution.

Parameters
----------
n : int, n>=1
    Order of moment.
arg1, arg2, arg3,... : float
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
kwds : keyword arguments, optional
    These can include "loc" and "scale", as well as other keyword
    arguments relevant for a given distribution.


return self.ppf(<NUM_LIT:0.5>, *args, **kwds)<EOL>

Median of the distribution.

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    Location parameter, Default is 0.
scale : array_like, optional
    Scale parameter, Default is 1.

Returns
-------
median : float
    The median of the distribution.

See Also
--------
stats.distributions.rv_discrete.ppf
    Inverse of the CDF


kwds['<STR_LIT>'] = '<STR_LIT:m>'<EOL>res = self.stats(*args, **kwds)<EOL>if isinstance(res, ndarray) and res.ndim == <NUM_LIT:0>:<EOL><INDENT>return res[()]<EOL><DEDENT>return res<EOL>

Mean of the distribution

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
mean : float
    the mean of the distribution


kwds['<STR_LIT>'] = '<STR_LIT:v>'<EOL>res = self.stats(*args, **kwds)<EOL>if isinstance(res, ndarray) and res.ndim == <NUM_LIT:0>:<EOL><INDENT>return res[()]<EOL><DEDENT>return res<EOL>

Variance of the distribution

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
var : float
    the variance of the distribution


kwds['<STR_LIT>'] = '<STR_LIT:v>'<EOL>res = sqrt(self.stats(*args, **kwds))<EOL>return res<EOL>

Standard deviation of the distribution.

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
std : float
    standard deviation of the distribution


def interval(self, alpha, *args, **kwds):

alpha = asarray(alpha)<EOL>if any((alpha > <NUM_LIT:1>) | (alpha < <NUM_LIT:0>)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>q1 = (<NUM_LIT:1.0>-alpha)/<NUM_LIT:2><EOL>q2 = (<NUM_LIT:1.0>+alpha)/<NUM_LIT:2><EOL>a = self.ppf(q1, *args, **kwds)<EOL>b = self.ppf(q2, *args, **kwds)<EOL>return a, b<EOL>

Confidence interval with equal areas around the median.

Parameters
----------
alpha : array_like of float
    Probability that an rv will be drawn from the returned range.
    Each value should be in the range [0, 1].
arg1, arg2, ... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    location parameter, Default is 0.
scale : array_like, optional
    scale parameter, Default is 1.

Returns
-------
a, b : ndarray of float
    end-points of range that contain ``100 * alpha %`` of the rv's
    possible values.


def _construct_default_doc(self, longname=None, extradoc=None):

if longname is None:<EOL><INDENT>longname = '<STR_LIT:A>'<EOL><DEDENT>if extradoc is None:<EOL><INDENT>extradoc = '<STR_LIT>'<EOL><DEDENT>if extradoc.startswith('<STR_LIT>'):<EOL><INDENT>extradoc = extradoc[<NUM_LIT:2>:]<EOL><DEDENT>self.__doc__ = '<STR_LIT>'.join(['<STR_LIT>' % longname,<EOL>'<STR_LIT>', docheaders['<STR_LIT>'],<EOL>extradoc, '<STR_LIT>'])<EOL>self._construct_doc(docdict)<EOL>

Construct instance docstring from the default template.


args, loc, scale = self._parse_args(*args, **kwds)<EOL>x, loc, scale = map(asarray, (x, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>x = asarray((x-loc)*<NUM_LIT:1.0>/scale)<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>)<EOL>cond1 = (scale > <NUM_LIT:0>) & (x >= self.a) & (x <= self.b)<EOL>cond = cond0 & cond1<EOL>output = zeros(shape(cond), '<STR_LIT:d>')<EOL>putmask(output, (<NUM_LIT:1>-cond0)+np.isnan(x), self.badvalue)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((x,)+args+(scale,)))<EOL>scale, goodargs = goodargs[-<NUM_LIT:1>], goodargs[:-<NUM_LIT:1>]<EOL>place(output, cond, self._pdf(*goodargs) / scale)<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Probability density function at x of the given RV.

Parameters
----------
x : array_like
    quantiles
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
pdf : ndarray
    Probability density function evaluated at x


args, loc, scale = self._parse_args(*args, **kwds)<EOL>x, loc, scale = map(asarray, (x, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>x = asarray((x-loc)*<NUM_LIT:1.0>/scale)<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>)<EOL>cond1 = (scale > <NUM_LIT:0>) & (x >= self.a) & (x <= self.b)<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>putmask(output, (<NUM_LIT:1>-cond0)+np.isnan(x), self.badvalue)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((x,)+args+(scale,)))<EOL>scale, goodargs = goodargs[-<NUM_LIT:1>], goodargs[:-<NUM_LIT:1>]<EOL>place(output, cond, self._logpdf(*goodargs) - log(scale))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the probability density function at x of the given RV.

This uses a more numerically accurate calculation if available.

Parameters
----------
x : array_like
    quantiles
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
logpdf : array_like
    Log of the probability density function evaluated at x


args, loc, scale = self._parse_args(*args, **kwds)<EOL>x, loc, scale = map(asarray, (x, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>x = (x-loc)*<NUM_LIT:1.0>/scale<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>)<EOL>cond1 = (scale > <NUM_LIT:0>) & (x > self.a) & (x < self.b)<EOL>cond2 = (x >= self.b) & cond0<EOL>cond = cond0 & cond1<EOL>output = zeros(shape(cond), '<STR_LIT:d>')<EOL>place(output, (<NUM_LIT:1>-cond0)+np.isnan(x), self.badvalue)<EOL>place(output, cond2, <NUM_LIT:1.0>)<EOL>if any(cond):  <EOL><INDENT>goodargs = argsreduce(cond, *((x,)+args))<EOL>place(output, cond, self._cdf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Cumulative distribution function of the given RV.

Parameters
----------
x : array_like
    quantiles
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
cdf : ndarray
    Cumulative distribution function evaluated at `x`


args, loc, scale = self._parse_args(*args, **kwds)<EOL>x, loc, scale = map(asarray, (x, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>x = (x-loc)*<NUM_LIT:1.0>/scale<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>)<EOL>cond1 = (scale > <NUM_LIT:0>) & (x > self.a) & (x < self.b)<EOL>cond2 = (x >= self.b) & cond0<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>place(output, (<NUM_LIT:1>-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue)<EOL>place(output, cond2, <NUM_LIT:0.0>)<EOL>if any(cond):  <EOL><INDENT>goodargs = argsreduce(cond, *((x,)+args))<EOL>place(output, cond, self._logcdf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the cumulative distribution function at x of the given RV.

Parameters
----------
x : array_like
    quantiles
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
logcdf : array_like
    Log of the cumulative distribution function evaluated at x


args, loc, scale = self._parse_args(*args, **kwds)<EOL>x, loc, scale = map(asarray, (x, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>x = (x-loc)*<NUM_LIT:1.0>/scale<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>)<EOL>cond1 = (scale > <NUM_LIT:0>) & (x > self.a) & (x < self.b)<EOL>cond2 = cond0 & (x <= self.a)<EOL>cond = cond0 & cond1<EOL>output = zeros(shape(cond), '<STR_LIT:d>')<EOL>place(output, (<NUM_LIT:1>-cond0)+np.isnan(x), self.badvalue)<EOL>place(output, cond2, <NUM_LIT:1.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((x,)+args))<EOL>place(output, cond, self._sf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Survival function (1-cdf) at x of the given RV.

Parameters
----------
x : array_like
    quantiles
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
sf : array_like
    Survival function evaluated at x


args, loc, scale = self._parse_args(*args, **kwds)<EOL>x, loc, scale = map(asarray, (x, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>x = (x-loc)*<NUM_LIT:1.0>/scale<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>)<EOL>cond1 = (scale > <NUM_LIT:0>) & (x > self.a) & (x < self.b)<EOL>cond2 = cond0 & (x <= self.a)<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>place(output, (<NUM_LIT:1>-cond0)+np.isnan(x), self.badvalue)<EOL>place(output, cond2, <NUM_LIT:0.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((x,)+args))<EOL>place(output, cond, self._logsf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the survival function of the given RV.

Returns the log of the "survival function," defined as (1 - `cdf`),
evaluated at `x`.

Parameters
----------
x : array_like
    quantiles
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
logsf : ndarray
    Log of the survival function evaluated at `x`.


args, loc, scale = self._parse_args(*args, **kwds)<EOL>q, loc, scale = map(asarray, (q, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>) & (loc == loc)<EOL>cond1 = (<NUM_LIT:0> < q) & (q < <NUM_LIT:1>)<EOL>cond2 = cond0 & (q == <NUM_LIT:0>)<EOL>cond3 = cond0 & (q == <NUM_LIT:1>)<EOL>cond = cond0 & cond1<EOL>output = valarray(shape(cond), value=self.badvalue)<EOL>lower_bound = self.a * scale + loc<EOL>upper_bound = self.b * scale + loc<EOL>place(output, cond2, argsreduce(cond2, lower_bound)[<NUM_LIT:0>])<EOL>place(output, cond3, argsreduce(cond3, upper_bound)[<NUM_LIT:0>])<EOL>if any(cond):  <EOL><INDENT>goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))<EOL>scale, loc, goodargs = goodargs[-<NUM_LIT:2>], goodargs[-<NUM_LIT:1>], goodargs[:-<NUM_LIT:2>]<EOL>place(output, cond, self._ppf(*goodargs) * scale + loc)<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Percent point function (inverse of cdf) at q of the given RV.

Parameters
----------
q : array_like
    lower tail probability
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
x : array_like
    quantile corresponding to the lower tail probability q.


args, loc, scale = self._parse_args(*args, **kwds)<EOL>q, loc, scale = map(asarray, (q, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>) & (loc == loc)<EOL>cond1 = (<NUM_LIT:0> < q) & (q < <NUM_LIT:1>)<EOL>cond2 = cond0 & (q == <NUM_LIT:1>)<EOL>cond3 = cond0 & (q == <NUM_LIT:0>)<EOL>cond = cond0 & cond1<EOL>output = valarray(shape(cond), value=self.badvalue)<EOL>lower_bound = self.a * scale + loc<EOL>upper_bound = self.b * scale + loc<EOL>place(output, cond2, argsreduce(cond2, lower_bound)[<NUM_LIT:0>])<EOL>place(output, cond3, argsreduce(cond3, upper_bound)[<NUM_LIT:0>])<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))<EOL>scale, loc, goodargs = goodargs[-<NUM_LIT:2>], goodargs[-<NUM_LIT:1>], goodargs[:-<NUM_LIT:2>]<EOL>place(output, cond, self._isf(*goodargs) * scale + loc)<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Inverse survival function at q of the given RV.

Parameters
----------
q : array_like
    upper tail probability
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
x : ndarray or scalar
    Quantile corresponding to the upper tail probability q.


try:<EOL><INDENT>loc = theta[-<NUM_LIT:2>]<EOL>scale = theta[-<NUM_LIT:1>]<EOL>args = tuple(theta[:-<NUM_LIT:2>])<EOL><DEDENT>except IndexError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not self._argcheck(*args) or scale <= <NUM_LIT:0>:<EOL><INDENT>return inf<EOL><DEDENT>x = asarray((x-loc) / scale)<EOL>cond0 = (x <= self.a) | (self.b <= x)<EOL>if (any(cond0)):<EOL><INDENT>return inf<EOL><DEDENT>else:<EOL><INDENT>N = len(x)<EOL>return self._nnlf(x, *args) + N * log(scale)<EOL><DEDENT>

Return negative loglikelihood function

        Notes
        -----
        This is ``-sum(log pdf(x, theta), axis=0)`` where theta are the
        parameters (including loc and scale).


try:<EOL><INDENT>loc = theta[-<NUM_LIT:2>]<EOL>scale = theta[-<NUM_LIT:1>]<EOL>args = tuple(theta[:-<NUM_LIT:2>])<EOL><DEDENT>except IndexError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not self._argcheck(*args) or scale <= <NUM_LIT:0>:<EOL><INDENT>return inf<EOL><DEDENT>x = asarray((x-loc) / scale)<EOL>loginf = log(_XMAX)<EOL>if np.isneginf(self.a).all() and np.isinf(self.b).all():<EOL><INDENT>Nbad = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>cond0 = (x <= self.a) | (self.b <= x)<EOL>Nbad = sum(cond0)<EOL>if Nbad > <NUM_LIT:0>:<EOL><INDENT>x = argsreduce(~cond0, x)[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>N = len(x)<EOL>return self._nnlf(x, *args) + N*log(scale) + Nbad * <NUM_LIT> * loginf<EOL>

Return negative loglikelihood function,
        i.e., - sum (log pdf(x, theta), axis=0)
           where theta are the parameters (including loc and scale)


Narg = len(args)<EOL>if Narg > self.numargs:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>start = [None]*<NUM_LIT:2><EOL>if (Narg < self.numargs) or not ('<STR_LIT>' in kwds and<EOL>'<STR_LIT>' in kwds):<EOL><INDENT>start = self._fitstart(data)<EOL>args += start[Narg:-<NUM_LIT:2>]<EOL><DEDENT>loc = kwds.get('<STR_LIT>', start[-<NUM_LIT:2>])<EOL>scale = kwds.get('<STR_LIT>', start[-<NUM_LIT:1>])<EOL>args += (loc, scale)<EOL>x0, func, restore, args = self._reduce_func(args, kwds)<EOL>optimizer = kwds.get('<STR_LIT>', optimize.fmin)<EOL>if not callable(optimizer) and isinstance(optimizer, string_types):<EOL><INDENT>if not optimizer.startswith('<STR_LIT>'):<EOL><INDENT>optimizer = "<STR_LIT>"+optimizer<EOL><DEDENT>if optimizer == '<STR_LIT>':<EOL><INDENT>optimizer = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>optimizer = getattr(optimize, optimizer)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError("<STR_LIT>" % optimizer)<EOL><DEDENT><DEDENT>vals = optimizer(func, x0, args=(ravel(data),), disp=<NUM_LIT:0>)<EOL>if restore is not None:<EOL><INDENT>vals = restore(args, vals)<EOL><DEDENT>vals = tuple(vals)<EOL>return vals<EOL>

Return MLEs for shape, location, and scale parameters from data.

MLE stands for Maximum Likelihood Estimate.  Starting estimates for
the fit are given by input arguments; for any arguments not provided
with starting estimates, ``self._fitstart(data)`` is called to generate
such.

One can hold some parameters fixed to specific values by passing in
keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)
and ``floc`` and ``fscale`` (for location and scale parameters,
respectively).

Parameters
----------
data : array_like
    Data to use in calculating the MLEs.
args : floats, optional
    Starting value(s) for any shape-characterizing arguments (those not
    provided will be determined by a call to ``_fitstart(data)``).
    No default value.
kwds : floats, optional
    Starting values for the location and scale parameters; no default.
    Special keyword arguments are recognized as holding certain
    parameters fixed:

    f0...fn : hold respective shape parameters fixed.

    floc : hold location parameter fixed to specified value.

    fscale : hold scale parameter fixed to specified value.

    optimizer : The optimizer to use.  The optimizer must take func,
                and starting position as the first two arguments,
                plus args (for extra arguments to pass to the
                function to be optimized) and disp=0 to suppress
                output as keyword arguments.

Returns
-------
shape, loc, scale : tuple of floats
    MLEs for any shape statistics, followed by those for location and
    scale.

Notes
-----
This fit is computed by maximizing a log-likelihood function, with
penalty applied for samples outside of range of the distribution. The
returned answer is not guaranteed to be the globally optimal MLE, it
may only be locally optimal, or the optimization may fail altogether.


mu, mu2 = self.stats(*args, **{'<STR_LIT>': '<STR_LIT>'})<EOL>tmp = asarray(data)<EOL>muhat = tmp.mean()<EOL>mu2hat = tmp.var()<EOL>Shat = sqrt(mu2hat / mu2)<EOL>Lhat = muhat - Shat*mu<EOL>if not np.isfinite(Lhat):<EOL><INDENT>Lhat = <NUM_LIT:0><EOL><DEDENT>if not (np.isfinite(Shat) and (<NUM_LIT:0> < Shat)):<EOL><INDENT>Shat = <NUM_LIT:1><EOL><DEDENT>return Lhat, Shat<EOL>

Estimate loc and scale parameters from data using 1st and 2nd moments.

Parameters
----------
data : array_like
    Data to fit.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).

Returns
-------
Lhat : float
    Estimated location parameter for the data.
Shat : float
    Estimated scale parameter for the data.


@np.deprecate<EOL><INDENT>def est_loc_scale(self, data, *args):<DEDENT>

return self.fit_loc_scale(data, *args)<EOL>

This function is deprecated, use self.fit_loc_scale(data) instead.


args, loc, scale = self._parse_args(*args, **kwds)<EOL>args = tuple(map(asarray, args))<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>) & (loc == loc)<EOL>output = zeros(shape(cond0), '<STR_LIT:d>')<EOL>place(output, (<NUM_LIT:1>-cond0), self.badvalue)<EOL>goodargs = argsreduce(cond0, *args)<EOL>if self.numargs == <NUM_LIT:0>:<EOL><INDENT>place(output, cond0, self._entropy() + log(scale))<EOL><DEDENT>else:<EOL><INDENT>place(output, cond0, self.vecentropy(*goodargs) + log(scale))<EOL><DEDENT>return output<EOL>

Differential entropy of the RV.

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).
scale : array_like, optional
    Scale parameter (default=1).


def expect(self, func=None, args=(), loc=<NUM_LIT:0>, scale=<NUM_LIT:1>, lb=None, ub=None,<EOL>conditional=False, **kwds):

lockwds = {'<STR_LIT>': loc,<EOL>'<STR_LIT>': scale}<EOL>self._argcheck(*args)<EOL>if func is None:<EOL><INDENT>def fun(x, *args):<EOL><INDENT>return x * self.pdf(x, *args, **lockwds)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>def fun(x, *args):<EOL><INDENT>return func(x) * self.pdf(x, *args, **lockwds)<EOL><DEDENT><DEDENT>if lb is None:<EOL><INDENT>lb = loc + self.a * scale<EOL><DEDENT>if ub is None:<EOL><INDENT>ub = loc + self.b * scale<EOL><DEDENT>if conditional:<EOL><INDENT>invfac = (self.sf(lb, *args, **lockwds)<EOL>- self.sf(ub, *args, **lockwds))<EOL><DEDENT>else:<EOL><INDENT>invfac = <NUM_LIT:1.0><EOL><DEDENT>kwds['<STR_LIT:args>'] = args<EOL>olderr = np.seterr(all='<STR_LIT:ignore>')<EOL>vals = integrate.quad(fun, lb, ub, **kwds)[<NUM_LIT:0>] / invfac<EOL>np.seterr(**olderr)<EOL>return vals<EOL>

Calculate expected value of a function with respect to the
        distribution.

        The expected value of a function ``f(x)`` with respect to a
        distribution ``dist`` is defined as::

                    ubound
            E[x] = Integral(f(x) * dist.pdf(x))
                    lbound

        Parameters
        ----------
        func : callable, optional
            Function for which integral is calculated. Takes only one argument.
            The default is the identity mapping f(x) = x.
        args : tuple, optional
            Argument (parameters) of the distribution.
        lb, ub : scalar, optional
            Lower and upper bound for integration. default is set to the
            support of the distribution.
        conditional : bool, optional
            If True, the integral is corrected by the conditional probability
            of the integration interval.  The return value is the expectation
            of the function, conditional on being in the given interval.
            Default is False.

        Additional keyword arguments are passed to the integration routine.

        Returns
        -------
        expect : float
            The calculated expected value.

        Notes
        -----
        The integration behavior of this function is inherited from
        `integrate.quad`.


if extradoc is None:<EOL><INDENT>extradoc = '<STR_LIT>'<EOL><DEDENT>if extradoc.startswith('<STR_LIT>'):<EOL><INDENT>extradoc = extradoc[<NUM_LIT:2>:]<EOL><DEDENT>self.__doc__ = '<STR_LIT>'.join(['<STR_LIT>' % longname,<EOL>'<STR_LIT>', docheaders['<STR_LIT>'],<EOL>extradoc, '<STR_LIT>'])<EOL>self._construct_doc(docdict_discrete)<EOL>

Construct instance docstring from the rv_discrete template.


kwargs['<STR_LIT>'] = True<EOL>return super(rv_discrete, self).rvs(*args, **kwargs)<EOL>

Random variates of given type.

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).
size : int or tuple of ints, optional
    Defining number of random variates (default=1).  Note that `size`
    has to be given as keyword, not as positional argument.

Returns
-------
rvs : ndarray or scalar
    Random variates of given `size`.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray((k-loc))<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k <= self.b) & self._nonzero(k, *args)<EOL>cond = cond0 & cond1<EOL>output = zeros(shape(cond), '<STR_LIT:d>')<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, np.clip(self._pmf(*goodargs), <NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Probability mass function at k of the given RV.

Parameters
----------
k : array_like
    quantiles
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    Location parameter (default=0).

Returns
-------
pmf : array_like
    Probability mass function evaluated at k


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray((k-loc))<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k <= self.b) & self._nonzero(k, *args)<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, self._logpmf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the probability mass function at k of the given RV.

Parameters
----------
k : array_like
    Quantiles.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter. Default is 0.

Returns
-------
logpmf : array_like
    Log of the probability mass function evaluated at k.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray((k-loc))<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k < self.b)<EOL>cond2 = (k >= self.b)<EOL>cond = cond0 & cond1<EOL>output = zeros(shape(cond), '<STR_LIT:d>')<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>place(output, cond2*(cond0 == cond0), <NUM_LIT:1.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, np.clip(self._cdf(*goodargs), <NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Cumulative distribution function of the given RV.

Parameters
----------
k : array_like, int
    Quantiles.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).

Returns
-------
cdf : ndarray
    Cumulative distribution function evaluated at `k`.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray((k-loc))<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k < self.b)<EOL>cond2 = (k >= self.b)<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>place(output, cond2*(cond0 == cond0), <NUM_LIT:0.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, self._logcdf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the cumulative distribution function at k of the given RV

Parameters
----------
k : array_like, int
    Quantiles.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).

Returns
-------
logcdf : array_like
    Log of the cumulative distribution function evaluated at k.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray(k-loc)<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k <= self.b)<EOL>cond2 = (k < self.a) & cond0<EOL>cond = cond0 & cond1<EOL>output = zeros(shape(cond), '<STR_LIT:d>')<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>place(output, cond2, <NUM_LIT:1.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, np.clip(self._sf(*goodargs), <NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Survival function (1-cdf) at k of the given RV.

Parameters
----------
k : array_like
    Quantiles.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).

Returns
-------
sf : array_like
    Survival function evaluated at k.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray(k-loc)<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k <= self.b)<EOL>cond2 = (k < self.a) & cond0<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>place(output, cond2, <NUM_LIT:0.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, self._logsf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the survival function of the given RV.

Returns the log of the "survival function," defined as ``1 - cdf``,
evaluated at `k`.

Parameters
----------
k : array_like
    Quantiles.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).

Returns
-------
logsf : ndarray
    Log of the survival function evaluated at `k`.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>q, loc = map(asarray, (q, loc))<EOL>args = tuple(map(asarray, args))<EOL>cond0 = self._argcheck(*args) & (loc == loc)<EOL>cond1 = (q > <NUM_LIT:0>) & (q < <NUM_LIT:1>)<EOL>cond2 = (q == <NUM_LIT:1>) & cond0<EOL>cond = cond0 & cond1<EOL>output = valarray(shape(cond), value=self.badvalue, typecode='<STR_LIT:d>')<EOL>place(output, (q == <NUM_LIT:0>)*(cond == cond), self.a-<NUM_LIT:1>)<EOL>place(output, cond2, self.b)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((q,)+args+(loc,)))<EOL>loc, goodargs = goodargs[-<NUM_LIT:1>], goodargs[:-<NUM_LIT:1>]<EOL>place(output, cond, self._ppf(*goodargs) + loc)<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Percent point function (inverse of cdf) at q of the given RV

Parameters
----------
q : array_like
    Lower tail probability.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).
scale : array_like, optional
    Scale parameter (default=1).

Returns
-------
k : array_like
    Quantile corresponding to the lower tail probability, q.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>q, loc = map(asarray, (q, loc))<EOL>args = tuple(map(asarray, args))<EOL>cond0 = self._argcheck(*args) & (loc == loc)<EOL>cond1 = (q > <NUM_LIT:0>) & (q < <NUM_LIT:1>)<EOL>cond2 = (q == <NUM_LIT:1>) & cond0<EOL>cond = cond0 & cond1<EOL>output = valarray(shape(cond), value=self.badvalue, typecode='<STR_LIT:d>')<EOL>place(output, (q == <NUM_LIT:0>)*(cond == cond), self.b)<EOL>place(output, cond2, self.a-<NUM_LIT:1>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((q,)+args+(loc,)))<EOL>loc, goodargs = goodargs[-<NUM_LIT:1>], goodargs[:-<NUM_LIT:1>]<EOL>place(output, cond, self._isf(*goodargs) + loc)<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Inverse survival function (inverse of `sf`) at q of the given RV.

Parameters
----------
q : array_like
    Upper tail probability.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).

Returns
-------
k : ndarray or scalar
    Quantile corresponding to the upper tail probability, q.


def expect(self, func=None, args=(), loc=<NUM_LIT:0>, lb=None, ub=None,<EOL>conditional=False):

<EOL>maxcount = <NUM_LIT:1000><EOL>suppnmin = <NUM_LIT:100>  <EOL>if func is None:<EOL><INDENT>def fun(x):<EOL><INDENT>return (x+loc)*self._pmf(x, *args)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>def fun(x):<EOL><INDENT>return func(x+loc)*self._pmf(x, *args)<EOL><DEDENT><DEDENT>self._argcheck(*args)  <EOL>if lb is None:<EOL><INDENT>lb = (self.a)<EOL><DEDENT>else:<EOL><INDENT>lb = lb - loc   <EOL><DEDENT>if ub is None:<EOL><INDENT>ub = (self.b)<EOL><DEDENT>else:<EOL><INDENT>ub = ub - loc   <EOL><DEDENT>if conditional:<EOL><INDENT>if np.isposinf(ub)[()]:<EOL><INDENT>invfac = <NUM_LIT:1> - self.cdf(lb-<NUM_LIT:1>, *args)<EOL><DEDENT>else:<EOL><INDENT>invfac = <NUM_LIT:1> - self.cdf(lb-<NUM_LIT:1>, *args) - self.sf(ub, *args)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>invfac = <NUM_LIT:1.0><EOL><DEDENT>tot = <NUM_LIT:0.0><EOL>low, upp = self._ppf(<NUM_LIT>, *args), self._ppf(<NUM_LIT>, *args)<EOL>low = max(min(-suppnmin, low), lb)<EOL>upp = min(max(suppnmin, upp), ub)<EOL>supp = np.arange(low, upp+<NUM_LIT:1>, self.inc)  <EOL>tot = np.sum(fun(supp))<EOL>diff = <NUM_LIT><EOL>pos = upp + self.inc<EOL>count = <NUM_LIT:0><EOL>while (pos <= ub) and (diff > self.moment_tol) and count <= maxcount:<EOL><INDENT>diff = fun(pos)<EOL>tot += diff<EOL>pos += self.inc<EOL>count += <NUM_LIT:1><EOL><DEDENT>if self.a < <NUM_LIT:0>:  <EOL><INDENT>diff = <NUM_LIT><EOL>pos = low - self.inc<EOL>while ((pos >= lb) and (diff > self.moment_tol) and<EOL>count <= maxcount):<EOL><INDENT>diff = fun(pos)<EOL>tot += diff<EOL>pos -= self.inc<EOL>count += <NUM_LIT:1><EOL><DEDENT><DEDENT>if count > maxcount:<EOL><INDENT>warnings.warn('<STR_LIT>', RuntimeWarning)<EOL><DEDENT>return tot/invfac<EOL>

Calculate expected value of a function with respect to the distribution
for discrete distribution

Parameters
----------
fn : function (default: identity mapping)
    Function for which sum is calculated. Takes only one argument.
args : tuple
    argument (parameters) of the distribution
lb, ub : numbers, optional
    lower and upper bound for integration, default is set to the
    support of the distribution, lb and ub are inclusive (ul<=k<=ub)
conditional : bool, optional
    Default is False.
    If true then the expectation is corrected by the conditional
    probability of the integration interval. The return value is the
    expectation of the function, conditional on being in the given
    interval (k such that ul<=k<=ub).

Returns
-------
expect : float
    Expected value.

Notes
-----
* function is not vectorized
* accuracy: uses self.moment_tol as stopping criterium
  for heavy tailed distribution e.g. zipf(4), accuracy for
  mean, variance in example is only 1e-5,
  increasing precision (moment_tol) makes zipf very slow
* suppnmin=100 internal parameter for minimum number of points to
  evaluate could be added as keyword parameter, to evaluate functions
  with non-monotonic shapes, points include integers in (-suppnmin,
  suppnmin)
* uses maxcount=1000 limits the number of points that are evaluated
  to break loop for infinite sums
  (a maximum of suppnmin+1000 positive plus suppnmin+1000 negative
  integers are evaluated)


def binned_statistic(x, values, statistic='<STR_LIT>',<EOL>bins=<NUM_LIT:10>, range=None):

try:<EOL><INDENT>N = len(bins)<EOL><DEDENT>except TypeError:<EOL><INDENT>N = <NUM_LIT:1><EOL><DEDENT>if N != <NUM_LIT:1>:<EOL><INDENT>bins = [np.asarray(bins, float)]<EOL><DEDENT>if range is not None:<EOL><INDENT>if len(range) == <NUM_LIT:2>:<EOL><INDENT>range = [range]<EOL><DEDENT><DEDENT>medians, edges, xy = binned_statistic_dd([x], values, statistic,<EOL>bins, range)<EOL>return medians, edges[<NUM_LIT:0>], xy<EOL>

Compute a binned statistic for a set of data.

This is a generalization of a histogram function.  A histogram divides
the space into bins, and returns the count of the number of points in
each bin.  This function allows the computation of the sum, mean, median,
or other statistic of the values within each bin.

Parameters
----------
x : array_like
    A sequence of values to be binned.
values : array_like
    The values on which the statistic will be computed.  This must be
    the same shape as `x`.
statistic : string or callable, optional
    The statistic to compute (default is 'mean').
    The following statistics are available:

      * 'mean' : compute the mean of values for points within each bin.
        Empty bins will be represented by NaN.
      * 'median' : compute the median of values for points within each
        bin. Empty bins will be represented by NaN.
      * 'count' : compute the count of points within each bin.  This is
        identical to an unweighted histogram.  `values` array is not
        referenced.
      * 'sum' : compute the sum of values for points within each bin.
        This is identical to a weighted histogram.
      * function : a user-defined function which takes a 1D array of
        values, and outputs a single numerical statistic. This function
        will be called on the values in each bin.  Empty bins will be
        represented by function([]), or NaN if this returns an error.

bins : int or sequence of scalars, optional
    If `bins` is an int, it defines the number of equal-width
    bins in the given range (10, by default). If `bins` is a sequence,
    it defines the bin edges, including the rightmost edge, allowing
    for non-uniform bin widths.
range : (float, float) or [(float, float)], optional
    The lower and upper range of the bins.  If not provided, range
    is simply ``(x.min(), x.max())``.  Values outside the range are
    ignored.

Returns
-------
statistic : array
    The values of the selected statistic in each bin.
bin_edges : array of dtype float
    Return the bin edges ``(length(statistic)+1)``.
binnumber : 1-D ndarray of ints
    This assigns to each observation an integer that represents the bin
    in which this observation falls. Array has the same length as values.

See Also
--------
numpy.histogram, binned_statistic_2d, binned_statistic_dd

Notes
-----
All but the last (righthand-most) bin is half-open.  In other words, if
`bins` is::

  [1, 2, 3, 4]

then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the
second ``[2, 3)``.  The last bin, however, is ``[3, 4]``, which *includes*
4.

.. versionadded:: 0.11.0

Examples
--------
>>> stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean',
... bins=3)
(array([ 1.,  2.,  4.]), array([ 1.,  2.,  3.,  4.]), array([1, 2, 1, 2, 3]))

>>> stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean', bins=3)
(array([ 1.,  2.,  4.]), array([ 1.,  2.,  3.,  4.]), array([1, 2, 1, 2, 3]))