def draw_tree_model(model, **kwargs): import plottool as pt import networkx as netx if not ut.get_argval('--hackjunc'): fnum = pt.ensure_fnum(None) fig = pt.figure(fnum=fnum, doclf=True) # NOQA ax = pt.gca() #name_nodes = sorted(ut.list_getattr(model.ttype2_cpds[NAME_TTYPE], 'variable')) netx_graph = model.to_markov_model() #pos = netx.pygraphviz_layout(netx_graph) #pos = netx.graphviz_layout(netx_graph) #pos = get_hacked_pos(netx_graph, name_nodes, prog='neato') pos = netx.nx_pydot.pydot_layout(netx_graph) node_color = [pt.WHITE] * len(pos) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color, node_size=1100) netx.draw(netx_graph, **drawkw) if kwargs.get('show_title', True): pt.set_figtitle('Markov Model') if not ut.get_argval('--hackmarkov'): fnum = pt.ensure_fnum(None) fig = pt.figure(fnum=fnum, doclf=True) # NOQA ax = pt.gca() netx_graph = model.to_junction_tree() # prettify nodes def fixtupkeys(dict_): return { ', '.join(k) if isinstance(k, tuple) else k: fixtupkeys(v) for k, v in dict_.items() } # FIXME n = fixtupkeys(netx_graph.node) e = fixtupkeys(netx_graph.edge) a = fixtupkeys(netx_graph.adj) netx_graph.nodes.update(n) netx_graph.edges.update(e) netx_graph.adj.update(a) #netx_graph = model.to_markov_model() #pos = netx.pygraphviz_layout(netx_graph) #pos = netx.graphviz_layout(netx_graph) pos = netx.nx_pydot.pydot_layout(netx_graph) node_color = [pt.WHITE] * len(pos) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color, node_size=2000) netx.draw(netx_graph, **drawkw) if kwargs.get('show_title', True): pt.set_figtitle('Junction/Clique Tree / Cluster Graph')
def plot(self, fnum=None, pnum=(1, 1, 1), **kwargs): import plottool as pt fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum, docla=True, doclf=True) show_keypoints(self.chip, self.kpts, fnum=fnum, pnum=pnum, **kwargs) if self.figtitle is not None: pt.set_figtitle(self.figtitle)
def draw_aids(infr, aids, fnum=None): from ibeis.viz import viz_chip import plottool as pt fnum = pt.ensure_fnum(None) fig = pt.figure(fnum=fnum) viz_chip.show_many_chips(infr.ibs, aids, fnum=fnum) return fig
def show_single_coverage_mask(qreq_, cm, weight_mask_m, weight_mask, daids, fnum=None): import plottool as pt from ibeis import viz fnum = pt.ensure_fnum(fnum) idx_list = ut.dict_take(cm.daid2_idx, daids) nPlots = len(idx_list) + 1 nRows, nCols = pt.get_square_row_cols(nPlots) pnum_ = pt.make_pnum_nextgen(nRows, nCols) pt.figure(fnum=fnum, pnum=(1, 2, 1)) # Draw coverage masks with bbox # <FlipHack> #weight_mask_m = np.fliplr(np.flipud(weight_mask_m)) #weight_mask = np.fliplr(np.flipud(weight_mask)) # </FlipHack> stacked_weights, offset_tup, sf_tup = vt.stack_images(weight_mask_m, weight_mask, return_sf=True) (woff, hoff) = offset_tup[1] wh1 = weight_mask_m.shape[0:2][::-1] wh2 = weight_mask.shape[0:2][::-1] pt.imshow(255 * (stacked_weights), fnum=fnum, pnum=pnum_(0), title='(query image) What did match vs what should match') pt.draw_bbox(( 0, 0) + wh1, bbox_color=(0, 0, 1)) pt.draw_bbox((woff, hoff) + wh2, bbox_color=(0, 0, 1)) # Get contributing matches qaid = cm.qaid daid_list = daids fm_list = ut.take(cm.fm_list, idx_list) fs_list = ut.take(cm.fs_list, idx_list) # Draw matches for px, (daid, fm, fs) in enumerate(zip(daid_list, fm_list, fs_list), start=1): viz.viz_matches.show_matches2(qreq_.ibs, qaid, daid, fm, fs, draw_pts=False, draw_lines=True, draw_ell=False, fnum=fnum, pnum=pnum_(px), darken=.5) coverage_score = score_matching_mask(weight_mask_m, weight_mask) pt.set_figtitle('score=%.4f' % (coverage_score,))
def show_probability_chip(ibs, aid, species=None, fnum=None, config2_=None, **kwargs): """ TODO: allow species override in controller CommandLine: python -m ibeis.viz.viz_hough --exec-show_probability_chip --cnn --show python -m ibeis.viz.viz_hough --exec-show_probability_chip --cnn --show --db PZ_Master1 python -m ibeis.viz.viz_hough --exec-show_probability_chip --cnn --show --db PZ_Master1 --aid 9970 Example: >>> # SCRIPT >>> from ibeis.viz.viz_hough import * # NOQA >>> import ibeis >>> from ibeis.viz import viz_chip >>> ibs, aid_list, kwargs, config2_ = viz_chip.testdata_showchip() >>> fnum = 1 >>> species = None >>> aid = aid_list[0] >>> fig, ax = show_probability_chip(ibs, aid, species, fnum, **kwargs) >>> ut.show_if_requested() """ fnum = pt.ensure_fnum(fnum) title = 'Probability Chip: ' + ', '.join(vh.get_annot_text(ibs, [aid], True)) hough_cpath = ibs.get_annot_probchip_fpath(aid, config2_=config2_) img = gtool.imread(hough_cpath) fig, ax = viz_image2.show_image(img, title=title, fnum=fnum, **kwargs) return fig, ax
def show_sv_simple(chip1, chip2, kpts1, kpts2, fm, inliers, mx=None, fnum=1, vert=None, **kwargs): """ CommandLine: python -m plottool.draw_sv --test-show_sv_simple --show Example: >>> # DISABLE_DOCTEST >>> from plottool.draw_sv import * # NOQA >>> import vtool as vt >>> kpts1, kpts2, fm, aff_inliers, chip1, chip2, xy_thresh_sqrd = vt.testdata_matching_affine_inliers() >>> inliers = aff_inliers >>> mx = None >>> fnum = 1 >>> vert = None # ut.get_argval('--vert', type_=bool, default=None) >>> result = show_sv_simple(chip1, chip2, kpts1, kpts2, fm, inliers, mx, fnum, vert=vert) >>> print(result) >>> ut.show_if_requested() """ import plottool as pt colors = df2.distinct_colors(2, brightness=.95) color1, color2 = colors[0:2] # Begin the drawing fnum = pt.ensure_fnum(fnum) df2.figure(fnum=fnum, pnum=(1, 1, 1), docla=True, doclf=True) #dmkwargs = dict(fs=None, title='Inconsistent Matches', all_kpts=False, draw_lines=True, # docla=True, draw_border=True, fnum=fnum, pnum=(1, 1, 1), colors=df2.ORANGE) inlier_mask = vt.index_to_boolmask(inliers, maxval=len(fm)) fm_inliers = fm.compress(inlier_mask, axis=0) fm_outliers = fm.compress(np.logical_not(inlier_mask), axis=0) ax, xywh1, xywh2 = df2.show_chipmatch2(chip1, chip2, vert=vert) fmatch_kw = dict(ell_linewidth=2, ell_alpha=.7, line_alpha=.7) df2.plot_fmatch(xywh1, xywh2, kpts1, kpts2, fm_inliers, colors=color1, **fmatch_kw) df2.plot_fmatch(xywh1, xywh2, kpts1, kpts2, fm_outliers, colors=color2, **fmatch_kw)
def gridsearch_image_function(param_info, test_func, args=tuple(), show_func=None): """ gridsearch for a function that produces a single image """ import plottool as pt cfgdict_list, cfglbl_list = param_info.get_gridsearch_input( defaultslice=slice(0, 10)) fnum = pt.ensure_fnum(None) if show_func is None: show_func = pt.imshow lbl = ut.get_funcname(test_func) cfgresult_list = [ test_func(*args, **cfgdict) for cfgdict in ut.ProgressIter(cfgdict_list, lbl=lbl) ] onclick_func = None ut.interact_gridsearch_result_images(show_func, cfgdict_list, cfglbl_list, cfgresult_list, fnum=fnum, figtitle=lbl, unpack=False, max_plots=25, onclick_func=onclick_func) pt.iup()
def draw_junction_tree(model, fnum=None, **kwargs): import plottool as pt fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum) ax = pt.gca() from pgmpy.models import JunctionTree if not isinstance(model, JunctionTree): netx_graph = model.to_junction_tree() else: netx_graph = model # prettify nodes def fixtupkeys(dict_): return { ', '.join(k) if isinstance(k, tuple) else k: fixtupkeys(v) for k, v in dict_.items() } n = fixtupkeys(netx_graph.node) e = fixtupkeys(netx_graph.edge) a = fixtupkeys(netx_graph.adj) netx_graph.node = n netx_graph.edge = e netx_graph.adj = a #netx_graph = model.to_markov_model() #pos = netx.pygraphviz_layout(netx_graph) #pos = netx.graphviz_layout(netx_graph) pos = netx.pydot_layout(netx_graph) node_color = [pt.NEUTRAL] * len(pos) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color, node_size=2000) netx.draw(netx_graph, **drawkw) if kwargs.get('show_title', True): pt.set_figtitle('Junction / Clique Tree / Cluster Graph')
def show_probability_chip(ibs, aid, species=None, fnum=None, config2_=None, blend=False, **kwargs): """ TODO: allow species override in controller CommandLine: python -m ibeis.viz.viz_hough --exec-show_probability_chip --cnn --show python -m ibeis.viz.viz_hough --exec-show_probability_chip --cnn --show --db PZ_Master1 python -m ibeis.viz.viz_hough --exec-show_probability_chip --cnn --show --db PZ_Master1 --aid 9970 Example: >>> # SCRIPT >>> from ibeis.viz.viz_hough import * # NOQA >>> import ibeis >>> from ibeis.viz import viz_chip >>> ibs, aid_list, kwargs, config2_ = viz_chip.testdata_showchip() >>> fnum = 1 >>> species = None >>> aid = aid_list[0] >>> fig, ax = show_probability_chip(ibs, aid, species, fnum, blend=True, **kwargs) >>> ut.show_if_requested() """ fnum = pt.ensure_fnum(fnum) title = 'Probability Chip: ' + ', '.join(vh.get_annot_text(ibs, [aid], True)) hough_cpath = ibs.get_annot_probchip_fpath(aid, config2_=config2_) img = vt.imread(hough_cpath) if blend: chip = ibs.get_annot_chips(aid, config2_=config2_) img = vt.blend_images_multiply(chip, vt.resize_mask(img, chip)) fig, ax = viz_image2.show_image(img, title=title, fnum=fnum, **kwargs) return fig, ax
def __init__(self, rchip1, rchip2, kpts1, kpts2, fm, fs, fsv, vecs1, vecs2, H1=None, H2=None, fnum=None, **kwargs): # Drawing Data self.rchip1 = rchip1 self.rchip2 = rchip2 self.kpts1 = kpts1 self.kpts2 = kpts2 self.fm = fm self.fs = fs self.fsv = fsv self.vecs1 = vecs1 self.vecs2 = vecs2 self.H1 = H1 self.H2 = H2 # Drawing settings kwargs = kwargs.copy() self.warp_homog = False self.mode = kwargs.pop('mode', 0) self.mx = kwargs.pop('mx', None) self.vert = kwargs.pop('vert', None) self.same_fig = kwargs.get('same_fig', True) self.last_fx = 0 # self.figtitle = kwargs.get('figtitle', 'Inspect Matches') self.xywh2 = None import plottool as pt self.fnum2 = pt.ensure_fnum(fnum) self.title = kwargs.get('title', True) self.truth = kwargs.pop('truth', None) #self.fnum2 = pt.next_fnum() #if BASE_CLASS is not object: kwargs['interaction_name'] = 'matches' super(MatchInteraction2, self).__init__(**kwargs)
def __init__(self, rchip1, rchip2, kpts1, kpts2, fm, fs, fsv, vecs1, vecs2, H1=None, H2=None, fnum=None, **kwargs): # Drawing Data self.rchip1 = rchip1 self.rchip2 = rchip2 self.kpts1 = kpts1 self.kpts2 = kpts2 self.fm = fm self.fs = fs self.fsv = fsv self.vecs1 = vecs1 self.vecs2 = vecs2 self.H1 = H1 self.H2 = H2 # Drawing settings kwargs = kwargs.copy() self.warp_homog = False self.mode = kwargs.pop("mode", 0) self.mx = kwargs.pop("mx", None) self.vert = kwargs.pop("vert", None) self.same_fig = kwargs.get("same_fig", True) self.last_fx = 0 # self.figtitle = kwargs.get('figtitle', 'Inspect Matches') self.xywh2 = None import plottool as pt self.fnum2 = pt.ensure_fnum(fnum) self.title = kwargs.get("title", True) self.truth = kwargs.pop("truth", None) # self.fnum2 = pt.next_fnum() # if BASE_CLASS is not object: kwargs["interaction_name"] = "matches" super(MatchInteraction2, self).__init__(**kwargs)
def draw_tree_model(model, **kwargs): import plottool as pt import networkx as netx if not ut.get_argval('--hackjunc'): fnum = pt.ensure_fnum(None) fig = pt.figure(fnum=fnum, doclf=True) # NOQA ax = pt.gca() #name_nodes = sorted(ut.list_getattr(model.ttype2_cpds['name'], 'variable')) netx_graph = model.to_markov_model() #pos = netx.pygraphviz_layout(netx_graph) #pos = netx.graphviz_layout(netx_graph) #pos = get_hacked_pos(netx_graph, name_nodes, prog='neato') pos = netx.pydot_layout(netx_graph) node_color = [pt.WHITE] * len(pos) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color, node_size=1100) netx.draw(netx_graph, **drawkw) if kwargs.get('show_title', True): pt.set_figtitle('Markov Model') if not ut.get_argval('--hackmarkov'): fnum = pt.ensure_fnum(None) fig = pt.figure(fnum=fnum, doclf=True) # NOQA ax = pt.gca() netx_graph = model.to_junction_tree() # prettify nodes def fixtupkeys(dict_): return { ', '.join(k) if isinstance(k, tuple) else k: fixtupkeys(v) for k, v in dict_.items() } n = fixtupkeys(netx_graph.node) e = fixtupkeys(netx_graph.edge) a = fixtupkeys(netx_graph.adj) netx_graph.node = n netx_graph.edge = e netx_graph.adj = a #netx_graph = model.to_markov_model() #pos = netx.pygraphviz_layout(netx_graph) #pos = netx.graphviz_layout(netx_graph) pos = netx.pydot_layout(netx_graph) node_color = [pt.WHITE] * len(pos) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color, node_size=2000) netx.draw(netx_graph, **drawkw) if kwargs.get('show_title', True): pt.set_figtitle('Junction/Clique Tree / Cluster Graph')
def show_selected(self, event): import plottool as pt print('show_selected') from ibeis.viz import viz_chip fnum = pt.ensure_fnum(None) print('fnum = %r' % (fnum, )) pt.figure(fnum=fnum) viz_chip.show_many_chips(self.ibs, self.selected_aids) pt.update()
def show_selected(self, event): import plottool as pt print('show_selected') from ibeis.viz import viz_chip fnum = pt.ensure_fnum(None) print('fnum = %r' % (fnum,)) pt.figure(fnum=fnum) viz_chip.show_many_chips(self.ibs, self.selected_aids) pt.update()
def visualize_vocab_word(ibs, invassign, wx, fnum=None): """ Example: >>> from ibeis.new_annots import * # NOQA >>> import plottool as pt >>> pt.qt4ensure() >>> ibs, aid_list, vocab = testdata_vocab() >>> #aid_list = aid_list[0:1] >>> fstack = StackedFeatures(ibs, aid_list) >>> nAssign = 2 >>> invassign = fstack.inverted_assignment(vocab, nAssign) >>> sortx = ut.argsort(invassign.num_list)[::-1] >>> wx_list = ut.take(invassign.wx_list, sortx) >>> wx = wx_list[0] """ import plottool as pt pt.qt4ensure() vecs = invassign.get_vecs(wx) word = invassign.vocab.wx2_word[wx] word_patches = invassign.get_patches(wx) average_patch = np.mean(word_patches, axis=0) average_vec = vecs.mean(axis=0) average_vec = word word with_sift = True fnum = 2 fnum = pt.ensure_fnum(fnum) if with_sift: patch_img = pt.render_sift_on_patch(average_patch, average_vec) #sift_word_patches = [pt.render_sift_on_patch(patch, vec) for patch, vec in ut.ProgIter(list(zip(word_patches, vecs)))] #stacked_patches = vt.stack_square_images(word_patches) #stacked_patches = vt.stack_square_images(sift_word_patches) else: patch_img = average_patch stacked_patches = vt.stack_square_images(word_patches) solidbar = np.zeros((patch_img.shape[0], int(patch_img.shape[1] * .1), 3), dtype=patch_img.dtype) border_color = (100, 10, 10) # bgr, darkblue if ut.is_float(solidbar): solidbar[:, :, :] = (np.array(border_color) / 255)[None, None] else: solidbar[:, :, :] = np.array(border_color)[None, None] word_img = vt.stack_image_list([patch_img, solidbar, stacked_patches], vert=False, modifysize=True) pt.imshow(word_img, fnum=fnum) #pt.imshow(patch_img, pnum=(1, 2, 1), fnum=fnum) #patch_size = 64 #half_size = patch_size / 2 #pt.imshow(stacked_patches, pnum=(1, 2, 2), fnum=fnum) pt.iup()
def show_bayesian_model(model, evidence={}, soft_evidence={}, fnum=None, **kwargs): r""" References: http://stackoverflow.com/questions/22207802/networkx-node-level-or-layer Ignore: import nx2tikz print(nx2tikz.dumps_tikz(model, layout='layered', use_label=True)) Ignore: sudo apt-get install libgraphviz4 libgraphviz-dev -y sudo apt-get install libgraphviz-dev pip install pygraphviz sudo pip3 install pygraphviz \ --install-option="--include-path=/usr/include/graphviz" \ --install-option="--library-path=/usr/lib/graphviz/" python -c "import pygraphviz; print(pygraphviz.__file__)" python3 -c "import pygraphviz; print(pygraphviz.__file__)" CommandLine: python -m ibeis.algo.hots.pgm_viz --exec-show_model --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.algo.hots.pgm_viz import * # NOQA >>> model = '?' >>> evidence = {} >>> soft_evidence = {} >>> result = show_model(model, evidence, soft_evidence) >>> print(result) >>> ut.quit_if_noshow() >>> import plottool as pt >>> ut.show_if_requested() """ import plottool as pt fnum = pt.ensure_fnum(fnum) top_assignments = kwargs.get('top_assignments', None) if evidence and top_assignments and 'factor_list' in kwargs: pnum1 = (3, 1, (slice(0, 2), 0)) pnum2 = (3, 8, (2, slice(4, None))) else: pnum1 = (1, 1, 1) draw_bayesian_model(model, evidence, soft_evidence, fnum=fnum, pnum=pnum1, **kwargs) # Draw probability hist if top_assignments is not None: draw_map_histogram(top_assignments, fnum=fnum, pnum=pnum2)
def __init__(self, fnum=None, _pnumiter=None, interactive=None, **kwargs): self.nRows = kwargs.get('nRows', None) self.nCols = kwargs.get('nCols', None) self._pnumiter = _pnumiter self.pnum_list = [] self.interactive = interactive self.ishow_func_list = [] self.func_list = [] self.fnum = pt.ensure_fnum(fnum) self.fig = None autostart = False super(ExpandableInteraction, self).__init__(autostart=autostart, **kwargs)
def draw_map_histogram(top_assignments, fnum=None, pnum=(1, 1, 1)): import plottool as pt bin_labels = ut.get_list_column(top_assignments, 0) bin_vals = ut.get_list_column(top_assignments, 1) fnum = pt.ensure_fnum(fnum) # bin_labels = ['\n'.join(ut.textwrap.wrap(_lbl, width=30)) for _lbl in bin_labels] pt.draw_histogram(bin_labels, bin_vals, fnum=fnum, pnum=pnum, transpose=True, use_darkbackground=False, #xtick_rotation=-10, ylabel='Prob', xlabel='assignment') pt.set_title('Assignment probabilities')
def show_single_coverage_mask(qreq_, cm, weight_mask_m, weight_mask, daids, fnum=None): import plottool as pt from ibeis import viz fnum = pt.ensure_fnum(fnum) idx_list = ut.dict_take(cm.daid2_idx, daids) nPlots = len(idx_list) + 1 nRows, nCols = pt.get_square_row_cols(nPlots) pnum_ = pt.make_pnum_nextgen(nRows, nCols) pt.figure(fnum=fnum, pnum=(1, 2, 1)) # Draw coverage masks with bbox # <FlipHack> #weight_mask_m = np.fliplr(np.flipud(weight_mask_m)) #weight_mask = np.fliplr(np.flipud(weight_mask)) # </FlipHack> stacked_weights, offset_tup, sf_tup = vt.stack_images(weight_mask_m, weight_mask, return_sf=True) (woff, hoff) = offset_tup[1] wh1 = weight_mask_m.shape[0:2][::-1] wh2 = weight_mask.shape[0:2][::-1] pt.imshow(255 * (stacked_weights), fnum=fnum, pnum=pnum_(0), title='(query image) What did match vs what should match') pt.draw_bbox((0, 0) + wh1, bbox_color=(0, 0, 1)) pt.draw_bbox((woff, hoff) + wh2, bbox_color=(0, 0, 1)) # Get contributing matches qaid = cm.qaid daid_list = daids fm_list = ut.take(cm.fm_list, idx_list) fs_list = ut.take(cm.fs_list, idx_list) # Draw matches for px, (daid, fm, fs) in enumerate(zip(daid_list, fm_list, fs_list), start=1): viz.viz_matches.show_matches2(qreq_.ibs, qaid, daid, fm, fs, draw_pts=False, draw_lines=True, draw_ell=False, fnum=fnum, pnum=pnum_(px), darken=.5) coverage_score = score_matching_mask(weight_mask_m, weight_mask) pt.set_figtitle('score=%.4f' % (coverage_score, ))
def show_edge(infr, edge, fnum=None, pnum=None, **kwargs): import plottool as pt match = infr._exec_pairwise_match([edge])[0] fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum, pnum=pnum) ax = pt.gca() showkw = dict(vert=False, heatmask=True, show_lines=False, show_ell=False, show_ori=False, show_eig=False, modifysize=True) showkw.update(kwargs) match.show(ax, **showkw)
def draw_map_histogram(top_assignments, fnum=None, pnum=(1, 1, 1)): import plottool as pt bin_labels = ut.get_list_column(top_assignments, 0) bin_vals = ut.get_list_column(top_assignments, 1) fnum = pt.ensure_fnum(fnum) # bin_labels = ['\n'.join(ut.textwrap.wrap(_lbl, width=30)) for _lbl in bin_labels] pt.draw_histogram( bin_labels, bin_vals, fnum=fnum, pnum=pnum, transpose=True, use_darkbackground=False, #xtick_rotation=-10, ylabel='Prob', xlabel='assignment') pt.set_title('Assignment probabilities')
def plot_annotaiton_gps(X_data): """ Plots gps coordinates on a map projection InstallBasemap: sudo apt-get install libgeos-dev pip install git+https://github.com/matplotlib/basemap Ignore: pip install git+git://github.com/myuser/foo.git@v123 """ import plottool as pt from mpl_toolkits.basemap import Basemap # lat = X_data[1:5, 1] # lon = X_data[1:5, 2] lat = X_data[:, 1] # NOQA lon = X_data[:, 2] # NOQA fnum = pt.ensure_fnum(None) fig = pt.figure(fnum=fnum, doclf=True, docla=True) # NOQA pt.close_figure(fig) fig = pt.figure(fnum=fnum, doclf=True, docla=True) # setup Lambert Conformal basemap. m = Basemap( llcrnrlon=lon.min(), urcrnrlon=lon.max(), llcrnrlat=lat.min(), urcrnrlat=lat.max(), projection="cea", resolution="h", ) # draw coastlines. # m.drawcoastlines() # m.drawstates() # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents will be drawn on top. # m.bluemarble() m.drawmapboundary(fill_color="aqua") m.fillcontinents(color="coral", lake_color="aqua") # Convert GPS to projected coordinates x1, y1 = m(lon, lat) # convert to meters # lon==X, lat==Y m.plot(x1, y1, "o") fig.show()
def gridsearch_image_function(param_info, test_func, args=tuple(), show_func=None): """ gridsearch for a function that produces a single image """ import plottool as pt cfgdict_list, cfglbl_list = param_info.get_gridsearch_input(defaultslice=slice(0, 10)) fnum = pt.ensure_fnum(None) if show_func is None: show_func = pt.imshow lbl = ut.get_funcname(test_func) cfgresult_list = [ test_func(*args, **cfgdict) for cfgdict in ut.ProgressIter(cfgdict_list, lbl=lbl) ] onclick_func = None ut.interact_gridsearch_result_images( show_func, cfgdict_list, cfglbl_list, cfgresult_list, fnum=fnum, figtitle=lbl, unpack=False, max_plots=25, onclick_func=onclick_func) pt.iup()
def draw_junction_tree(model, fnum=None, **kwargs): import plottool as pt fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum) ax = pt.gca() from pgmpy.models import JunctionTree if not isinstance(model, JunctionTree): netx_graph = model.to_junction_tree() else: netx_graph = model # prettify nodes def fixtupkeys(dict_): return { ', '.join(k) if isinstance(k, tuple) else k: fixtupkeys(v) for k, v in dict_.items() } n = fixtupkeys(netx_graph.node) e = fixtupkeys(netx_graph.edge) a = fixtupkeys(netx_graph.adj) netx_graph.node = n netx_graph.edge = e netx_graph.adj = a #netx_graph = model.to_markov_model() #pos = nx.nx_agraph.pygraphviz_layout(netx_graph) #pos = nx.nx_agraph.graphviz_layout(netx_graph) pos = nx.pydot_layout(netx_graph) node_color = [pt.NEUTRAL] * len(pos) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color, node_size=2000) nx.draw(netx_graph, **drawkw) if kwargs.get('show_title', True): pt.set_figtitle('Junction / Clique Tree / Cluster Graph')
def ishow_chip(ibs, aid, fnum=2, fx=None, dodraw=True, config2_=None, ischild=False, **kwargs): r""" # TODO: split into two interactions interact chip and interact chip features Args: ibs (IBEISController): ibeis controller object aid (int): annotation id fnum (int): figure number fx (None): CommandLine: python -m ibeis.viz.interact.interact_chip --test-ishow_chip --show python -m ibeis.viz.interact.interact_chip --test-ishow_chip --show --aid 2 Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.interact.interact_chip import * # NOQA >>> import ibeis >>> # build test data >>> ibs = ibeis.opendb('testdb1') >>> aid = ut.get_argval('--aid', type_=int, default=1) >>> fnum = 2 >>> fx = None >>> # execute function >>> dodraw = ut.show_was_requested() >>> result = ishow_chip(ibs, aid, fnum, fx, dodraw) >>> # verify results >>> pt.show_if_requested() >>> print(result) """ fnum = pt.ensure_fnum(fnum) vh.ibsfuncs.assert_valid_aids(ibs, (aid,)) # TODO: Reconcile this with interact keypoints. # Preferably this will call that but it will set some fancy callbacks if not ischild: fig = ih.begin_interaction('chip', fnum) else: fig = pt.gcf() #fig = pt.figure(fnum=fnum, pnum=pnum) # Get chip info (make sure get_chips is called first) #mode_ptr = [1] mode_ptr = [0] def _select_fxth_kpt(fx): # Get the fx-th keypiont chip = ibs.get_annot_chips(aid, config2_=config2_) kp = ibs.get_annot_kpts(aid, config2_=config2_)[fx] sift = ibs.get_annot_vecs(aid, config2_=config2_)[fx] # Draw chip + keypoints + highlighted plots _chip_view(pnum=(2, 1, 1), sel_fx=fx) #ishow_chip(ibs, aid, fnum=None, fx=fx, config2_=config2_, **kwargs) # Draw the selected feature plots nRows, nCols, px = (2, 3, 3) draw_feat_row(chip, fx, kp, sift, fnum, nRows, nCols, px, None) def _chip_view(mode=0, pnum=(1, 1, 1), **kwargs): print('... _chip_view mode=%r' % mode_ptr[0]) kwargs['ell'] = mode_ptr[0] == 1 kwargs['pts'] = mode_ptr[0] == 2 if not ischild: df2.figure(fnum=fnum, pnum=pnum, docla=True, doclf=True) # Toggle no keypoints view viz.show_chip(ibs, aid, fnum=fnum, pnum=pnum, config2_=config2_, **kwargs) df2.set_figtitle('Chip View') def _on_chip_click(event): print('[inter] clicked chip') ax, x, y = event.inaxes, event.xdata, event.ydata if ih.clicked_outside_axis(event): if not ischild: print('... out of axis') mode_ptr[0] = (mode_ptr[0] + 1) % 3 _chip_view(**kwargs) else: if event.button == 3: # right-click import guitool #from ibeis.viz.interact import interact_chip height = fig.canvas.geometry().height() qpoint = guitool.newQPoint(event.x, height - event.y) refresh_func = partial(_chip_view, **kwargs) callback_list = build_annot_context_options( ibs, aid, refresh_func=refresh_func, with_interact_chip=False, config2_=config2_) qwin = fig.canvas guitool.popup_menu(qwin, qpoint, callback_list) #interact_chip.show_annot_context_menu( # ibs, aid, fig.canvas, qpoint, refresh_func=refresh_func, # with_interact_chip=False, config2_=config2_) else: viztype = vh.get_ibsdat(ax, 'viztype') print('[ic] viztype=%r' % viztype) if viztype == 'chip' and event.key == 'shift': _chip_view(**kwargs) ih.disconnect_callback(fig, 'button_press_event') elif viztype == 'chip': kpts = ibs.get_annot_kpts(aid, config2_=config2_) if len(kpts) > 0: fx = vt.nearest_point( x, y, kpts, conflict_mode='next')[0] print('... clicked fx=%r' % fx) _select_fxth_kpt(fx) else: print('... len(kpts) == 0') elif viztype in ['warped', 'unwarped']: fx = vh.get_ibsdat(ax, 'fx') if fx is not None and viztype == 'warped': viz.show_keypoint_gradient_orientations( ibs, aid, fx, fnum=df2.next_fnum()) else: print('...Unknown viztype: %r' % viztype) viz.draw() # Draw without keypoints the first time if fx is not None: _select_fxth_kpt(fx) else: _chip_view(**kwargs) if dodraw: viz.draw() if not ischild: ih.connect_callback(fig, 'button_press_event', _on_chip_click)
def gridsearch_chipextract(): r""" CommandLine: python -m vtool.chip --test-gridsearch_chipextract --show Example: >>> # GRIDSEARCH >>> from vtool.chip import * # NOQA >>> gridsearch_chipextract() >>> ut.show_if_requested() """ import cv2 test_func = extract_chip_from_img if False: gpath = ut.grab_test_imgpath('carl.jpg') bbox = (100, 3, 100, 100) theta = 0.0 new_size = (58, 34) else: gpath = '/media/raid/work/GZ_Master1/_ibsdb/images/1524525d-2131-8770-d27c-3a5f9922e9e9.jpg' bbox = (450, 373, 2062, 1124) theta = 0.0 old_size = bbox[2:4] #target_area = 700 ** 2 target_area = 1200 ** 2 new_size = get_scaled_sizes_with_area(target_area, [old_size])[0] print('old_size = %r' % (old_size,)) print('new_size = %r' % (new_size,)) #new_size = (677, 369) imgBGR = gtool.imread(gpath) args = (imgBGR, bbox, theta, new_size) param_info = ut.ParamInfoList('extract_params', [ ut.ParamInfo('interpolation', cv2.INTER_LANCZOS4, varyvals=[ cv2.INTER_LANCZOS4, cv2.INTER_CUBIC, cv2.INTER_LINEAR, cv2.INTER_NEAREST, #cv2.INTER_AREA ],) ]) show_func = None # Generalize import plottool as pt pt.imshow(imgBGR) # HACK cfgdict_list, cfglbl_list = param_info.get_gridsearch_input(defaultslice=slice(0, 10)) fnum = pt.ensure_fnum(None) if show_func is None: show_func = pt.imshow lbl = ut.get_funcname(test_func) cfgresult_list = [ test_func(*args, **cfgdict) for cfgdict in ut.ProgressIter(cfgdict_list, lbl=lbl) ] onclick_func = None ut.interact_gridsearch_result_images( show_func, cfgdict_list, cfglbl_list, cfgresult_list, fnum=fnum, figtitle=lbl, unpack=False, max_plots=25, onclick_func=onclick_func) pt.iup()
def show_model(model, evidence={}, soft_evidence={}, **kwargs): """ References: http://stackoverflow.com/questions/22207802/pygraphviz-networkx-set-node-level-or-layer Ignore: pkg-config --libs-only-L libcgraph sudo apt-get install libgraphviz-dev -y sudo apt-get install libgraphviz4 -y # sudo apt-get install pkg-config sudo apt-get install libgraphviz-dev # pip install git+git://github.com/pygraphviz/pygraphviz.git pip install pygraphviz python -c "import pygraphviz; print(pygraphviz.__file__)" sudo pip3 install pygraphviz --install-option="--include-path=/usr/include/graphviz" --install-option="--library-path=/usr/lib/graphviz/" python3 -c "import pygraphviz; print(pygraphviz.__file__)" """ if ut.get_argval('--hackmarkov') or ut.get_argval('--hackjunc'): draw_tree_model(model, **kwargs) return import plottool as pt import networkx as netx import matplotlib as mpl fnum = pt.ensure_fnum(None) fig = pt.figure(fnum=fnum, pnum=(3, 1, (slice(0, 2), 0)), doclf=True) # NOQA #fig = pt.figure(fnum=fnum, pnum=(3, 2, (1, slice(1, 2))), doclf=True) # NOQA ax = pt.gca() var2_post = {f.variables[0]: f for f in kwargs.get('factor_list', [])} netx_graph = (model) #netx_graph.graph.setdefault('graph', {})['size'] = '"10,5"' #netx_graph.graph.setdefault('graph', {})['rankdir'] = 'LR' pos = get_hacked_pos(netx_graph) #netx.pygraphviz_layout(netx_graph) #pos = netx.pydot_layout(netx_graph, prog='dot') #pos = netx.graphviz_layout(netx_graph) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_size=1500) if evidence is not None: node_colors = [ # (pt.TRUE_BLUE (pt.WHITE if node not in soft_evidence else pt.LIGHT_PINK) if node not in evidence else pt.FALSE_RED for node in netx_graph.nodes()] for node in netx_graph.nodes(): cpd = model.var2_cpd[node] if cpd.ttype == 'score': pass drawkw['node_color'] = node_colors netx.draw(netx_graph, **drawkw) show_probs = True if show_probs: textprops = { 'family': 'monospace', 'horizontalalignment': 'left', #'horizontalalignment': 'center', #'size': 12, 'size': 8, } textkw = dict( xycoords='data', boxcoords='offset points', pad=0.25, frameon=True, arrowprops=dict(arrowstyle='->'), #bboxprops=dict(fc=node_attr['fillcolor']), ) netx_nodes = model.nodes(data=True) node_key_list = ut.get_list_column(netx_nodes, 0) pos_list = ut.dict_take(pos, node_key_list) artist_list = [] offset_box_list = [] for pos_, node in zip(pos_list, netx_nodes): x, y = pos_ variable = node[0] cpd = model.var2_cpd[variable] prior_marg = (cpd if cpd.evidence is None else cpd.marginalize(cpd.evidence, inplace=False)) prior_text = None text = None if variable in evidence: text = cpd.variable_statenames[evidence[variable]] elif variable in var2_post: post_marg = var2_post[variable] text = pgm_ext.make_factor_text(post_marg, 'post') prior_text = pgm_ext.make_factor_text(prior_marg, 'prior') else: if len(evidence) == 0 and len(soft_evidence) == 0: prior_text = pgm_ext.make_factor_text(prior_marg, 'prior') show_post = kwargs.get('show_post', False) show_prior = kwargs.get('show_prior', False) show_prior = True show_post = True show_ev = (evidence is not None and variable in evidence) if (show_post or show_ev) and text is not None: offset_box = mpl.offsetbox.TextArea(text, textprops) artist = mpl.offsetbox.AnnotationBbox( # offset_box, (x + 5, y), xybox=(20., 5.), offset_box, (x, y + 5), xybox=(4., 20.), #box_alignment=(0, 0), box_alignment=(.5, 0), **textkw) offset_box_list.append(offset_box) artist_list.append(artist) if show_prior and prior_text is not None: offset_box2 = mpl.offsetbox.TextArea(prior_text, textprops) artist2 = mpl.offsetbox.AnnotationBbox( # offset_box2, (x - 5, y), xybox=(-20., -15.), # offset_box2, (x, y - 5), xybox=(-15., -20.), offset_box2, (x, y - 5), xybox=(-4, -20.), #box_alignment=(1, 1), box_alignment=(.5, 1), **textkw) offset_box_list.append(offset_box2) artist_list.append(artist2) for artist in artist_list: ax.add_artist(artist) xmin, ymin = np.array(pos_list).min(axis=0) xmax, ymax = np.array(pos_list).max(axis=0) num_annots = len(model.ttype2_cpds['name']) if num_annots > 4: ax.set_xlim((xmin - 40, xmax + 40)) ax.set_ylim((ymin - 50, ymax + 50)) fig.set_size_inches(30, 7) else: ax.set_xlim((xmin - 42, xmax + 42)) ax.set_ylim((ymin - 50, ymax + 50)) fig.set_size_inches(23, 7) fig = pt.gcf() title = 'num_names=%r, num_annots=%r' % (model.num_names, num_annots,) map_assign = kwargs.get('map_assign', None) #max_marginal_list = [] #for name, marginal in marginalized_joints.items(): # states = list(ut.iprod(*marginal.statenames)) # vals = marginal.values.ravel() # x = vals.argmax() # max_marginal_list += ['P(' + ', '.join(states[x]) + ') = ' + str(vals[x])] # title += str(marginal) top_assignments = kwargs.get('top_assignments', None) if top_assignments is not None: map_assign, map_prob = top_assignments[0] if map_assign is not None: # title += '\nMAP=' + ut.repr2(map_assign, strvals=True) title += '\nMAP: ' + map_assign + ' @' + '%.2f%%' % (100 * map_prob,) if kwargs.get('show_title', True): pt.set_figtitle(title, size=14) #pt.set_xlabel() def hack_fix_centeralign(): if textprops['horizontalalignment'] == 'center': print('Fixing centeralign') fig = pt.gcf() fig.canvas.draw() # Superhack for centered text. Fix bug in # /usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py # /usr/local/lib/python2.7/dist-packages/matplotlib/text.py for offset_box in offset_box_list: offset_box.set_offset z = offset_box._text.get_window_extent() (z.x1 - z.x0) / 2 offset_box._text T = offset_box._text.get_transform() A = mpl.transforms.Affine2D() A.clear() A.translate((z.x1 - z.x0) / 2, 0) offset_box._text.set_transform(T + A) hack_fix_centeralign() top_assignments = kwargs.get('top_assignments', None) if top_assignments is not None: bin_labels = ut.get_list_column(top_assignments, 0) bin_vals = ut.get_list_column(top_assignments, 1) # bin_labels = ['\n'.join(ut.textwrap.wrap(_lbl, width=30)) for _lbl in bin_labels] pt.draw_histogram(bin_labels, bin_vals, fnum=fnum, pnum=(3, 8, (2, slice(4, None))), transpose=True, use_darkbackground=False, #xtick_rotation=-10, ylabel='Prob', xlabel='assignment') pt.set_title('Assignment probabilities')
def show_multiple_chips(ibs, aid_list, in_image=True, fnum=0, sel_aids=[], subtitle='', annote=False, **kwargs): """ CommandLine: python -m ibeis.viz.viz_name --test-show_multiple_chips --show --no-inimage python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=6435,9861,137,6563,9167,12547,9332,12598,13285 --no-inimage --notitle python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=137,6563,12547,9332,12598,13285 --no-inimage --notitle --adjust=.05 python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=6563,9332,13285,12598 --no-inimage --notitle --adjust=.05 --rc=1,4 python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=1288 --no-inimage --notitle --adjust=.05 python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=4020,4839 --no-inimage --notitle --adjust=.05 python -m ibeis.viz.viz_name --test-show_multiple_chips --db NNP_Master3 --aids=6524,6540,6571,6751 --no-inimage --notitle --adjust=.05 --diskshow python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST -a default:index=0:4 --show --aids=1 --doboth --show --no-inimage python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --show --no-inimage python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --rc=2,1 --show --no-inimage python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --rc=2,1 --show --notitle --trydrawline --no-draw_lbls python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1,2 --doboth --show --notitle --trydrawline python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1,2,3,4,5 --doboth --rc=2,5 --show --chrlbl --trydrawline --qualtitle --no-figtitle --notitle --doboth --doboth --show python -m ibeis.viz.viz_name --test-show_multiple_chips --db NNP_Master3 --aids=15419 --doboth --rc=2,1 --show --notitle --trydrawline --no-draw_lbls Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.viz_name import * # NOQA >>> import ibeis >>> ibs, aid_list, in_image = testdata_multichips() >>> fnum = 0 >>> sel_aids = [] >>> subtitle = '' >>> annote = False >>> fig = show_multiple_chips(ibs, aid_list, in_image, fnum, sel_aids, subtitle, annote) >>> ut.quit_if_noshow() >>> fig.canvas.draw() >>> ut.show_if_requested() """ fnum = pt.ensure_fnum(fnum) nAids = len(aid_list) if nAids == 0: fig = df2.figure(fnum=fnum, pnum=(1, 1, 1), **kwargs) df2.imshow_null(fnum=fnum, **kwargs) return fig # Trigger computation of all chips in parallel ibsfuncs.ensure_annotation_data(ibs, aid_list, chips=(not in_image or annote), feats=annote) print('[viz_name] * annot_vuuid=%r' % ((ibs.get_annot_visual_uuids(aid_list),))) print('[viz_name] * aid_list=%r' % ((aid_list,))) DOBOTH = ut.get_argflag('--doboth') rc = ut.get_argval('--rc', type_=list, default=None) if rc is None: nRows, nCols = ph.get_square_row_cols(nAids * (2 if DOBOTH else 1)) else: nRows, nCols = rc notitle = ut.get_argflag('--notitle') draw_lbls = not ut.get_argflag('--no-draw_lbls') show_chip_kw = dict(annote=annote, in_image=in_image, notitle=notitle, draw_lbls=draw_lbls) #print('[viz_name] * r=%r, c=%r' % (nRows, nCols)) #gs2 = gridspec.GridSpec(nRows, nCols) pnum_ = df2.get_pnum_func(nRows, nCols) fig = df2.figure(fnum=fnum, pnum=pnum_(0), **kwargs) fig.clf() ax_list1 = [] for px, aid in enumerate(aid_list): print('px = %r' % (px,)) _fig, _ax1 = viz_chip.show_chip(ibs, aid=aid, pnum=pnum_(px), **show_chip_kw) print('other_aids = %r' % (ibs.get_annot_contact_aids(aid),)) ax = df2.gca() ax_list1.append(_ax1) if aid in sel_aids: df2.draw_border(ax, df2.GREEN, 4) if ut.get_argflag('--chrlbl') and not DOBOTH: ax.set_xlabel('(' + chr(ord('a') - 1 + px) + ')') elif ut.get_argflag('--numlbl') and not DOBOTH: ax.set_xlabel('(' + str(px + 1) + ')') #plot_aid3(ibs, aid) # HACK to show in image and not in image if DOBOTH: #ut.embed() #ph.get_plotdat_dict(ax_list1[1]) #ph.get_plotdat_dict(ax_list2[1]) ax_list2 = [] show_chip_kw['in_image'] = not show_chip_kw['in_image'] start = px + 1 for px, aid in enumerate(aid_list, start=start): _fig, _ax2 = viz_chip.show_chip(ibs, aid=aid, pnum=pnum_(px), **show_chip_kw) ax = df2.gca() ax_list2.append(_ax2) if ut.get_argflag('--chrlbl'): ax.set_xlabel('(' + chr(ord('a') - start + px) + ')') elif ut.get_argflag('--numlbl'): ax.set_xlabel('(' + str(px - start + 1) + ')') if ut.get_argflag('--qualtitle'): qualtext = ibs.get_annot_quality_texts(aid) ax.set_title(qualtext) if aid in sel_aids: df2.draw_border(ax, df2.GREEN, 4) if in_image: ax_list1, ax_list2 = ax_list2, ax_list1 if ut.get_argflag('--trydrawline'): # Unfinished #ut.embed() # Draw lines between corresponding axes # References: # http://stackoverflow.com/questions/17543359/drawing-lines-between-two-plots-in-matplotlib import matplotlib as mpl import vtool as vt # !!! #http://matplotlib.org/users/transforms_tutorial.html #invTransFigure_fn1 = fig.transFigure.inverted().transform #invTransFigure_fn2 = fig.transFigure.inverted().transform #print(ax_list1) #print(ax_list2) assert len(ax_list1) == len(ax_list2) for ax1, ax2 in zip(ax_list1, ax_list2): #_ = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) #bbox1 = (0, 0, _.width * fig.dpi, _.height * fig.dpi) # returns in figure coordinates #bbox1 = df2.get_axis_bbox(ax=ax1) #if bbox1[-1] < 0: # # Weird bug # bbox1 = bbox1[1] print('--') print('ax1 = %r' % (ax1,)) print('ax2 = %r' % (ax2,)) chipshape = ph.get_plotdat(ax1, 'chipshape') #_bbox1 = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) #bbox1 = (0, 0, _bbox1.width * fig.dpi, _bbox1.height * fig.dpi) bbox1 = (0, 0, chipshape[1], chipshape[0]) aid_ = ph.get_plotdat(ax2, 'aid') aid_list_ = ph.get_plotdat(ax2, 'aid_list') index = aid_list_.index(aid_) annotation_bbox_list = ph.get_plotdat(ax2, 'annotation_bbox_list') bbox2 = annotation_bbox_list[index] print('bbox1 = %r' % (bbox1,)) print('bbox2 = %r' % (bbox2,)) vert_list1 = np.array(vt.verts_from_bbox(bbox1)) vert_list2 = np.array(vt.verts_from_bbox(bbox2)) print('vert_list1 = %r' % (vert_list1,)) print('vert_list2 = %r' % (vert_list2,)) #for vx in [0, 1, 2, 3]: for vx in [0, 1]: vert1 = vert_list1[vx].tolist() vert2 = vert_list2[vx].tolist() print(' ***') print(' * vert1 = %r' % (vert1,)) print(' * vert2 = %r' % (vert2,)) coordsA = coordsB = 'data' #coords = 'axes points' #'axes fraction' #'axes pixels' #coordsA = 'axes pixels' #coordsB = 'data' #'figure fraction' #'figure pixels' #'figure pixels' #'figure points' #'polar' #'offset points' con = mpl.patches.ConnectionPatch( xyA=vert1, xyB=vert2, coordsA=coordsA, coordsB=coordsB, axesA=ax1, axesB=ax2, linewidth=1, color='k') #, arrowstyle="-") #ut.embed() #con.set_zorder(None) ax1.add_artist(con) #ax2.add_artist(con) #ut.embed() #verts2.T[1] -= bbox2[-1] #bottom_left1, bottom_right1 = verts1[1:3].tolist() #bottom_left2, bottom_right2 = verts2[1:3].tolist() ##transAxes1 = ax1.transData.inverted() #transAxes1_fn = ax1.transData.transform #transAxes2_fn = ax2.transData.transform #transAxes1_fn = ut.identity #transAxes2_fn = ut.identity #coord_bl1 = transFigure.transform(transAxes1.transform(bottom_left1)) #coord_br1 = transFigure.transform(transAxes1.transform(bottom_right1)) #coord_bl1 = invTransFigure_fn1(transAxes1_fn(bottom_left1)) #print('bottom_left2 = %r' % (bottom_left2,)) #coord_bl1 = (5, 5) #coord_bl2 = invTransFigure_fn2(transAxes2_fn(bottom_left2)) #print('coord_bl2 = %r' % (coord_bl2,)) #coord_br1 = invTransFigure_fn1(transAxes1_fn(bottom_right1)) #coord_br2 = invTransFigure_fn2(transAxes2_fn(bottom_right2)) ##print('coord_bl1 = %r' % (coord_bl1,)) #line_coords1 = np.vstack([coord_bl1, coord_bl2]) #line_coords2 = np.vstack([coord_br1, coord_br2]) #print('line_coords1 = %r' % (line_coords1,)) #line1 = mpl.lines.Line2D((line_coords1[0]), (line_coords1[1]), transform=fig.transFigure) #line2 = mpl.lines.Line2D((line_coords2[0]), (line_coords2[1]), transform=fig.transFigure) #xs1, ys1 = line_coords1.T #xs2, ys2 = line_coords2.T #linekw = dict(transform=fig.transFigure) #linekw = dict() #print('xs1 = %r' % (xs1,)) #print('ys1 = %r' % (ys1,)) #line1 = mpl.lines.Line2D(xs1, ys1, **linekw) #line2 = mpl.lines.Line2D(xs2, ys2, **linekw) # NOQA #shrinkA=5, shrinkB=5, mutation_scale=20, fc="w") #ax2.add_artist(con) #fig.lines.append(line1) #fig.lines.append(line2) pass return fig
def show_qres(ibs, cm, qreq_=None, **kwargs): """ Display Query Result Logic Defaults to: query chip, groundtruth matches, and top matches Args: ibs (ibeis.IBEISController): ibeis controller object cm (ibeis.ChipMatch): object of feature correspondences and scores Kwargs: in_image (bool) show result in image view if True else chip view annot_mode (int): if annot_mode == 0, then draw lines and ellipse elif annot_mode == 1, then dont draw lines or ellipse elif annot_mode == 2, then draw only lines See: viz_matches.show_name_matches, viz_helpers.get_query_text Returns: mpl.Figure: fig CommandLine: ./main.py --query 1 -y --db PZ_MTEST --noshow-qtres python -m ibeis.viz.viz_qres --test-show_qres --show python -m ibeis.viz.viz_qres --test-show_qres --show --top-aids=10 --db=PZ_MTEST --sidebyside --annot_mode=0 --notitle --no-viz_name_score --qaids=5 --max_nCols=2 --adjust=.01,.01,.01 python -m ibeis.viz.viz_qres --test-show_qres --show --top-aids=10 --db=PZ_MTEST --sidebyside --annot_mode=0 --notitle --no-viz_name_score --qaids=5 --max_nCols=2 --adjust=.01,.01,.01 Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.viz_qres import * # NOQA >>> import plottool as pt >>> ibs, cm, qreq_, kwargs = testdata_show_qres() >>> # execute function >>> fig = show_qres(ibs, cm, show_query=False, qreq_=qreq_, **kwargs) >>> # verify results >>> #fig.show() >>> pt.show_if_requested() """ #ut.print_dict(kwargs) annot_mode = kwargs.get('annot_mode', 1) % 3 # this is toggled figtitle = kwargs.get('figtitle', '') make_figtitle = kwargs.get('make_figtitle', False) aug = kwargs.get('aug', '') top_aids = kwargs.get('top_aids', DEFAULT_NTOP) gt_aids = kwargs.get('gt_aids', []) all_kpts = kwargs.get('all_kpts', False) show_query = kwargs.get('show_query', False) in_image = kwargs.get('in_image', False) sidebyside = kwargs.get('sidebyside', True) #name_scoring = kwargs.get('name_scoring', False) viz_name_score = kwargs.get('viz_name_score', qreq_ is not None) max_nCols = kwargs.get('max_nCols', None) failed_to_match = kwargs.get('failed_to_match', False) fnum = pt.ensure_fnum(kwargs.get('fnum', None)) if ut.VERBOSE and ut.NOT_QUIET: print('query_info = ' + ut.obj_str(ibs.get_annot_info(cm.qaid, default=True, gname=False, name=False, notes=False, exemplar=False), nl=4)) print('top_aids_info = ' + ut.obj_str(ibs.get_annot_info(top_aids, default=True, gname=False, name=False, notes=False, exemplar=False, reference_aid=cm.qaid), nl=4)) if make_figtitle is True: pass #figtitle = cm.make_title(pack=True) #figtitle fig = pt.figure(fnum=fnum, docla=True, doclf=True) if isinstance(top_aids, int): #if isinstance(cm, chip_match.ChipMatch): top_aids = cm.get_top_aids(top_aids) #else: # top_aids = cm.get_top_aids(num=top_aids, name_scoring=name_scoring, ibs=ibs) if failed_to_match: # HACK to visually indicate failure to match in analysis top_aids = [None] + top_aids nTop = len(top_aids) if max_nCols is None: max_nCols = 5 if nTop in [6, 7]: max_nCols = 3 if nTop in [8]: max_nCols = 4 try: assert len(list(set(top_aids).intersection( set(gt_aids)))) == 0, ('gts should be missed. not in top') except AssertionError as ex: ut.printex(ex, keys=['top_aids', 'gt_aids']) raise if ut.DEBUG2: print(cm.get_inspect_str()) #-------------------------------------------------- # Get grid / cell information to build subplot grid #-------------------------------------------------- # Show query or not nQuerySubplts = 1 if show_query else 0 # The top row is given slots for ground truths and querys # all aids in gt_aids should not be in top aids nGtSubplts = nQuerySubplts + (0 if gt_aids is None else len(gt_aids)) # The bottom rows are for the top results nTopNSubplts = nTop nTopNCols = min(max_nCols, nTopNSubplts) nGTCols = min(max_nCols, nGtSubplts) nGTCols = max(nGTCols, nTopNCols) nTopNCols = nGTCols # Get number of rows to show groundtruth nGtRows = 0 if nGTCols == 0 else int(np.ceil(nGtSubplts / nGTCols)) # Get number of rows to show results nTopNRows = 0 if nTopNCols == 0 else int(np.ceil(nTopNSubplts / nTopNCols)) nGtCells = nGtRows * nGTCols # Total number of rows nRows = nTopNRows + nGtRows DEBUG_SHOW_QRES = 0 if DEBUG_SHOW_QRES: allgt_aids = ibs.get_annot_groundtruth(cm.qaid) nSelGt = len(gt_aids) nAllGt = len(allgt_aids) print('[show_qres]========================') print('[show_qres]----------------') print('[show_qres] * annot_mode=%r' % (annot_mode, )) print('[show_qres] #nTop=%r #missed_gts=%r/%r' % (nTop, nSelGt, nAllGt)) print('[show_qres] * -----') print('[show_qres] * nRows=%r' % (nRows, )) print('[show_qres] * nGtSubplts=%r' % (nGtSubplts, )) print('[show_qres] * nTopNSubplts=%r' % (nTopNSubplts, )) print('[show_qres] * nQuerySubplts=%r' % (nQuerySubplts, )) print('[show_qres] * -----') print('[show_qres] * nGTCols=%r' % (nGTCols, )) print('[show_qres] * -----') print('[show_qres] * fnum=%r' % (fnum, )) print('[show_qres] * figtitle=%r' % (figtitle, )) print('[show_qres] * max_nCols=%r' % (max_nCols, )) print('[show_qres] * show_query=%r' % (show_query, )) print('[show_qres] * kwargs=%s' % (ut.dict_str(kwargs), )) # HACK: _color_list = pt.distinct_colors(nTop) aid2_color = {aid: _color_list[ox] for ox, aid in enumerate(top_aids)} ranked_aids = cm.get_top_aids() # Helpers def _show_query_fn(plotx_shift, rowcols): """ helper for show_qres """ plotx = plotx_shift + 1 pnum = (rowcols[0], rowcols[1], plotx) #print('[viz] Plotting Query: pnum=%r' % (pnum,)) _kwshow = dict(draw_kpts=annot_mode) _kwshow.update(kwargs) _kwshow['prefix'] = 'q' _kwshow['pnum'] = pnum _kwshow['aid2_color'] = aid2_color _kwshow['draw_ell'] = annot_mode >= 1 viz_chip.show_chip(ibs, cm.qaid, annote=False, qreq_=qreq_, **_kwshow) def _plot_matches_aids(aid_list, plotx_shift, rowcols): """ helper for show_qres to draw many aids """ _kwshow = dict(draw_ell=annot_mode, draw_pts=False, draw_lines=annot_mode, ell_alpha=.5, all_kpts=all_kpts) _kwshow.update(kwargs) _kwshow['fnum'] = fnum _kwshow['in_image'] = in_image if sidebyside: # Draw each match side by side the query _kwshow['draw_ell'] = annot_mode == 1 _kwshow['draw_lines'] = annot_mode >= 1 else: #print('annot_mode = %r' % (annot_mode,)) _kwshow['draw_ell'] = annot_mode == 1 #_kwshow['draw_pts'] = annot_mode >= 1 #_kwshow['draw_lines'] = False _kwshow['show_query'] = False def _show_matches_fn(aid, orank, pnum): """ Helper function for drawing matches to one aid """ aug = 'rank=%r\n' % orank _kwshow['pnum'] = pnum _kwshow['title_aug'] = aug #draw_ell = annot_mode == 1 #draw_lines = annot_mode >= 1 # If we already are showing the query dont show it here if sidebyside: # Draw each match side by side the query if viz_name_score: cm.show_single_namematch(qreq_, ibs.get_annot_nids(aid), **_kwshow) else: _kwshow['draw_border'] = False _kwshow['draw_lbl'] = False _kwshow['notitle'] = True _kwshow['vert'] = False cm.show_single_annotmatch(qreq_, aid, **_kwshow) #viz_matches.show_matches(ibs, cm, aid, qreq_=qreq_, **_kwshow) else: # Draw each match by themselves data_config2_ = None if qreq_ is None else qreq_.get_external_data_config2( ) #_kwshow['draw_border'] = kwargs.get('draw_border', True) #_kwshow['notitle'] = ut.get_argflag(('--no-title', '--notitle')) viz_chip.show_chip(ibs, aid, annote=False, notitle=True, data_config2_=data_config2_, **_kwshow) if DEBUG_SHOW_QRES: print('[show_qres()] Plotting Chips %s:' % vh.get_aidstrs(aid_list)) if aid_list is None: return # Do lazy load before show #data_config2_ = None if qreq_ is None else qreq_.get_external_data_config2() tblhack = getattr(qreq_, 'tablename', None) # HACK FOR HUMPBACKS # (Also in viz_matches) if tblhack == 'vsone' or (qreq_ is not None and not qreq_._isnewreq): # precompute pass #ibs.get_annot_chips(aid_list, config2_=data_config2_, ensure=True) #ibs.get_annot_kpts(aid_list, config2_=data_config2_, ensure=True) for ox, aid in enumerate(aid_list): plotx = ox + plotx_shift + 1 pnum = (rowcols[0], rowcols[1], plotx) oranks = np.where(ranked_aids == aid)[0] # This pair has no matches between them. if len(oranks) == 0: orank = -1 if aid is None: pt.imshow_null('Failed to find matches\nfor qaid=%r' % (cm.qaid), fnum=fnum, pnum=pnum, fontsize=18) else: _show_matches_fn(aid, orank, pnum) #if DEBUG_SHOW_QRES: # print('skipping pnum=%r' % (pnum,)) continue if DEBUG_SHOW_QRES: print('pnum=%r' % (pnum, )) orank = oranks[0] + 1 _show_matches_fn(aid, orank, pnum) shift_topN = nGtCells if nGtSubplts == 1: nGTCols = 1 if nRows == 0: pt.imshow_null('[viz_qres] No matches. nRows=0', fnum=fnum) else: fig = pt.figure(fnum=fnum, pnum=(nRows, nGTCols, 1), docla=True, doclf=True) pt.plt.subplot(nRows, nGTCols, 1) # Plot Query if show_query: _show_query_fn(0, (nRows, nGTCols)) # Plot Ground Truth (if given) _plot_matches_aids(gt_aids, nQuerySubplts, (nRows, nGTCols)) # Plot Results _plot_matches_aids(top_aids, shift_topN, (nRows, nTopNCols)) figtitle += aug if failed_to_match: figtitle += '\n No matches found' incanvas = kwargs.get('with_figtitle', not vh.NO_LBL_OVERRIDE) pt.set_figtitle(figtitle, incanvas=incanvas) # Result Interaction return fig
def show_model(model, evidence={}, soft_evidence={}, **kwargs): """ References: http://stackoverflow.com/questions/22207802/pygraphviz-networkx-set-node-level-or-layer Ignore: pkg-config --libs-only-L libcgraph sudo apt-get install libgraphviz-dev -y sudo apt-get install libgraphviz4 -y # sudo apt-get install pkg-config sudo apt-get install libgraphviz-dev # pip install git+git://github.com/pygraphviz/pygraphviz.git pip install pygraphviz python -c "import pygraphviz; print(pygraphviz.__file__)" sudo pip3 install pygraphviz --install-option="--include-path=/usr/include/graphviz" --install-option="--library-path=/usr/lib/graphviz/" python3 -c "import pygraphviz; print(pygraphviz.__file__)" """ if ut.get_argval('--hackmarkov') or ut.get_argval('--hackjunc'): draw_tree_model(model, **kwargs) return import plottool as pt import networkx as netx import matplotlib as mpl fnum = pt.ensure_fnum(None) fig = pt.figure(fnum=fnum, pnum=(3, 1, (slice(0, 2), 0)), doclf=True) # NOQA #fig = pt.figure(fnum=fnum, pnum=(3, 2, (1, slice(1, 2))), doclf=True) # NOQA ax = pt.gca() var2_post = {f.variables[0]: f for f in kwargs.get('factor_list', [])} netx_graph = (model) #netx_graph.graph.setdefault('graph', {})['size'] = '"10,5"' #netx_graph.graph.setdefault('graph', {})['rankdir'] = 'LR' pos = get_hacked_pos(netx_graph) #netx.nx_agraph.pygraphviz_layout(netx_graph) #pos = netx.nx_agraph.pydot_layout(netx_graph, prog='dot') #pos = netx.nx_agraph.graphviz_layout(netx_graph) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_size=1500) if evidence is not None: node_colors = [ # (pt.TRUE_BLUE (pt.WHITE if node not in soft_evidence else pt.LIGHT_PINK) if node not in evidence else pt.FALSE_RED for node in netx_graph.nodes() ] for node in netx_graph.nodes(): cpd = model.var2_cpd[node] if cpd.ttype == 'score': pass drawkw['node_color'] = node_colors netx.draw(netx_graph, **drawkw) show_probs = True if show_probs: textprops = { 'family': 'monospace', 'horizontalalignment': 'left', #'horizontalalignment': 'center', #'size': 12, 'size': 8, } textkw = dict( xycoords='data', boxcoords='offset points', pad=0.25, framewidth=True, arrowprops=dict(arrowstyle='->'), #bboxprops=dict(fc=node_attr['fillcolor']), ) netx_nodes = model.nodes(data=True) node_key_list = ut.get_list_column(netx_nodes, 0) pos_list = ut.dict_take(pos, node_key_list) artist_list = [] offset_box_list = [] for pos_, node in zip(pos_list, netx_nodes): x, y = pos_ variable = node[0] cpd = model.var2_cpd[variable] prior_marg = (cpd if cpd.evidence is None else cpd.marginalize( cpd.evidence, inplace=False)) prior_text = None text = None if variable in evidence: text = cpd.variable_statenames[evidence[variable]] elif variable in var2_post: post_marg = var2_post[variable] text = pgm_ext.make_factor_text(post_marg, 'post') prior_text = pgm_ext.make_factor_text(prior_marg, 'prior') else: if len(evidence) == 0 and len(soft_evidence) == 0: prior_text = pgm_ext.make_factor_text(prior_marg, 'prior') show_post = kwargs.get('show_post', False) show_prior = kwargs.get('show_prior', False) show_prior = True show_post = True show_ev = (evidence is not None and variable in evidence) if (show_post or show_ev) and text is not None: offset_box = mpl.offsetbox.TextArea(text, textprops) artist = mpl.offsetbox.AnnotationBbox( # offset_box, (x + 5, y), xybox=(20., 5.), offset_box, (x, y + 5), xybox=(4., 20.), #box_alignment=(0, 0), box_alignment=(.5, 0), **textkw) offset_box_list.append(offset_box) artist_list.append(artist) if show_prior and prior_text is not None: offset_box2 = mpl.offsetbox.TextArea(prior_text, textprops) artist2 = mpl.offsetbox.AnnotationBbox( # offset_box2, (x - 5, y), xybox=(-20., -15.), # offset_box2, (x, y - 5), xybox=(-15., -20.), offset_box2, (x, y - 5), xybox=(-4, -20.), #box_alignment=(1, 1), box_alignment=(.5, 1), **textkw) offset_box_list.append(offset_box2) artist_list.append(artist2) for artist in artist_list: ax.add_artist(artist) xmin, ymin = np.array(pos_list).min(axis=0) xmax, ymax = np.array(pos_list).max(axis=0) num_annots = len(model.ttype2_cpds['name']) if num_annots > 4: ax.set_xlim((xmin - 40, xmax + 40)) ax.set_ylim((ymin - 50, ymax + 50)) fig.set_size_inches(30, 7) else: ax.set_xlim((xmin - 42, xmax + 42)) ax.set_ylim((ymin - 50, ymax + 50)) fig.set_size_inches(23, 7) fig = pt.gcf() title = 'num_names=%r, num_annots=%r' % ( model.num_names, num_annots, ) map_assign = kwargs.get('map_assign', None) #max_marginal_list = [] #for name, marginal in marginalized_joints.items(): # states = list(ut.iprod(*marginal.statenames)) # vals = marginal.values.ravel() # x = vals.argmax() # max_marginal_list += ['P(' + ', '.join(states[x]) + ') = ' + str(vals[x])] # title += str(marginal) top_assignments = kwargs.get('top_assignments', None) if top_assignments is not None: map_assign, map_prob = top_assignments[0] if map_assign is not None: # title += '\nMAP=' + ut.repr2(map_assign, strvals=True) title += '\nMAP: ' + map_assign + ' @' + '%.2f%%' % ( 100 * map_prob, ) if kwargs.get('show_title', True): pt.set_figtitle(title, size=14) #pt.set_xlabel() def hack_fix_centeralign(): if textprops['horizontalalignment'] == 'center': print('Fixing centeralign') fig = pt.gcf() fig.canvas.draw() # Superhack for centered text. Fix bug in # /usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py # /usr/local/lib/python2.7/dist-packages/matplotlib/text.py for offset_box in offset_box_list: offset_box.set_offset z = offset_box._text.get_window_extent() (z.x1 - z.x0) / 2 offset_box._text T = offset_box._text.get_transform() A = mpl.transforms.Affine2D() A.clear() A.translate((z.x1 - z.x0) / 2, 0) offset_box._text.set_transform(T + A) hack_fix_centeralign() top_assignments = kwargs.get('top_assignments', None) if top_assignments is not None: bin_labels = ut.get_list_column(top_assignments, 0) bin_vals = ut.get_list_column(top_assignments, 1) # bin_labels = ['\n'.join(ut.textwrap.wrap(_lbl, width=30)) for _lbl in bin_labels] pt.draw_histogram( bin_labels, bin_vals, fnum=fnum, pnum=(3, 8, (2, slice(4, None))), transpose=True, use_darkbackground=False, #xtick_rotation=-10, ylabel='Prob', xlabel='assignment') pt.set_title('Assignment probabilities')
def show_qres(ibs, cm, qreq_=None, **kwargs): """ Display Query Result Logic Defaults to: query chip, groundtruth matches, and top matches Args: ibs (ibeis.IBEISController): ibeis controller object cm (ibeis.ChipMatch): object of feature correspondences and scores Kwargs: in_image (bool) show result in image view if True else chip view annot_mode (int): if annot_mode == 0, then draw lines and ellipse elif annot_mode == 1, then dont draw lines or ellipse elif annot_mode == 2, then draw only lines See: viz_matches.show_name_matches, viz_helpers.get_query_text Returns: mpl.Figure: fig CommandLine: ./main.py --query 1 -y --db PZ_MTEST --noshow-qtres python -m ibeis.viz.viz_qres --test-show_qres --show python -m ibeis.viz.viz_qres --test-show_qres --show --top-aids=10 --db=PZ_MTEST --sidebyside --annot_mode=0 --notitle --no-viz_name_score --qaids=5 --max_nCols=2 --adjust=.01,.01,.01 python -m ibeis.viz.viz_qres --test-show_qres --show --top-aids=10 --db=PZ_MTEST --sidebyside --annot_mode=0 --notitle --no-viz_name_score --qaids=5 --max_nCols=2 --adjust=.01,.01,.01 Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.viz_qres import * # NOQA >>> import plottool as pt >>> ibs, cm, qreq_, kwargs = testdata_show_qres() >>> # execute function >>> fig = show_qres(ibs, cm, show_query=False, qreq_=qreq_, **kwargs) >>> # verify results >>> #fig.show() >>> pt.show_if_requested() """ #ut.print_dict(kwargs) annot_mode = kwargs.get('annot_mode', 1) % 3 # this is toggled figtitle = kwargs.get('figtitle', '') make_figtitle = kwargs.get('make_figtitle', False) aug = kwargs.get('aug', '') top_aids = kwargs.get('top_aids', DEFAULT_NTOP) gt_aids = kwargs.get('gt_aids', []) all_kpts = kwargs.get('all_kpts', False) show_query = kwargs.get('show_query', False) in_image = kwargs.get('in_image', False) sidebyside = kwargs.get('sidebyside', True) #name_scoring = kwargs.get('name_scoring', False) viz_name_score = kwargs.get('viz_name_score', qreq_ is not None) max_nCols = kwargs.get('max_nCols', None) failed_to_match = kwargs.get('failed_to_match', False) fnum = pt.ensure_fnum(kwargs.get('fnum', None)) if ut.VERBOSE and ut.NOT_QUIET: print('query_info = ' + ut.obj_str( ibs.get_annot_info(cm.qaid, default=True, gname=False, name=False, notes=False, exemplar=False), nl=4)) print('top_aids_info = ' + ut.obj_str( ibs.get_annot_info(top_aids, default=True, gname=False, name=False, notes=False, exemplar=False, reference_aid=cm.qaid), nl=4)) if make_figtitle is True: pass #figtitle = cm.make_title(pack=True) #figtitle fig = pt.figure(fnum=fnum, docla=True, doclf=True) if isinstance(top_aids, int): #if isinstance(cm, chip_match.ChipMatch): top_aids = cm.get_top_aids(top_aids) #else: # top_aids = cm.get_top_aids(num=top_aids, name_scoring=name_scoring, ibs=ibs) if failed_to_match: # HACK to visually indicate failure to match in analysis top_aids = [None] + top_aids nTop = len(top_aids) if max_nCols is None: max_nCols = 5 if nTop in [6, 7]: max_nCols = 3 if nTop in [8]: max_nCols = 4 try: assert len(list(set(top_aids).intersection(set(gt_aids)))) == 0, ( 'gts should be missed. not in top') except AssertionError as ex: ut.printex(ex, keys=['top_aids', 'gt_aids']) raise if ut.DEBUG2: print(cm.get_inspect_str()) #-------------------------------------------------- # Get grid / cell information to build subplot grid #-------------------------------------------------- # Show query or not nQuerySubplts = 1 if show_query else 0 # The top row is given slots for ground truths and querys # all aids in gt_aids should not be in top aids nGtSubplts = nQuerySubplts + (0 if gt_aids is None else len(gt_aids)) # The bottom rows are for the top results nTopNSubplts = nTop nTopNCols = min(max_nCols, nTopNSubplts) nGTCols = min(max_nCols, nGtSubplts) nGTCols = max(nGTCols, nTopNCols) nTopNCols = nGTCols # Get number of rows to show groundtruth nGtRows = 0 if nGTCols == 0 else int(np.ceil(nGtSubplts / nGTCols)) # Get number of rows to show results nTopNRows = 0 if nTopNCols == 0 else int(np.ceil(nTopNSubplts / nTopNCols)) nGtCells = nGtRows * nGTCols # Total number of rows nRows = nTopNRows + nGtRows DEBUG_SHOW_QRES = 0 if DEBUG_SHOW_QRES: allgt_aids = ibs.get_annot_groundtruth(cm.qaid) nSelGt = len(gt_aids) nAllGt = len(allgt_aids) print('[show_qres]========================') print('[show_qres]----------------') print('[show_qres] * annot_mode=%r' % (annot_mode,)) print('[show_qres] #nTop=%r #missed_gts=%r/%r' % (nTop, nSelGt, nAllGt)) print('[show_qres] * -----') print('[show_qres] * nRows=%r' % (nRows,)) print('[show_qres] * nGtSubplts=%r' % (nGtSubplts,)) print('[show_qres] * nTopNSubplts=%r' % (nTopNSubplts,)) print('[show_qres] * nQuerySubplts=%r' % (nQuerySubplts,)) print('[show_qres] * -----') print('[show_qres] * nGTCols=%r' % (nGTCols,)) print('[show_qres] * -----') print('[show_qres] * fnum=%r' % (fnum,)) print('[show_qres] * figtitle=%r' % (figtitle,)) print('[show_qres] * max_nCols=%r' % (max_nCols,)) print('[show_qres] * show_query=%r' % (show_query,)) print('[show_qres] * kwargs=%s' % (ut.dict_str(kwargs),)) # HACK: _color_list = pt.distinct_colors(nTop) aid2_color = {aid: _color_list[ox] for ox, aid in enumerate(top_aids)} ranked_aids = cm.get_top_aids() # Helpers def _show_query_fn(plotx_shift, rowcols): """ helper for show_qres """ plotx = plotx_shift + 1 pnum = (rowcols[0], rowcols[1], plotx) #print('[viz] Plotting Query: pnum=%r' % (pnum,)) _kwshow = dict(draw_kpts=annot_mode) _kwshow.update(kwargs) _kwshow['prefix'] = 'q' _kwshow['pnum'] = pnum _kwshow['aid2_color'] = aid2_color _kwshow['draw_ell'] = annot_mode >= 1 viz_chip.show_chip(ibs, cm.qaid, annote=False, qreq_=qreq_, **_kwshow) def _plot_matches_aids(aid_list, plotx_shift, rowcols): """ helper for show_qres to draw many aids """ _kwshow = dict(draw_ell=annot_mode, draw_pts=False, draw_lines=annot_mode, ell_alpha=.5, all_kpts=all_kpts) _kwshow.update(kwargs) _kwshow['fnum'] = fnum _kwshow['in_image'] = in_image if sidebyside: # Draw each match side by side the query _kwshow['draw_ell'] = annot_mode == 1 _kwshow['draw_lines'] = annot_mode >= 1 else: #print('annot_mode = %r' % (annot_mode,)) _kwshow['draw_ell'] = annot_mode == 1 #_kwshow['draw_pts'] = annot_mode >= 1 #_kwshow['draw_lines'] = False _kwshow['show_query'] = False def _show_matches_fn(aid, orank, pnum): """ Helper function for drawing matches to one aid """ aug = 'rank=%r\n' % orank _kwshow['pnum'] = pnum _kwshow['title_aug'] = aug #draw_ell = annot_mode == 1 #draw_lines = annot_mode >= 1 # If we already are showing the query dont show it here if sidebyside: # Draw each match side by side the query if viz_name_score: cm.show_single_namematch(qreq_, ibs.get_annot_nids(aid), **_kwshow) else: _kwshow['draw_border'] = False _kwshow['draw_lbl'] = False _kwshow['notitle'] = True _kwshow['vert'] = False cm.show_single_annotmatch(qreq_, aid, **_kwshow) #viz_matches.show_matches(ibs, cm, aid, qreq_=qreq_, **_kwshow) else: # Draw each match by themselves data_config2_ = None if qreq_ is None else qreq_.get_external_data_config2() #_kwshow['draw_border'] = kwargs.get('draw_border', True) #_kwshow['notitle'] = ut.get_argflag(('--no-title', '--notitle')) viz_chip.show_chip(ibs, aid, annote=False, notitle=True, data_config2_=data_config2_, **_kwshow) if DEBUG_SHOW_QRES: print('[show_qres()] Plotting Chips %s:' % vh.get_aidstrs(aid_list)) if aid_list is None: return # Do lazy load before show #data_config2_ = None if qreq_ is None else qreq_.get_external_data_config2() tblhack = getattr(qreq_, 'tablename', None) # HACK FOR HUMPBACKS # (Also in viz_matches) if tblhack == 'vsone' or (qreq_ is not None and not qreq_._isnewreq): # precompute pass #ibs.get_annot_chips(aid_list, config2_=data_config2_, ensure=True) #ibs.get_annot_kpts(aid_list, config2_=data_config2_, ensure=True) for ox, aid in enumerate(aid_list): plotx = ox + plotx_shift + 1 pnum = (rowcols[0], rowcols[1], plotx) oranks = np.where(ranked_aids == aid)[0] # This pair has no matches between them. if len(oranks) == 0: orank = -1 if aid is None: pt.imshow_null('Failed to find matches\nfor qaid=%r' % (cm.qaid), fnum=fnum, pnum=pnum, fontsize=18) else: _show_matches_fn(aid, orank, pnum) #if DEBUG_SHOW_QRES: # print('skipping pnum=%r' % (pnum,)) continue if DEBUG_SHOW_QRES: print('pnum=%r' % (pnum,)) orank = oranks[0] + 1 _show_matches_fn(aid, orank, pnum) shift_topN = nGtCells if nGtSubplts == 1: nGTCols = 1 if nRows == 0: pt.imshow_null('[viz_qres] No matches. nRows=0', fnum=fnum) else: fig = pt.figure(fnum=fnum, pnum=(nRows, nGTCols, 1), docla=True, doclf=True) pt.plt.subplot(nRows, nGTCols, 1) # Plot Query if show_query: _show_query_fn(0, (nRows, nGTCols)) # Plot Ground Truth (if given) _plot_matches_aids(gt_aids, nQuerySubplts, (nRows, nGTCols)) # Plot Results _plot_matches_aids(top_aids, shift_topN, (nRows, nTopNCols)) figtitle += aug if failed_to_match: figtitle += '\n No matches found' incanvas = kwargs.get('with_figtitle', not vh.NO_LBL_OVERRIDE) pt.set_figtitle(figtitle, incanvas=incanvas) # Result Interaction return fig
def hackshow_names(ibs, aid_list, fnum=None): r""" Args: ibs (IBEISController): ibeis controller object aid_list (list): CommandLine: python -m ibeis.other.dbinfo --exec-hackshow_names --show python -m ibeis.other.dbinfo --exec-hackshow_names --show --db PZ_Master1 Example: >>> # DISABLE_DOCTEST >>> from ibeis.other.dbinfo import * # NOQA >>> import ibeis >>> ibs = ibeis.opendb(defaultdb='PZ_MTEST') >>> aid_list = ibs.get_valid_aids() >>> result = hackshow_names(ibs, aid_list) >>> print(result) >>> ut.show_if_requested() """ import plottool as pt import vtool as vt grouped_aids, nid_list = ibs.group_annots_by_name(aid_list) grouped_aids = [aids for aids in grouped_aids if len(aids) > 1] unixtimes_list = ibs.unflat_map(ibs.get_annot_image_unixtimes_asfloat, grouped_aids) yaws_list = ibs.unflat_map(ibs.get_annot_yaws, grouped_aids) #markers_list = [[(1, 2, yaw * 360 / (np.pi * 2)) for yaw in yaws] for yaws in yaws_list] unixtime_list = ut.flatten(unixtimes_list) timemax = np.nanmax(unixtime_list) timemin = np.nanmin(unixtime_list) timerange = timemax - timemin unixtimes_list = [((unixtimes[:] - timemin) / timerange) for unixtimes in unixtimes_list] for unixtimes in unixtimes_list: num_nan = sum(np.isnan(unixtimes)) unixtimes[np.isnan(unixtimes)] = np.linspace(-1, -.5, num_nan) #ydata_list = [np.arange(len(aids)) for aids in grouped_aids] sortx_list = vt.argsort_groups(unixtimes_list, reverse=False) #markers_list = ut.list_ziptake(markers_list, sortx_list) yaws_list = ut.list_ziptake(yaws_list, sortx_list) ydatas_list = vt.ziptake(unixtimes_list, sortx_list) #ydatas_list = sortx_list #ydatas_list = vt.argsort_groups(unixtimes_list, reverse=False) # Sort by num members #ydatas_list = ut.take(ydatas_list, np.argsort(list(map(len, ydatas_list)))) xdatas_list = [np.zeros(len(ydatas)) + count for count, ydatas in enumerate(ydatas_list)] #markers = ut.flatten(markers_list) #yaws = np.array(ut.flatten(yaws_list)) y_data = np.array(ut.flatten(ydatas_list)) x_data = np.array(ut.flatten(xdatas_list)) fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum) ax = pt.gca() #unique_yaws, groupxs = vt.group_indices(yaws) ax.scatter(x_data, y_data, color=[1, 0, 0], s=1, marker='.') #pt.draw_stems(x_data, y_data, marker=markers, setlims=True, linestyle='') pt.dark_background() ax = pt.gca() ax.set_xlim(min(x_data) - .1, max(x_data) + .1) ax.set_ylim(min(y_data) - .1, max(y_data) + .1)
def show_model(model, evidence={}, soft_evidence={}, **kwargs): """ References: http://stackoverflow.com/questions/22207802/pygraphviz-networkx-set-node-level-or-layer Ignore: pkg-config --libs-only-L libcgraph sudo apt-get install libgraphviz-dev -y sudo apt-get install libgraphviz4 -y # sudo apt-get install pkg-config sudo apt-get install libgraphviz-dev # pip install git+git://github.com/pygraphviz/pygraphviz.git pip install pygraphviz python -c "import pygraphviz; print(pygraphviz.__file__)" sudo pip3 install pygraphviz --install-option="--include-path=/usr/include/graphviz" --install-option="--library-path=/usr/lib/graphviz/" python3 -c "import pygraphviz; print(pygraphviz.__file__)" CommandLine: python -m ibeis.algo.hots.bayes --exec-show_model --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.algo.hots.bayes import * # NOQA >>> model = '?' >>> evidence = {} >>> soft_evidence = {} >>> result = show_model(model, evidence, soft_evidence) >>> print(result) >>> ut.quit_if_noshow() >>> import plottool as pt >>> ut.show_if_requested() """ if ut.get_argval('--hackmarkov') or ut.get_argval('--hackjunc'): draw_tree_model(model, **kwargs) return import plottool as pt import networkx as netx fnum = pt.ensure_fnum(None) netx_graph = (model) #netx_graph.graph.setdefault('graph', {})['size'] = '"10,5"' #netx_graph.graph.setdefault('graph', {})['rankdir'] = 'LR' pos_dict = get_hacked_pos(netx_graph) #pos_dict = netx.pygraphviz_layout(netx_graph) #pos = netx.pydot_layout(netx_graph, prog='dot') #pos_dict = netx.graphviz_layout(netx_graph) textprops = { 'family': 'monospace', 'horizontalalignment': 'left', #'horizontalalignment': 'center', #'size': 12, 'size': 8, } netx_nodes = model.nodes(data=True) node_key_list = ut.get_list_column(netx_nodes, 0) pos_list = ut.dict_take(pos_dict, node_key_list) var2_post = {f.variables[0]: f for f in kwargs.get('factor_list', [])} prior_text = None post_text = None evidence_tas = [] post_tas = [] prior_tas = [] node_color = [] has_infered = evidence or var2_post if has_infered: ignore_prior_with_ttype = ['score', 'match'] show_prior = False else: ignore_prior_with_ttype = [] #show_prior = True show_prior = False dpy = 5 dbx, dby = (20, 20) takw1 = {'bbox_align': (.5, 0), 'pos_offset': [0, dpy], 'bbox_offset': [dbx, dby]} takw2 = {'bbox_align': (.5, 1), 'pos_offset': [0, -dpy], 'bbox_offset': [-dbx, -dby]} name_colors = pt.distinct_colors(max(model.num_names, 10)) name_colors = name_colors[:model.num_names] #cmap_ = 'hot' #mx = 0.65 #mn = 0.15 cmap_, mn, mx = 'plasma', 0.15, 1.0 _cmap = pt.plt.get_cmap(cmap_) def cmap(x): return _cmap((x * mx) + mn) for node, pos in zip(netx_nodes, pos_list): variable = node[0] cpd = model.var2_cpd[variable] prior_marg = (cpd if cpd.evidence is None else cpd.marginalize(cpd.evidence, inplace=False)) show_evidence = variable in evidence show_prior = cpd.ttype not in ignore_prior_with_ttype show_post = variable in var2_post show_prior |= cpd.ttype not in ignore_prior_with_ttype post_marg = None if show_post: post_marg = var2_post[variable] def get_name_color(phi): order = phi.values.argsort()[::-1] if len(order) < 2: dist_next = phi.values[order[0]] else: dist_next = phi.values[order[0]] - phi.values[order[1]] dist_total = (phi.values[order[0]]) confidence = (dist_total * dist_next) ** (2.5 / 4) #print('confidence = %r' % (confidence,)) color = name_colors[order[0]] color = pt.color_funcs.desaturate_rgb(color, 1 - confidence) color = np.array(color) return color if variable in evidence: if cpd.ttype == 'score': cmap_index = evidence[variable] / (cpd.variable_card - 1) color = cmap(cmap_index) color = pt.lighten_rgb(color, .4) color = np.array(color) node_color.append(color) elif cpd.ttype == 'name': color = name_colors[evidence[variable]] color = np.array(color) node_color.append(color) else: color = pt.FALSE_RED node_color.append(color) #elif variable in soft_evidence: # color = pt.LIGHT_PINK # show_prior = True # color = get_name_color(prior_marg) # node_color.append(color) else: if cpd.ttype == 'name' and post_marg is not None: color = get_name_color(post_marg) node_color.append(color) elif cpd.ttype == 'match' and post_marg is not None: color = cmap(post_marg.values[1]) color = pt.lighten_rgb(color, .4) color = np.array(color) node_color.append(color) else: #color = pt.WHITE color = pt.NEUTRAL node_color.append(color) if show_prior: if variable in soft_evidence: prior_color = pt.LIGHT_PINK else: prior_color = None prior_text = pgm_ext.make_factor_text(prior_marg, 'prior') prior_tas.append(dict(text=prior_text, pos=pos, color=prior_color, **takw2)) if show_evidence: _takw1 = takw1 if cpd.ttype == 'score': _takw1 = takw2 evidence_text = cpd.variable_statenames[evidence[variable]] if isinstance(evidence_text, int): evidence_text = '%d/%d' % (evidence_text + 1, cpd.variable_card) evidence_tas.append(dict(text=evidence_text, pos=pos, color=color, **_takw1)) if show_post: _takw1 = takw1 if cpd.ttype == 'match': _takw1 = takw2 post_text = pgm_ext.make_factor_text(post_marg, 'post') post_tas.append(dict(text=post_text, pos=pos, color=None, **_takw1)) def trnps_(dict_list): """ tranpose dict list """ list_dict = ut.ddict(list) for dict_ in dict_list: for key, val in dict_.items(): list_dict[key + '_list'].append(val) return list_dict takw1_ = trnps_(post_tas + evidence_tas) takw2_ = trnps_(prior_tas) # Draw graph if has_infered: pnum1 = (3, 1, (slice(0, 2), 0)) else: pnum1 = None fig = pt.figure(fnum=fnum, pnum=pnum1, doclf=True) # NOQA ax = pt.gca() #print('node_color = %s' % (ut.repr3(node_color),)) drawkw = dict(pos=pos_dict, ax=ax, with_labels=True, node_size=1500, node_color=node_color) netx.draw(netx_graph, **drawkw) hacks = [] if len(post_tas + evidence_tas): hacks.append(pt.draw_text_annotations(textprops=textprops, **takw1_)) if prior_tas: hacks.append(pt.draw_text_annotations(textprops=textprops, **takw2_)) xmin, ymin = np.array(pos_list).min(axis=0) xmax, ymax = np.array(pos_list).max(axis=0) num_annots = len(model.ttype2_cpds['name']) if num_annots > 4: ax.set_xlim((xmin - 40, xmax + 40)) ax.set_ylim((ymin - 50, ymax + 50)) fig.set_size_inches(30, 7) else: ax.set_xlim((xmin - 42, xmax + 42)) ax.set_ylim((ymin - 50, ymax + 50)) fig.set_size_inches(23, 7) fig = pt.gcf() title = 'num_names=%r, num_annots=%r' % (model.num_names, num_annots,) map_assign = kwargs.get('map_assign', None) top_assignments = kwargs.get('top_assignments', None) if top_assignments is not None: map_assign, map_prob = top_assignments[0] if map_assign is not None: def word_insert(text): return '' if len(text) == 0 else text + ' ' title += '\n%sMAP: ' % (word_insert(kwargs.get('method', ''))) title += map_assign + ' @' + '%.2f%%' % (100 * map_prob,) if kwargs.get('show_title', True): pt.set_figtitle(title, size=14) for hack in hacks: hack() # Hack in colorbars if has_infered: pt.colorbar(np.linspace(0, 1, len(name_colors)), name_colors, lbl='name', ticklabels=model.ttype2_template['name'].basis, ticklocation='left') basis = model.ttype2_template['score'].basis scalars = np.linspace(0, 1, len(basis)) scalars = np.linspace(0, 1, 100) colors = pt.scores_to_color(scalars, cmap_=cmap_, reverse_cmap=False, cmap_range=(mn, mx)) colors = [pt.lighten_rgb(c, .4) for c in colors] if ut.list_type(basis) is int: pt.colorbar(scalars, colors, lbl='score', ticklabels=np.array(basis) + 1) else: pt.colorbar(scalars, colors, lbl='score', ticklabels=basis) #print('basis = %r' % (basis,)) # Draw probability hist if has_infered and top_assignments is not None: bin_labels = ut.get_list_column(top_assignments, 0) bin_vals = ut.get_list_column(top_assignments, 1) # bin_labels = ['\n'.join(ut.textwrap.wrap(_lbl, width=30)) for _lbl in bin_labels] pt.draw_histogram(bin_labels, bin_vals, fnum=fnum, pnum=(3, 8, (2, slice(4, None))), transpose=True, use_darkbackground=False, #xtick_rotation=-10, ylabel='Prob', xlabel='assignment') pt.set_title('Assignment probabilities')
def __init__(self, ibs, cm, aid2=None, fnum=None, figtitle='Match Interaction', same_fig=True, qreq_=None, **kwargs): self.qres = cm self.ibs = ibs self.cm = cm self.qreq_ = qreq_ self.fnum = pt.ensure_fnum(fnum) # Unpack Args if aid2 is None: index = 0 # FIXME: no sortself cm.sortself() self.rank = index else: index = cm.daid2_idx.get(aid2, None) # TODO: rank? self.rank = None if index is not None: self.qaid = self.cm.qaid self.daid = self.cm.daid_list[index] self.fm = self.cm.fm_list[index] self.fk = self.cm.fk_list[index] self.fsv = self.cm.fsv_list[index] if self.cm.fs_list is None: fs_list = self.cm.get_fsv_prod_list() else: fs_list = self.cm.fs_list self.fs = None if fs_list is None else fs_list[index] self.score = None if self.cm.score_list is None else self.cm.score_list[ index] self.H1 = None if self.cm.H_list is None else cm.H_list[index] else: self.qaid = self.cm.qaid self.daid = aid2 self.fm = np.empty((0, 2), dtype=hstypes.FM_DTYPE) self.fk = np.empty(0, dtype=hstypes.FK_DTYPE) self.fsv = np.empty((0, 2), dtype=hstypes.FS_DTYPE) self.fs = np.empty(0, dtype=hstypes.FS_DTYPE) self.score = None self.H1 = None # Read properties self.query_config2_ = (None if self.qreq_ is None else self.qreq_.get_external_query_config2()) self.data_config2_ = (None if self.qreq_ is None else self.qreq_.get_external_data_config2()) self.rchip1 = vh.get_chips(ibs, [self.qaid], config2_=self.query_config2_)[0] self.rchip2 = vh.get_chips(ibs, [self.daid], config2_=self.data_config2_)[0] # Begin Interaction # call doclf docla and make figure self.fig = ih.begin_interaction('matches', self.fnum) self.xywh2_ptr = [None] self.mode = kwargs.pop('mode', 0) # New state vars self.same_fig = same_fig self.use_homog = False self.vert = kwargs.pop('vert', None) self.mx = kwargs.pop('mx', None) self.last_fx = 0 self.fnum2 = pt.next_fnum() self.figtitle = figtitle self.kwargs = kwargs abstract_interaction.register_interaction(self) ut.inject_func_as_method(self, AbstractInteraction.append_button.im_func) ut.inject_func_as_method(self, AbstractInteraction.show_popup_menu.im_func) self.scope = [] if not kwargs.get('nobegin', False): dodraw = kwargs.get('dodraw', True) self.begin(dodraw=dodraw)
def show_multiple_chips(ibs, aid_list, in_image=True, fnum=0, sel_aids=[], subtitle='', annote=False, **kwargs): """ CommandLine: python -m ibeis.viz.viz_name --test-show_multiple_chips --show --no-inimage python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=6435,9861,137,6563,9167,12547,9332,12598,13285 --no-inimage --notitle python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=137,6563,12547,9332,12598,13285 --no-inimage --notitle --adjust=.05 python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db NNP_Master3 --aids=6563,9332,13285,12598 --no-inimage --notitle --adjust=.05 --rc=1,4 python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=1288 --no-inimage --notitle --adjust=.05 python -m ibeis.viz.viz_name --test-show_multiple_chips --show --db PZ_Master0 --aids=4020,4839 --no-inimage --notitle --adjust=.05 python -m ibeis.viz.viz_name --test-show_multiple_chips --db NNP_Master3 --aids=6524,6540,6571,6751 --no-inimage --notitle --adjust=.05 --diskshow python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST -a default:index=0:4 --show --aids=1 --doboth --show --no-inimage python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --show --no-inimage python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --rc=2,1 --show --no-inimage python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1 --doboth --rc=2,1 --show --notitle --trydrawline --no-draw_lbls python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1,2 --doboth --show --notitle --trydrawline python -m ibeis.viz.viz_name --test-show_multiple_chips --db PZ_MTEST --aids=1,2,3,4,5 --doboth --rc=2,5 --show --chrlbl --trydrawline --qualtitle --no-figtitle --notitle --doboth --doboth --show python -m ibeis.viz.viz_name --test-show_multiple_chips --db NNP_Master3 --aids=15419 --doboth --rc=2,1 --show --notitle --trydrawline --no-draw_lbls Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.viz_name import * # NOQA >>> import ibeis >>> ibs, aid_list, in_image = testdata_multichips() >>> if True: >>> import matplotlib as mpl >>> from ibeis.scripts.thesis import TMP_RC >>> mpl.rcParams.update(TMP_RC) >>> fnum = 0 >>> sel_aids = [] >>> subtitle = '' >>> annote = False >>> fig = show_multiple_chips(ibs, aid_list, in_image, fnum, sel_aids, subtitle, annote) >>> ut.quit_if_noshow() >>> fig.canvas.draw() >>> ut.show_if_requested() """ fnum = pt.ensure_fnum(fnum) nAids = len(aid_list) if nAids == 0: fig = df2.figure(fnum=fnum, pnum=(1, 1, 1), **kwargs) df2.imshow_null(fnum=fnum, **kwargs) return fig # Trigger computation of all chips in parallel ibsfuncs.ensure_annotation_data(ibs, aid_list, chips=(not in_image or annote), feats=annote) print('[viz_name] * annot_vuuid=%r' % ((ibs.get_annot_visual_uuids(aid_list), ))) print('[viz_name] * aid_list=%r' % ((aid_list, ))) DOBOTH = ut.get_argflag('--doboth') rc = ut.get_argval('--rc', type_=list, default=None) if rc is None: nRows, nCols = ph.get_square_row_cols(nAids * (2 if DOBOTH else 1)) else: nRows, nCols = rc notitle = ut.get_argflag('--notitle') draw_lbls = not ut.get_argflag('--no-draw_lbls') show_chip_kw = dict(annote=annote, in_image=in_image, notitle=notitle, draw_lbls=draw_lbls) #print('[viz_name] * r=%r, c=%r' % (nRows, nCols)) #gs2 = gridspec.GridSpec(nRows, nCols) pnum_ = df2.get_pnum_func(nRows, nCols) fig = df2.figure(fnum=fnum, pnum=pnum_(0), **kwargs) fig.clf() ax_list1 = [] for px, aid in enumerate(aid_list): print('px = %r' % (px, )) _fig, _ax1 = viz_chip.show_chip(ibs, aid=aid, pnum=pnum_(px), **show_chip_kw) print('other_aids = %r' % (ibs.get_annot_contact_aids(aid), )) ax = df2.gca() ax_list1.append(_ax1) if aid in sel_aids: df2.draw_border(ax, df2.GREEN, 4) if ut.get_argflag('--chrlbl') and not DOBOTH: ax.set_xlabel('(' + chr(ord('a') - 1 + px) + ')') elif ut.get_argflag('--numlbl') and not DOBOTH: ax.set_xlabel('(' + str(px + 1) + ')') #plot_aid3(ibs, aid) # HACK to show in image and not in image if DOBOTH: #ut.embed() #ph.get_plotdat_dict(ax_list1[1]) #ph.get_plotdat_dict(ax_list2[1]) ax_list2 = [] show_chip_kw['in_image'] = not show_chip_kw['in_image'] start = px + 1 for px, aid in enumerate(aid_list, start=start): _fig, _ax2 = viz_chip.show_chip(ibs, aid=aid, pnum=pnum_(px), **show_chip_kw) ax = df2.gca() ax_list2.append(_ax2) if ut.get_argflag('--chrlbl'): ax.set_xlabel('(' + chr(ord('a') - start + px) + ')') elif ut.get_argflag('--numlbl'): ax.set_xlabel('(' + str(px - start + 1) + ')') if ut.get_argflag('--qualtitle'): qualtext = ibs.get_annot_quality_texts(aid) ax.set_title(qualtext) if aid in sel_aids: df2.draw_border(ax, df2.GREEN, 4) if in_image: ax_list1, ax_list2 = ax_list2, ax_list1 if ut.get_argflag('--trydrawline'): # Unfinished #ut.embed() # Draw lines between corresponding axes # References: # http://stackoverflow.com/questions/17543359/drawing-lines-between-two-plots-in-matplotlib import matplotlib as mpl import vtool as vt # !!! #http://matplotlib.org/users/transforms_tutorial.html #invTransFigure_fn1 = fig.transFigure.inverted().transform #invTransFigure_fn2 = fig.transFigure.inverted().transform #print(ax_list1) #print(ax_list2) assert len(ax_list1) == len(ax_list2) for ax1, ax2 in zip(ax_list1, ax_list2): #_ = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) #bbox1 = (0, 0, _.width * fig.dpi, _.height * fig.dpi) # returns in figure coordinates #bbox1 = df2.get_axis_bbox(ax=ax1) #if bbox1[-1] < 0: # # Weird bug # bbox1 = bbox1[1] print('--') print('ax1 = %r' % (ax1, )) print('ax2 = %r' % (ax2, )) chipshape = ph.get_plotdat(ax1, 'chipshape') #_bbox1 = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) #bbox1 = (0, 0, _bbox1.width * fig.dpi, _bbox1.height * fig.dpi) bbox1 = (0, 0, chipshape[1], chipshape[0]) aid_ = ph.get_plotdat(ax2, 'aid') aid_list_ = ph.get_plotdat(ax2, 'aid_list') index = aid_list_.index(aid_) annotation_bbox_list = ph.get_plotdat(ax2, 'annotation_bbox_list') bbox2 = annotation_bbox_list[index] print('bbox1 = %r' % (bbox1, )) print('bbox2 = %r' % (bbox2, )) vert_list1 = np.array(vt.verts_from_bbox(bbox1)) vert_list2 = np.array(vt.verts_from_bbox(bbox2)) print('vert_list1 = %r' % (vert_list1, )) print('vert_list2 = %r' % (vert_list2, )) #for vx in [0, 1, 2, 3]: for vx in [0, 1]: vert1 = vert_list1[vx].tolist() vert2 = vert_list2[vx].tolist() print(' ***') print(' * vert1 = %r' % (vert1, )) print(' * vert2 = %r' % (vert2, )) coordsA = coordsB = 'data' #coords = 'axes points' #'axes fraction' #'axes pixels' #coordsA = 'axes pixels' #coordsB = 'data' #'figure fraction' #'figure pixels' #'figure pixels' #'figure points' #'polar' #'offset points' con = mpl.patches.ConnectionPatch(xyA=vert1, xyB=vert2, coordsA=coordsA, coordsB=coordsB, axesA=ax1, axesB=ax2, linewidth=1, color='k') #, arrowstyle="-") #ut.embed() #con.set_zorder(None) ax1.add_artist(con) #ax2.add_artist(con) #ut.embed() #verts2.T[1] -= bbox2[-1] #bottom_left1, bottom_right1 = verts1[1:3].tolist() #bottom_left2, bottom_right2 = verts2[1:3].tolist() ##transAxes1 = ax1.transData.inverted() #transAxes1_fn = ax1.transData.transform #transAxes2_fn = ax2.transData.transform #transAxes1_fn = ut.identity #transAxes2_fn = ut.identity #coord_bl1 = transFigure.transform(transAxes1.transform(bottom_left1)) #coord_br1 = transFigure.transform(transAxes1.transform(bottom_right1)) #coord_bl1 = invTransFigure_fn1(transAxes1_fn(bottom_left1)) #print('bottom_left2 = %r' % (bottom_left2,)) #coord_bl1 = (5, 5) #coord_bl2 = invTransFigure_fn2(transAxes2_fn(bottom_left2)) #print('coord_bl2 = %r' % (coord_bl2,)) #coord_br1 = invTransFigure_fn1(transAxes1_fn(bottom_right1)) #coord_br2 = invTransFigure_fn2(transAxes2_fn(bottom_right2)) ##print('coord_bl1 = %r' % (coord_bl1,)) #line_coords1 = np.vstack([coord_bl1, coord_bl2]) #line_coords2 = np.vstack([coord_br1, coord_br2]) #print('line_coords1 = %r' % (line_coords1,)) #line1 = mpl.lines.Line2D((line_coords1[0]), (line_coords1[1]), transform=fig.transFigure) #line2 = mpl.lines.Line2D((line_coords2[0]), (line_coords2[1]), transform=fig.transFigure) #xs1, ys1 = line_coords1.T #xs2, ys2 = line_coords2.T #linekw = dict(transform=fig.transFigure) #linekw = dict() #print('xs1 = %r' % (xs1,)) #print('ys1 = %r' % (ys1,)) #line1 = mpl.lines.Line2D(xs1, ys1, **linekw) #line2 = mpl.lines.Line2D(xs2, ys2, **linekw) # NOQA #shrinkA=5, shrinkB=5, mutation_scale=20, fc="w") #ax2.add_artist(con) #fig.lines.append(line1) #fig.lines.append(line2) pass return fig
def draw_markov_model(model, fnum=None, **kwargs): import plottool as pt fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum, doclf=True) ax = pt.gca() from pgmpy.models import MarkovModel if isinstance(model, MarkovModel): markovmodel = model else: markovmodel = model.to_markov_model() # pos = nx.nx_agraph.pydot_layout(markovmodel) pos = nx.nx_agraph.pygraphviz_layout(markovmodel) # Referenecs: # https://groups.google.com/forum/#!topic/networkx-discuss/FwYk0ixLDuY # pos = nx.spring_layout(markovmodel) # pos = nx.circular_layout(markovmodel) # curved-arrow # markovmodel.edge_attr['curved-arrow'] = True # markovmodel.graph.setdefault('edge', {})['splines'] = 'curved' # markovmodel.graph.setdefault('graph', {})['splines'] = 'curved' # markovmodel.graph.setdefault('edge', {})['splines'] = 'curved' node_color = [pt.NEUTRAL] * len(pos) drawkw = dict( pos=pos, ax=ax, with_labels=True, node_color=node_color, # NOQA node_size=1100) from matplotlib.patches import FancyArrowPatch, Circle import numpy as np def draw_network(G, pos, ax, sg=None): for n in G: c = Circle(pos[n], radius=10, alpha=0.5, color=pt.NEUTRAL_BLUE) ax.add_patch(c) G.node[n]['patch'] = c x, y = pos[n] pt.ax_absolute_text(x, y, n, ha='center', va='center') seen = {} for (u, v, d) in G.edges(data=True): n1 = G.node[u]['patch'] n2 = G.node[v]['patch'] rad = 0.1 if (u, v) in seen: rad = seen.get((u, v)) rad = (rad + np.sign(rad) * 0.1) * -1 alpha = 0.5 color = 'k' e = FancyArrowPatch( n1.center, n2.center, patchA=n1, patchB=n2, # arrowstyle='-|>', arrowstyle='-', connectionstyle='arc3,rad=%s' % rad, mutation_scale=10.0, lw=2, alpha=alpha, color=color) seen[(u, v)] = rad ax.add_patch(e) return e # nx.draw(markovmodel, **drawkw) draw_network(markovmodel, pos, ax) ax.autoscale() pt.plt.axis('equal') pt.plt.axis('off') if kwargs.get('show_title', True): pt.set_figtitle('Markov Model')
def gridsearch_chipextract(): r""" CommandLine: python -m vtool.chip --test-gridsearch_chipextract --show Example: >>> # GRIDSEARCH >>> from vtool.chip import * # NOQA >>> gridsearch_chipextract() >>> ut.show_if_requested() """ import cv2 test_func = extract_chip_from_img if False: gpath = ut.grab_test_imgpath('carl.jpg') bbox = (100, 3, 100, 100) theta = 0.0 new_size = (58, 34) else: gpath = '/media/raid/work/GZ_Master1/_ibsdb/images/1524525d-2131-8770-d27c-3a5f9922e9e9.jpg' bbox = (450, 373, 2062, 1124) theta = 0.0 old_size = bbox[2:4] #target_area = 700 ** 2 target_area = 1200**2 new_size = get_scaled_sizes_with_area(target_area, [old_size])[0] print('old_size = %r' % (old_size, )) print('new_size = %r' % (new_size, )) #new_size = (677, 369) imgBGR = gtool.imread(gpath) args = (imgBGR, bbox, theta, new_size) param_info = ut.ParamInfoList( 'extract_params', [ ut.ParamInfo( 'interpolation', cv2.INTER_LANCZOS4, varyvals=[ cv2.INTER_LANCZOS4, cv2.INTER_CUBIC, cv2.INTER_LINEAR, cv2.INTER_NEAREST, #cv2.INTER_AREA ], ) ]) show_func = None # Generalize import plottool as pt pt.imshow(imgBGR) # HACK cfgdict_list, cfglbl_list = param_info.get_gridsearch_input( defaultslice=slice(0, 10)) fnum = pt.ensure_fnum(None) if show_func is None: show_func = pt.imshow lbl = ut.get_funcname(test_func) cfgresult_list = [ test_func(*args, **cfgdict) for cfgdict in ut.ProgressIter(cfgdict_list, lbl=lbl) ] onclick_func = None ut.interact_gridsearch_result_images(show_func, cfgdict_list, cfglbl_list, cfgresult_list, fnum=fnum, figtitle=lbl, unpack=False, max_plots=25, onclick_func=onclick_func) pt.iup()
def show_nx(graph, with_labels=True, fnum=None, pnum=None, layout='agraph', ax=None, pos=None, img_dict=None, title=None, layoutkw=None, verbose=None, **kwargs): r""" Args: graph (networkx.Graph): with_labels (bool): (default = True) node_size (int): (default = 1100) fnum (int): figure number(default = None) pnum (tuple): plot number(default = None) CommandLine: python -m plottool.nx_helpers --exec-show_nx --show python -m dtool --tf DependencyCache.make_graph --show python -m ibeis.scripts.specialdraw double_depcache_graph --show --testmode python -m vtool.clustering2 unsupervised_multicut_labeling --show Example: >>> # DISABLE_DOCTEST >>> from plottool.nx_helpers import * # NOQA >>> import networkx as nx >>> graph = nx.DiGraph() >>> graph.add_nodes_from(['a', 'b', 'c', 'd']) >>> graph.add_edges_from({'a': 'b', 'b': 'c', 'b': 'd', 'c': 'd'}.items()) >>> nx.set_node_attributes(graph, 'shape', 'rect') >>> nx.set_node_attributes(graph, 'image', {'a': ut.grab_test_imgpath('carl.jpg')}) >>> nx.set_node_attributes(graph, 'image', {'d': ut.grab_test_imgpath('lena.png')}) >>> #nx.set_node_attributes(graph, 'height', 100) >>> with_labels = True >>> fnum = None >>> pnum = None >>> e = show_nx(graph, with_labels, fnum, pnum, layout='agraph') >>> ut.show_if_requested() """ import plottool as pt import networkx as nx if ax is None: fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum, pnum=pnum) ax = pt.gca() if img_dict is None: img_dict = nx.get_node_attributes(graph, 'image') if verbose is None: verbose = ut.VERBOSE use_image = kwargs.get('use_image', True) if verbose: print('Getting layout') layout_info = get_nx_layout(graph, layout, layoutkw=layoutkw, verbose=verbose) if verbose: print('Drawing graph') # zoom = kwargs.pop('zoom', .4) framewidth = kwargs.pop('framewidth', 1.0) patch_dict = draw_network2(graph, layout_info, ax, verbose=verbose, **kwargs) layout_info.update(patch_dict) if kwargs.get('modify_ax', True): ax.grid(False) pt.plt.axis('equal') ax.axesPatch.set_facecolor('white') ax.autoscale() ax.autoscale_view(True, True, True) #axes.facecolor node_size = layout_info['node']['size'] node_pos = layout_info['node']['pos'] if node_size is not None: half_size_arr = np.array(ut.take(node_size, graph.nodes())) / 2. pos_arr = np.array(ut.take(node_pos, graph.nodes())) # autoscale does not seem to work #ul_pos = pos_arr - half_size_arr #br_pos = pos_arr + half_size_arr # hack because edges are cut off. # need to take into account extent of edges as well ul_pos = pos_arr - half_size_arr * 1.5 br_pos = pos_arr + half_size_arr * 1.5 xmin, ymin = ul_pos.min(axis=0) xmax, ymax = br_pos.max(axis=0) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) #pt.plt.axis('off') ax.set_xticks([]) ax.set_yticks([]) if use_image and img_dict is not None and len(img_dict) > 0: if verbose: print('Drawing images') node_list = sorted(img_dict.keys()) pos_list = ut.dict_take(node_pos, node_list) img_list = ut.dict_take(img_dict, node_list) size_list = ut.dict_take(node_size, node_list) #color_list = ut.dict_take(nx.get_node_attributes(graph, 'color'), node_list, None) color_list = ut.dict_take(nx.get_node_attributes(graph, 'framecolor'), node_list, None) framewidth_list = ut.dict_take(nx.get_node_attributes(graph, 'framewidth'), node_list, framewidth) # TODO; frames without images imgdat = pt.netx_draw_images_at_positions(img_list, pos_list, size_list, color_list, framewidth_list=framewidth_list) imgdat['node_list'] = node_list layout_info['imgdat'] = imgdat else: if verbose: print('Not drawing images') if title is not None: pt.set_title(title) return layout_info
def __init__(self, ibs, cm, aid2=None, fnum=None, figtitle='Match Interaction', same_fig=True, qreq_=None, **kwargs): self.qres = cm self.ibs = ibs self.cm = cm self.qreq_ = qreq_ self.fnum = pt.ensure_fnum(fnum) # Unpack Args if aid2 is None: index = 0 # FIXME: no sortself cm.sortself() self.rank = index else: index = cm.daid2_idx.get(aid2, None) # TODO: rank? self.rank = None if index is not None: self.qaid = self.cm.qaid self.daid = self.cm.daid_list[index] self.fm = self.cm.fm_list[index] self.fk = self.cm.fk_list[index] self.fsv = self.cm.fsv_list[index] if self.cm.fs_list is None: fs_list = self.cm.get_fsv_prod_list() else: fs_list = self.cm.fs_list self.fs = None if fs_list is None else fs_list[index] self.score = None if self.cm.score_list is None else self.cm.score_list[index] self.H1 = None if self.cm.H_list is None else cm.H_list[index] else: self.qaid = self.cm.qaid self.daid = aid2 self.fm = np.empty((0, 2), dtype=hstypes.FM_DTYPE) self.fk = np.empty(0, dtype=hstypes.FK_DTYPE) self.fsv = np.empty((0, 2), dtype=hstypes.FS_DTYPE) self.fs = np.empty(0, dtype=hstypes.FS_DTYPE) self.score = None self.H1 = None # Read properties self.query_config2_ = (None if self.qreq_ is None else self.qreq_.get_external_query_config2()) self.data_config2_ = (None if self.qreq_ is None else self.qreq_.get_external_data_config2()) self.rchip1 = vh.get_chips(ibs, [self.qaid], config2_=self.query_config2_)[0] self.rchip2 = vh.get_chips(ibs, [self.daid], config2_=self.data_config2_)[0] # Begin Interaction # call doclf docla and make figure self.fig = ih.begin_interaction('matches', self.fnum) self.xywh2_ptr = [None] self.mode = kwargs.pop('mode', 0) # New state vars self.same_fig = same_fig self.use_homog = False self.vert = kwargs.pop('vert', None) self.mx = kwargs.pop('mx', None) self.last_fx = 0 self.fnum2 = pt.next_fnum() self.figtitle = figtitle self.kwargs = kwargs abstract_interaction.register_interaction(self) ut.inject_func_as_method(self, AbstractInteraction.append_button.im_func) ut.inject_func_as_method(self, AbstractInteraction.show_popup_menu.im_func) self.scope = [] if not kwargs.get('nobegin', False): dodraw = kwargs.get('dodraw', True) self.begin(dodraw=dodraw)
def show_augmented_patches(Xb, Xb_, yb, yb_, data_per_label=1, shadows=None): """ from ibeis_cnn.augment import * # NOQA std_ = center_std mean_ = center_mean """ import plottool as pt import vtool as vt Xb_old = vt.rectify_to_float01(Xb) Xb_new = vt.rectify_to_float01(Xb_) # only look at ones that were actually augmented sample1 = Xb_old[0::data_per_label] sample2 = Xb_new[0::data_per_label] diff = np.abs((sample1 - sample2)) diff_batches = diff.sum(-1).sum(-1).sum(-1) > 0 modified_indexes = np.where(diff_batches > 0)[0] print('modified_indexes = %r' % (modified_indexes,)) #modified_indexes = np.arange(num_examples) Xb_old = vt.rectify_to_uint8(Xb_old) Xb_new = vt.rectify_to_uint8(Xb_new) # Group data into n-tuples grouped_idxs = [np.arange(n, len(Xb_), data_per_label) for n in range(data_per_label)] data_lists_old = vt.apply_grouping(Xb_old, grouped_idxs, axis=0) data_lists_new = vt.apply_grouping(Xb_new, grouped_idxs, axis=0) import six #chunck_sizes = (4, 10) import utool with utool.embed_on_exception_context: chunk_sizes = pt.get_square_row_cols(len(modified_indexes), max_cols=10, fix=False, inclusive=False) _iter = ut.iter_multichunks(modified_indexes, chunk_sizes) multiindices = six.next(_iter) from ibeis_cnn import draw_results tup = draw_results.get_patch_multichunks(data_lists_old, yb, {}, multiindices) orig_stack = tup[0] #stacked_img, stacked_offsets, stacked_sfs = tup tup = draw_results.get_patch_multichunks(data_lists_new, yb_, {}, multiindices) warp_stack = tup[0] #stacked_img, stacked_offsets, stacked_sfs = tup #orig_stack = stacked_img_pairs(Xb_old, modified_indexes, yb) #warp_stack = stacked_img_pairs(Xb_new, modified_indexes, yb_) if shadows is not None: # hack shadow_stack = stacked_img_pairs(shadows, modified_indexes, yb_) fnum = None fnum = pt.ensure_fnum(fnum) pt.figure(fnum) #next_pnum = pt.make_pnum_nextgen(nRows=2 + (shadows is not None), nCols=1) next_pnum = pt.make_pnum_nextgen(nCols=2 + (shadows is not None), nRows=1) pt.imshow(orig_stack, pnum=next_pnum(), title='before') pt.imshow(warp_stack, pnum=next_pnum(), title='after') if shadows is not None: pt.imshow(shadow_stack, pnum=next_pnum(), title='shadow_stack')
def viz_netx_chipgraph(ibs, graph, fnum=None, use_image=False, layout=None, zoom=None, prog='neato', as_directed=False, augment_graph=True, layoutkw=None, framewidth=3.0, **kwargs): r""" DEPRICATE or improve Args: ibs (IBEISController): ibeis controller object graph (nx.DiGraph): fnum (int): figure number(default = None) use_image (bool): (default = False) zoom (float): (default = 0.4) Returns: ?: pos CommandLine: python -m ibeis --tf viz_netx_chipgraph --show Cand: ibeis review_tagged_joins --save figures4/mergecase.png --figsize=15,15 --clipwhite --diskshow ibeis compute_occurrence_groups --save figures4/occurgraph.png --figsize=40,40 --clipwhite --diskshow ~/code/ibeis/ibeis/algo/preproc/preproc_occurrence.py Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.viz_graph import * # NOQA >>> import ibeis >>> ibs = ibeis.opendb(defaultdb='PZ_MTEST') >>> nid_list = ibs.get_valid_nids()[0:10] >>> fnum = None >>> use_image = True >>> zoom = 0.4 >>> make_name_graph_interaction(ibs, nid_list, prog='neato') >>> ut.show_if_requested() """ import plottool as pt print('[viz_graph] drawing chip graph') fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum, pnum=(1, 1, 1)) ax = pt.gca() if layout is None: layout = 'agraph' print('layout = %r' % (layout,)) if use_image: ensure_node_images(ibs, graph) nx.set_node_attributes(graph, 'shape', 'rect') if layoutkw is None: layoutkw = {} layoutkw['prog'] = layoutkw.get('prog', prog) layoutkw.update(kwargs) if prog == 'neato': graph = graph.to_undirected() plotinfo = pt.show_nx(graph, ax=ax, # img_dict=img_dict, layout=layout, # hacknonode=bool(use_image), layoutkw=layoutkw, as_directed=as_directed, framewidth=framewidth, ) return plotinfo
def viz_netx_chipgraph(ibs, graph, fnum=None, use_image=False, layout=None, zoom=None, prog='neato', as_directed=False, augment_graph=True, layoutkw=None, framewidth=3.0, **kwargs): r""" DEPRICATE or improve Args: ibs (IBEISController): ibeis controller object graph (nx.DiGraph): fnum (int): figure number(default = None) use_image (bool): (default = False) zoom (float): (default = 0.4) Returns: ?: pos CommandLine: python -m ibeis --tf viz_netx_chipgraph --show Cand: ibeis review_tagged_joins --save figures4/mergecase.png --figsize=15,15 --clipwhite --diskshow ibeis compute_occurrence_groups --save figures4/occurgraph.png --figsize=40,40 --clipwhite --diskshow ~/code/ibeis/ibeis/algo/preproc/preproc_occurrence.py Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.viz_graph import * # NOQA >>> import ibeis >>> ibs = ibeis.opendb(defaultdb='PZ_MTEST') >>> nid_list = ibs.get_valid_nids()[0:10] >>> fnum = None >>> use_image = True >>> zoom = 0.4 >>> make_name_graph_interaction(ibs, nid_list, prog='neato') >>> ut.show_if_requested() """ import plottool as pt print('[viz_graph] drawing chip graph') fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum, pnum=(1, 1, 1)) ax = pt.gca() if layout is None: layout = 'agraph' print('layout = %r' % (layout, )) if use_image: ensure_node_images(ibs, graph) nx.set_node_attributes(graph, 'shape', 'rect') if layoutkw is None: layoutkw = {} layoutkw['prog'] = layoutkw.get('prog', prog) layoutkw.update(kwargs) if prog == 'neato': graph = graph.to_undirected() plotinfo = pt.show_nx( graph, ax=ax, # img_dict=img_dict, layout=layout, # hacknonode=bool(use_image), layoutkw=layoutkw, as_directed=as_directed, framewidth=framewidth, ) return plotinfo
def show_model(model, evidence={}, soft_evidence={}, **kwargs): """ References: http://stackoverflow.com/questions/22207802/pygraphviz-networkx-set-node-level-or-layer Ignore: pkg-config --libs-only-L libcgraph sudo apt-get install libgraphviz-dev -y sudo apt-get install libgraphviz4 -y # sudo apt-get install pkg-config sudo apt-get install libgraphviz-dev # pip install git+git://github.com/pygraphviz/pygraphviz.git pip install pygraphviz python -c "import pygraphviz; print(pygraphviz.__file__)" sudo pip3 install pygraphviz --install-option="--include-path=/usr/include/graphviz" --install-option="--library-path=/usr/lib/graphviz/" python3 -c "import pygraphviz; print(pygraphviz.__file__)" CommandLine: python -m ibeis.algo.hots.bayes --exec-show_model --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.algo.hots.bayes import * # NOQA >>> model = '?' >>> evidence = {} >>> soft_evidence = {} >>> result = show_model(model, evidence, soft_evidence) >>> print(result) >>> ut.quit_if_noshow() >>> import plottool as pt >>> ut.show_if_requested() """ if ut.get_argval('--hackmarkov') or ut.get_argval('--hackjunc'): draw_tree_model(model, **kwargs) return import plottool as pt import networkx as netx fnum = pt.ensure_fnum(None) netx_graph = (model) #netx_graph.graph.setdefault('graph', {})['size'] = '"10,5"' #netx_graph.graph.setdefault('graph', {})['rankdir'] = 'LR' pos_dict = get_hacked_pos(netx_graph) #pos_dict = netx.nx_agraph.pygraphviz_layout(netx_graph) #pos = netx.nx_agraph.nx_pydot.pydot_layout(netx_graph, prog='dot') #pos_dict = netx.nx_agraph.graphviz_layout(netx_graph) textprops = { 'family': 'monospace', 'horizontalalignment': 'left', #'horizontalalignment': 'center', #'size': 12, 'size': 8, } netx_nodes = model.nodes(data=True) node_key_list = ut.get_list_column(netx_nodes, 0) pos_list = ut.dict_take(pos_dict, node_key_list) var2_post = {f.variables[0]: f for f in kwargs.get('factor_list', [])} prior_text = None post_text = None evidence_tas = [] post_tas = [] prior_tas = [] node_color = [] has_inferred = evidence or var2_post if has_inferred: ignore_prior_with_ttype = [SCORE_TTYPE, MATCH_TTYPE] show_prior = False else: ignore_prior_with_ttype = [] #show_prior = True show_prior = False dpy = 5 dbx, dby = (20, 20) takw1 = { 'bbox_align': (.5, 0), 'pos_offset': [0, dpy], 'bbox_offset': [dbx, dby] } takw2 = { 'bbox_align': (.5, 1), 'pos_offset': [0, -dpy], 'bbox_offset': [-dbx, -dby] } name_colors = pt.distinct_colors(max(model.num_names, 10)) name_colors = name_colors[:model.num_names] #cmap_ = 'hot' #mx = 0.65 #mn = 0.15 cmap_, mn, mx = 'plasma', 0.15, 1.0 _cmap = pt.plt.get_cmap(cmap_) def cmap(x): return _cmap((x * mx) + mn) for node, pos in zip(netx_nodes, pos_list): variable = node[0] cpd = model.var2_cpd[variable] prior_marg = (cpd if cpd.evidence is None else cpd.marginalize( cpd.evidence, inplace=False)) show_evidence = variable in evidence show_prior = cpd.ttype not in ignore_prior_with_ttype show_post = variable in var2_post show_prior |= cpd.ttype not in ignore_prior_with_ttype post_marg = None if show_post: post_marg = var2_post[variable] def get_name_color(phi): order = phi.values.argsort()[::-1] if len(order) < 2: dist_next = phi.values[order[0]] else: dist_next = phi.values[order[0]] - phi.values[order[1]] dist_total = (phi.values[order[0]]) confidence = (dist_total * dist_next)**(2.5 / 4) #print('confidence = %r' % (confidence,)) color = name_colors[order[0]] color = pt.color_funcs.desaturate_rgb(color, 1 - confidence) color = np.array(color) return color if variable in evidence: if cpd.ttype == SCORE_TTYPE: cmap_index = evidence[variable] / (cpd.variable_card - 1) color = cmap(cmap_index) color = pt.lighten_rgb(color, .4) color = np.array(color) node_color.append(color) elif cpd.ttype == NAME_TTYPE: color = name_colors[evidence[variable]] color = np.array(color) node_color.append(color) else: color = pt.FALSE_RED node_color.append(color) #elif variable in soft_evidence: # color = pt.LIGHT_PINK # show_prior = True # color = get_name_color(prior_marg) # node_color.append(color) else: if cpd.ttype == NAME_TTYPE and post_marg is not None: color = get_name_color(post_marg) node_color.append(color) elif cpd.ttype == MATCH_TTYPE and post_marg is not None: color = cmap(post_marg.values[1]) color = pt.lighten_rgb(color, .4) color = np.array(color) node_color.append(color) else: #color = pt.WHITE color = pt.NEUTRAL node_color.append(color) if show_prior: if variable in soft_evidence: prior_color = pt.LIGHT_PINK else: prior_color = None prior_text = pgm_ext.make_factor_text(prior_marg, 'prior') prior_tas.append( dict(text=prior_text, pos=pos, color=prior_color, **takw2)) if show_evidence: _takw1 = takw1 if cpd.ttype == SCORE_TTYPE: _takw1 = takw2 evidence_text = cpd.variable_statenames[evidence[variable]] if isinstance(evidence_text, int): evidence_text = '%d/%d' % (evidence_text + 1, cpd.variable_card) evidence_tas.append( dict(text=evidence_text, pos=pos, color=color, **_takw1)) if show_post: _takw1 = takw1 if cpd.ttype == MATCH_TTYPE: _takw1 = takw2 post_text = pgm_ext.make_factor_text(post_marg, 'post') post_tas.append(dict(text=post_text, pos=pos, color=None, **_takw1)) def trnps_(dict_list): """ tranpose dict list """ list_dict = ut.ddict(list) for dict_ in dict_list: for key, val in dict_.items(): list_dict[key + '_list'].append(val) return list_dict takw1_ = trnps_(post_tas + evidence_tas) takw2_ = trnps_(prior_tas) # Draw graph if has_inferred: pnum1 = (3, 1, (slice(0, 2), 0)) else: pnum1 = None fig = pt.figure(fnum=fnum, pnum=pnum1, doclf=True) # NOQA ax = pt.gca() #print('node_color = %s' % (ut.repr3(node_color),)) drawkw = dict(pos=pos_dict, ax=ax, with_labels=True, node_size=1500, node_color=node_color) netx.draw(netx_graph, **drawkw) hacks = [] if len(post_tas + evidence_tas): hacks.append(pt.draw_text_annotations(textprops=textprops, **takw1_)) if prior_tas: hacks.append(pt.draw_text_annotations(textprops=textprops, **takw2_)) xmin, ymin = np.array(pos_list).min(axis=0) xmax, ymax = np.array(pos_list).max(axis=0) num_annots = len(model.ttype2_cpds[NAME_TTYPE]) if num_annots > 4: ax.set_xlim((xmin - 40, xmax + 40)) ax.set_ylim((ymin - 50, ymax + 50)) fig.set_size_inches(30, 7) else: ax.set_xlim((xmin - 42, xmax + 42)) ax.set_ylim((ymin - 50, ymax + 50)) fig.set_size_inches(23, 7) fig = pt.gcf() title = 'num_names=%r, num_annots=%r' % ( model.num_names, num_annots, ) map_assign = kwargs.get('map_assign', None) top_assignments = kwargs.get('top_assignments', None) if top_assignments is not None: map_assign, map_prob = top_assignments[0] if map_assign is not None: def word_insert(text): return '' if len(text) == 0 else text + ' ' title += '\n%sMAP: ' % (word_insert(kwargs.get('method', ''))) title += map_assign + ' @' + '%.2f%%' % (100 * map_prob, ) if kwargs.get('show_title', True): pt.set_figtitle(title, size=14) for hack in hacks: hack() # Hack in colorbars if has_inferred: pt.colorbar(np.linspace(0, 1, len(name_colors)), name_colors, lbl=NAME_TTYPE, ticklabels=model.ttype2_template[NAME_TTYPE].basis, ticklocation='left') basis = model.ttype2_template[SCORE_TTYPE].basis scalars = np.linspace(0, 1, len(basis)) scalars = np.linspace(0, 1, 100) colors = pt.scores_to_color(scalars, cmap_=cmap_, reverse_cmap=False, cmap_range=(mn, mx)) colors = [pt.lighten_rgb(c, .4) for c in colors] if ut.list_type(basis) is int: pt.colorbar(scalars, colors, lbl=SCORE_TTYPE, ticklabels=np.array(basis) + 1) else: pt.colorbar(scalars, colors, lbl=SCORE_TTYPE, ticklabels=basis) #print('basis = %r' % (basis,)) # Draw probability hist if has_inferred and top_assignments is not None: bin_labels = ut.get_list_column(top_assignments, 0) bin_vals = ut.get_list_column(top_assignments, 1) # bin_labels = ['\n'.join(ut.textwrap.wrap(_lbl, width=30)) for _lbl in bin_labels] pt.draw_histogram( bin_labels, bin_vals, fnum=fnum, pnum=(3, 8, (2, slice(4, None))), transpose=True, use_darkbackground=False, #xtick_rotation=-10, ylabel='Prob', xlabel='assignment') pt.set_title('Assignment probabilities')
def show_multi_images(ibs, gid_list, fnum=None, **kwargs): r""" Args: ibs (IBEISController): ibeis controller object gid_list (list): fnum (int): figure number(default = None) CommandLine: python -m ibeis.viz.viz_image --test-show_multi_images --db NNP_Master3 --gids=7409,7448,4670,7497,7496,7464,7446,7442 --show python -m ibeis.viz.viz_image --test-show_multi_images --db NNP_Master3 --gids=1,2,3 --show Ignore: >>> # print to 8 gids sorted by num aids >>> import ibeis >>> ibs = ibeis.opendb('NNP_Master3') >>> gid_list = ibs.get_valid_gids() >>> aids_list = ibs.get_image_aids(gid_list) >>> index_list = ut.list_argsort(list(map(len, aids_list)))[::-1] >>> gid_list = ut.take(gid_list, index_list[0:8]) >>> print(','.join(map(str, gid_list))) Example: >>> # DISABLE_DOCTEST >>> from ibeis.viz.viz_image import * # NOQA >>> import ibeis >>> ibs = ibeis.opendb(defaultdb='testdb1') >>> gid_list = ut.get_argval('--gids', list, default=[1, 2]) >>> fnum = None >>> result = show_multi_images(ibs, gid_list, fnum, draw_lbls=False, notitle=True, sel_aids='all') >>> print(result) >>> ut.show_if_requested() """ fnum = pt.ensure_fnum(fnum) nGids = len(gid_list) if nGids == 0: fig = pt.figure(fnum=fnum, pnum=(1, 1, 1), **kwargs) pt.imshow_null(fnum=fnum, **kwargs) return fig # Trigger computation of all chips in parallel #ibsfuncs.ensure_annotation_data(ibs, aid_list, chips=(not in_image or annote), feats=annote) rc = ut.get_argval('--rc', type_=list, default=None) if rc is None: nRows, nCols = ph.get_square_row_cols(nGids) else: nRows, nCols = rc #notitle = ut.get_argflag('--notitle') #draw_lbls = not ut.get_argflag('--no-draw_lbls') #show_chip_kw = dict(annote=annote, in_image=in_image, notitle=notitle, draw_lbls=draw_lbls) #print('[viz_name] * r=%r, c=%r' % (nRows, nCols)) #gs2 = gridspec.GridSpec(nRows, nCols) pnum_ = pt.get_pnum_func(nRows, nCols) fig = pt.figure(fnum=fnum, pnum=pnum_(0), **kwargs) fig.clf() for px, gid in enumerate(gid_list): print(pnum_(px)) _fig, _ax1 = show_image(ibs, gid, fnum=fnum, pnum=pnum_(px), **kwargs) #ax = pt.gca() #if aid in sel_aids: # pt.draw_border(ax, pt.GREEN, 4) #if ut.get_argflag('--numlbl') and not DOBOTH: # ax.set_xlabel('(' + str(px + 1) + ')') #plot_aid3(ibs, aid) pass
def draw_markov_model(model, fnum=None, **kwargs): import plottool as pt fnum = pt.ensure_fnum(fnum) pt.figure(fnum=fnum, doclf=True) ax = pt.gca() from pgmpy.models import MarkovModel if isinstance(model, MarkovModel): markovmodel = model else: markovmodel = model.to_markov_model() # pos = netx.pydot_layout(markovmodel) pos = netx.pygraphviz_layout(markovmodel) # Referenecs: # https://groups.google.com/forum/#!topic/networkx-discuss/FwYk0ixLDuY # pos = netx.spring_layout(markovmodel) # pos = netx.circular_layout(markovmodel) # curved-arrow # markovmodel.edge_attr['curved-arrow'] = True # markovmodel.graph.setdefault('edge', {})['splines'] = 'curved' # markovmodel.graph.setdefault('graph', {})['splines'] = 'curved' # markovmodel.graph.setdefault('edge', {})['splines'] = 'curved' node_color = [pt.NEUTRAL] * len(pos) drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color, # NOQA node_size=1100) from matplotlib.patches import FancyArrowPatch, Circle import numpy as np def draw_network(G, pos, ax, sg=None): for n in G: c = Circle(pos[n], radius=10, alpha=0.5, color=pt.NEUTRAL_BLUE) ax.add_patch(c) G.node[n]['patch'] = c x, y = pos[n] pt.ax_absolute_text(x, y, n, ha='center', va='center') seen = {} for (u, v, d) in G.edges(data=True): n1 = G.node[u]['patch'] n2 = G.node[v]['patch'] rad = 0.1 if (u, v) in seen: rad = seen.get((u, v)) rad = (rad + np.sign(rad) * 0.1) * -1 alpha = 0.5 color = 'k' e = FancyArrowPatch(n1.center, n2.center, patchA=n1, patchB=n2, # arrowstyle='-|>', arrowstyle='-', connectionstyle='arc3,rad=%s' % rad, mutation_scale=10.0, lw=2, alpha=alpha, color=color) seen[(u, v)] = rad ax.add_patch(e) return e # netx.draw(markovmodel, **drawkw) draw_network(markovmodel, pos, ax) ax.autoscale() pt.plt.axis('equal') pt.plt.axis('off') if kwargs.get('show_title', True): pt.set_figtitle('Markov Model')