def save_flann(dstcnvs_normer, cachedir=None, verbose=True):
     cachedir = dstcnvs_normer.cachedir if cachedir is None else cachedir
     flann_fpath = dstcnvs_normer.get_flann_fpath(cachedir)
     if verbose:
         logger.info('flann.save_index(%r)' %
                     ut.path_ndir_split(flann_fpath, n=5))
     dstcnvs_normer.flann.save_index(flann_fpath)
def flann_cache(dpts,
                cache_dir='default',
                cfgstr='',
                flann_params={},
                use_cache=True,
                save=True,
                use_params_hash=True,
                use_data_hash=True,
                appname='vtool',
                verbose=utool.NOT_QUIET,
                quiet=utool.QUIET):
    """
    Tries to load a cached flann index before doing anything
    from vtool.nn
    """
    if verbose:
        print('+--- START CACHED FLANN INDEX ')
    if len(dpts) == 0:
        raise AssertionError(
            'cannot build flann when len(dpts) == 0. (prevents a segfault)')
    flann_fpath = get_flann_fpath(dpts,
                                  cache_dir,
                                  cfgstr,
                                  flann_params,
                                  use_params_hash=use_params_hash,
                                  use_data_hash=use_data_hash,
                                  appname=appname,
                                  verbose=verbose)
    # Load the index if it exists
    flann = pyflann.FLANN()
    flann.flann_fpath = flann_fpath
    if use_cache and exists(flann_fpath):
        try:
            flann.load_index(flann_fpath, dpts)
            if not quiet:
                print('...flann cache hit: %d vectors' % (len(dpts)))
            if verbose:
                print('L___ END FLANN INDEX ')
            return flann
        except Exception as ex:
            utool.printex(ex, '... cannot load index', iswarning=True)
    # Rebuild the index otherwise
    if not quiet:
        print('...flann cache miss.')
    flann = build_flann_index(dpts,
                              flann_params,
                              verbose=verbose,
                              quiet=quiet,
                              flann=flann)
    if verbose:
        print('flann.save_index(%r)' % utool.path_ndir_split(flann_fpath, n=2))
    if save:
        flann.save_index(flann_fpath)
    if verbose:
        print('L___ END CACHED FLANN INDEX ')
    return flann
Exemple #3
0
 def save(nnindexer, cachedir=None, fpath=None, verbose=True):
     r"""
     Caches a flann neighbor indexer to disk (not the data)
     """
     if NOSAVE_FLANN:
         if ut.VERYVERBOSE or verbose:
             print('[nnindex] flann save is deactivated')
         return False
     if fpath is None:
         flann_fpath = nnindexer.get_fpath(cachedir)
     else:
         flann_fpath = fpath
     nnindexer.flann_fpath = flann_fpath
     if ut.VERYVERBOSE or verbose:
         print('[nnindex] flann.save_index(%r)' %
               ut.path_ndir_split(flann_fpath, n=5))
     nnindexer.flann.save_index(flann_fpath)
Exemple #4
0
 def save(nnindexer, cachedir=None, fpath=None, verbose=True):
     r"""
     Caches a flann neighbor indexer to disk (not the data)
     """
     if NOSAVE_FLANN:
         if ut.VERYVERBOSE or verbose:
             print('[nnindex] flann save is deactivated')
         return False
     if fpath is None:
         flann_fpath = nnindexer.get_fpath(cachedir)
     else:
         flann_fpath = fpath
     nnindexer.flann_fpath = flann_fpath
     if ut.VERYVERBOSE or verbose:
         print('[nnindex] flann.save_index(%r)' %
               ut.path_ndir_split(flann_fpath, n=5))
     nnindexer.flann.save_index(flann_fpath)
Exemple #5
0
def flann_cache(dpts, cache_dir='default', cfgstr='', flann_params={},
                use_cache=True, save=True, use_params_hash=True,
                use_data_hash=True, appname='vtool', verbose=utool.NOT_QUIET,
                quiet=utool.QUIET):
    """
    Tries to load a cached flann index before doing anything
    from vtool.nn
    """
    if verbose:
        print('+--- START CACHED FLANN INDEX ')
    if len(dpts) == 0:
        raise AssertionError(
            'cannot build flann when len(dpts) == 0. (prevents a segfault)')
    flann_fpath = get_flann_fpath(dpts, cache_dir, cfgstr, flann_params,
                                  use_params_hash=use_params_hash,
                                  use_data_hash=use_data_hash, appname=appname,
                                  verbose=verbose)
    # Load the index if it exists
    flann = pyflann.FLANN()
    flann.flann_fpath = flann_fpath
    if use_cache and exists(flann_fpath):
        try:
            flann.load_index(flann_fpath, dpts)
            if not quiet:
                print('...flann cache hit: %d vectors' % (len(dpts)))
            if verbose:
                print('L___ END FLANN INDEX ')
            return flann
        except Exception as ex:
            utool.printex(ex, '... cannot load index', iswarning=True)
    # Rebuild the index otherwise
    if not quiet:
        print('...flann cache miss.')
    flann = build_flann_index(dpts, flann_params, verbose=verbose, quiet=quiet, flann=flann)
    if verbose:
        print('flann.save_index(%r)' % utool.path_ndir_split(flann_fpath, n=2))
    if save:
        flann.save_index(flann_fpath)
    if verbose:
        print('L___ END CACHED FLANN INDEX ')
    return flann
 def save_flann(dstcnvs_normer, cachedir=None, verbose=True):
     cachedir = dstcnvs_normer.cachedir if cachedir is None else cachedir
     flann_fpath = dstcnvs_normer.get_flann_fpath(cachedir)
     if verbose:
         print('flann.save_index(%r)' % ut.path_ndir_split(flann_fpath, n=5))
     dstcnvs_normer.flann.save_index(flann_fpath)
Exemple #7
0
def save_figure(fnum=None,
                fpath=None,
                fpath_strict=None,
                usetitle=False,
                overwrite=True,
                defaultext=None,
                verbose=1,
                dpi=None,
                figsize=None,
                saveax=None,
                fig=None,
                dpath=None):
    """
    Helper to save the figure image to disk. Tries to be smart about filename
    lengths, extensions, overwrites, etc...

    DEPCIATE

    Args:
        fnum (int):  figure number
        fpath (str): file path string
        fpath_strict (str): uses this exact path
        usetitle (bool): uses title as the fpath
        overwrite (bool): default=True
        defaultext (str): default extension
        verbose (int):  verbosity flag
        dpi (int): dots per inch
        figsize (tuple(int, int)): figure size
        saveax (bool or Axes): specifies if the axes should be saved instead of
            the figure

    References:
        for saving only a specific Axes
        http://stackoverflow.com/questions/4325733/save-a-subplot-in-matplotlib
        http://robotics.usc.edu/~ampereir/wordpress/?p=626
        http://stackoverflow.com/questions/1271023/resize-a-figure-automatically-in-matplotlib
    """
    if dpi is None:
        dpi = custom_constants.DPI

    if defaultext is None:
        if mpl.get_backend().lower() == 'pdf':
            defaultext = '.pdf'
        else:
            defaultext = '.jpg'
    #print('figsize = %r' % (figsize,))
    fig, fnum = prepare_figure_for_save(fnum, dpi, figsize, fig)
    if fpath_strict is None:
        fpath_clean = prepare_figure_fpath(fig, fpath, fnum, usetitle,
                                           defaultext, verbose, dpath)
    else:
        fpath_clean = fpath_strict
    savekw = {'dpi': dpi}
    if verbose > 1:
        #print('verbose = %r' % (verbose,))
        print('[pt.save_figure] saveax = %r' % (saveax, ))

    if False:
        import plottool as pt
        extent = pt.extract_axes_extents(fig)
        savekw['bbox_inches'] = extent

    if saveax is not None and saveax is not False:
        if verbose > 0:
            print("\n[pt.save_figure] SAVING ONLY EXTENT saveax=%r\n" %
                  (saveax, ))
        if saveax is True:
            saveax = plt.gca()
        #ut.embed()
        #saveax.set_aspect('auto')
        import plottool as pt
        import numpy as np
        xy, w, h = pt.get_axis_xy_width_height(saveax)
        ar = np.abs(w / h)
        if verbose == 2:
            print('[pt.save_figure] saveax xywh = %r' % ((xy, w, h), ))
            print('[pt.save_figure] saveax ar = %.2f' % (ar, ))
        saveax.set_aspect('equal')
        # extent is bbox in the form [[x0, y0], [x1, y1]]
        extent = saveax.get_window_extent().transformed(
            fig.dpi_scale_trans.inverted())
        if verbose == 2:
            print('[pt.save_figure] bbox ar = %.2f' % np.abs(
                (extent.width / extent.height, )))
        #extent = saveax.get_window_extent().transformed(fig.transFigure.inverted())
        #print('[df2] bbox ar = %.2f' % np.abs((extent.width / extent.height,)))
        savekw['bbox_inches'] = extent.expanded(1.0, 1.0)
        if verbose == 2:
            print('[pt.save_figure] savekw = ' + ut.dict_str(savekw))
        #ut.embed()

    #fname_clean = split(fpath_clean)[1]
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        if overwrite or not exists(fpath_clean):
            if verbose == 2:
                print('[pt.save_figure] save_figure() full=%r' %
                      (fpath_clean, ))
            elif verbose == 1:
                fpathndir = ut.path_ndir_split(fpath_clean, 5)
                print('[pt.save_figure] save_figure() ndir=%r' % (fpathndir))
            #fig.savefig(fpath_clean)
            if verbose > 1 or ut.VERBOSE:
                print(']pt.save_figure] fpath_clean = %s' % (fpath_clean, ))
                print('[pt.save_figure] savekw = ' + ut.dict_str(savekw))
            # savekw['bbox_inches'] = 'tight'
            #print('savekw = %r' % (savekw,))
            if fpath_clean.endswith('.png'):
                savekw['transparent'] = True
                savekw['edgecolor'] = 'none'
                #savekw['axes.edgecolor'] = 'none'
            fig.savefig(fpath_clean, **savekw)
        else:
            if verbose > 0:
                print('[pt.save_figure] not overwriteing')
    return fpath_clean
Exemple #8
0
def save_figure(fnum=None, fpath=None, fpath_strict=None, usetitle=False,
                overwrite=True, defaultext=None, verbose=1, dpi=None,
                figsize=None, saveax=None, fig=None, dpath=None):
    """
    Helper to save the figure image to disk. Tries to be smart about filename
    lengths, extensions, overwrites, etc...

    DEPCIATE

    Args:
        fnum (int):  figure number
        fpath (str): file path string
        fpath_strict (str): uses this exact path
        usetitle (bool): uses title as the fpath
        overwrite (bool): default=True
        defaultext (str): default extension
        verbose (int):  verbosity flag
        dpi (int): dots per inch
        figsize (tuple(int, int)): figure size
        saveax (bool or Axes): specifies if the axes should be saved instead of
            the figure

    References:
        for saving only a specific Axes
        http://stackoverflow.com/questions/4325733/save-a-subplot-in-matplotlib
        http://robotics.usc.edu/~ampereir/wordpress/?p=626
        http://stackoverflow.com/questions/1271023/resize-a-figure-automatically-in-matplotlib
    """
    if dpi is None:
        dpi = custom_constants.DPI

    if defaultext is None:
        if mpl.get_backend().lower() == 'pdf':
            defaultext = '.pdf'
        else:
            defaultext = '.jpg'
    #print('figsize = %r' % (figsize,))
    fig, fnum = prepare_figure_for_save(fnum, dpi, figsize, fig)
    if fpath_strict is None:
        fpath_clean = prepare_figure_fpath(fig, fpath, fnum, usetitle, defaultext, verbose, dpath)
    else:
        fpath_clean = fpath_strict
    savekw = {'dpi': dpi}
    if verbose > 1:
        #print('verbose = %r' % (verbose,))
        print('[pt.save_figure] saveax = %r' % (saveax,))

    if False:
        import plottool as pt
        extent = pt.extract_axes_extents(fig)
        savekw['bbox_inches'] = extent

    if saveax is not None and saveax is not False:
        if verbose > 0:
            print("\n[pt.save_figure] SAVING ONLY EXTENT saveax=%r\n" % (saveax,))
        if saveax is True:
            saveax = plt.gca()
        #ut.embed()
        #saveax.set_aspect('auto')
        import plottool as pt
        import numpy as np
        xy, w, h = pt.get_axis_xy_width_height(saveax)
        ar = np.abs(w / h)
        if verbose == 2:
            print('[pt.save_figure] saveax xywh = %r' % ((xy, w, h),))
            print('[pt.save_figure] saveax ar = %.2f' % (ar,))
        saveax.set_aspect('equal')
        # extent is bbox in the form [[x0, y0], [x1, y1]]
        extent = saveax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
        if verbose == 2:
            print('[pt.save_figure] bbox ar = %.2f' % np.abs((extent.width / extent.height,)))
        #extent = saveax.get_window_extent().transformed(fig.transFigure.inverted())
        #print('[df2] bbox ar = %.2f' % np.abs((extent.width / extent.height,)))
        savekw['bbox_inches'] = extent.expanded(1.0, 1.0)
        if verbose == 2:
            print('[pt.save_figure] savekw = ' + ut.dict_str(savekw))
        #ut.embed()

    #fname_clean = split(fpath_clean)[1]
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        if overwrite or not exists(fpath_clean):
            if verbose == 2:
                print('[pt.save_figure] save_figure() full=%r' % (fpath_clean,))
            elif verbose == 1:
                fpathndir = ut.path_ndir_split(fpath_clean, 5)
                print('[pt.save_figure] save_figure() ndir=%r' % (fpathndir))
            #fig.savefig(fpath_clean)
            if verbose > 1 or ut.VERBOSE:
                print(']pt.save_figure] fpath_clean = %s' % (fpath_clean, ))
                print('[pt.save_figure] savekw = ' + ut.dict_str(savekw))
            # savekw['bbox_inches'] = 'tight'
            #print('savekw = %r' % (savekw,))
            if fpath_clean.endswith('.png'):
                savekw['transparent'] = True
                savekw['edgecolor'] = 'none'
                #savekw['axes.edgecolor'] = 'none'
            fig.savefig(fpath_clean, **savekw)
        else:
            if verbose > 0:
                print('[pt.save_figure] not overwriteing')
    return fpath_clean