def intraoccurrence_connected(): r""" CommandLine: python -m ibeis.scripts.specialdraw intraoccurrence_connected --show python -m ibeis.scripts.specialdraw intraoccurrence_connected --show --postcut python -m ibeis.scripts.specialdraw intraoccurrence_connected --show --smaller Example: >>> # DISABLE_DOCTEST >>> from ibeis.scripts.specialdraw import * # NOQA >>> result = intraoccurrence_connected() >>> print(result) >>> ut.quit_if_noshow() >>> import plottool as pt >>> ut.show_if_requested() """ import ibeis import plottool as pt from ibeis.viz import viz_graph import networkx as nx pt.ensure_pylab_qt4() ibs = ibeis.opendb(defaultdb='PZ_Master1') nid2_aid = { #4880: [3690, 3696, 3703, 3706, 3712, 3721], 4880: [3690, 3696, 3703], 6537: [3739], 6653: [7671], 6610: [7566, 7408], #6612: [7664, 7462, 7522], #6624: [7465, 7360], #6625: [7746, 7383, 7390, 7477, 7376, 7579], 6630: [7586, 7377, 7464, 7478], #6677: [7500] } nid2_dbaids = {4880: [33, 6120, 7164], 6537: [7017, 7206], 6653: [7660]} if ut.get_argflag('--small') or ut.get_argflag('--smaller'): del nid2_aid[6630] del nid2_aid[6537] del nid2_dbaids[6537] if ut.get_argflag('--smaller'): nid2_dbaids[4880].remove(33) nid2_aid[4880].remove(3690) nid2_aid[6610].remove(7408) #del nid2_aid[4880] #del nid2_dbaids[4880] aids = ut.flatten(nid2_aid.values()) temp_nids = [1] * len(aids) postcut = ut.get_argflag('--postcut') aids_list = ibs.group_annots_by_name(aids)[0] ensure_edges = 'all' if True or not postcut else None unlabeled_graph = viz_graph.make_netx_graph_from_aid_groups( ibs, aids_list, #invis_edges=invis_edges, ensure_edges=ensure_edges, temp_nids=temp_nids) viz_graph.color_by_nids(unlabeled_graph, unique_nids=[1] * len(list(unlabeled_graph.nodes()))) viz_graph.ensure_node_images(ibs, unlabeled_graph) nx.set_node_attributes(unlabeled_graph, 'shape', 'rect') #unlabeled_graph = unlabeled_graph.to_undirected() # Find the "database exemplars for these annots" if False: gt_aids = ibs.get_annot_groundtruth(aids) gt_aids = [ut.setdiff(s, aids) for s in gt_aids] dbaids = ut.unique(ut.flatten(gt_aids)) dbaids = ibs.filter_annots_general(dbaids, minqual='good') ibs.get_annot_quality_texts(dbaids) else: dbaids = ut.flatten(nid2_dbaids.values()) exemplars = nx.DiGraph() #graph = exemplars # NOQA exemplars.add_nodes_from(dbaids) def add_clique(graph, nodes, edgeattrs={}, nodeattrs={}): edge_list = ut.upper_diag_self_prodx(nodes) graph.add_edges_from(edge_list, **edgeattrs) return edge_list for aids_, nid in zip(*ibs.group_annots_by_name(dbaids)): add_clique(exemplars, aids_) viz_graph.ensure_node_images(ibs, exemplars) viz_graph.color_by_nids(exemplars, ibs=ibs) nx.set_node_attributes(unlabeled_graph, 'framewidth', False) nx.set_node_attributes(exemplars, 'framewidth', 4.0) nx.set_node_attributes(unlabeled_graph, 'group', 'unlab') nx.set_node_attributes(exemplars, 'group', 'exemp') #big_graph = nx.compose_all([unlabeled_graph]) big_graph = nx.compose_all([exemplars, unlabeled_graph]) # add sparse connections from unlabeled to exemplars import numpy as np rng = np.random.RandomState(0) if True or not postcut: for aid_ in unlabeled_graph.nodes(): flags = rng.rand(len(exemplars)) > .5 nid_ = ibs.get_annot_nids(aid_) exnids = np.array(ibs.get_annot_nids(list(exemplars.nodes()))) flags = np.logical_or(exnids == nid_, flags) exmatches = ut.compress(list(exemplars.nodes()), flags) big_graph.add_edges_from(list(ut.product([aid_], exmatches)), color=pt.ORANGE, implicit=True) else: for aid_ in unlabeled_graph.nodes(): flags = rng.rand(len(exemplars)) > .5 exmatches = ut.compress(list(exemplars.nodes()), flags) nid_ = ibs.get_annot_nids(aid_) exnids = np.array(ibs.get_annot_nids(exmatches)) exmatches = ut.compress(exmatches, exnids == nid_) big_graph.add_edges_from(list(ut.product([aid_], exmatches))) pass nx.set_node_attributes(big_graph, 'shape', 'rect') #if False and postcut: # ut.nx_delete_node_attr(big_graph, 'nid') # ut.nx_delete_edge_attr(big_graph, 'color') # viz_graph.ensure_graph_nid_labels(big_graph, ibs=ibs) # viz_graph.color_by_nids(big_graph, ibs=ibs) # big_graph = big_graph.to_undirected() layoutkw = { 'sep': 1 / 5, 'prog': 'neato', 'overlap': 'false', #'splines': 'ortho', 'splines': 'spline', } as_directed = False #as_directed = True #hacknode = True hacknode = 0 graph = big_graph ut.nx_ensure_agraph_color(graph) if hacknode: nx.set_edge_attributes(graph, 'taillabel', {e: str(e[0]) for e in graph.edges()}) nx.set_edge_attributes(graph, 'headlabel', {e: str(e[1]) for e in graph.edges()}) explicit_graph = pt.get_explicit_graph(graph) _, layout_info = pt.nx_agraph_layout(explicit_graph, orig_graph=graph, inplace=True, **layoutkw) if ut.get_argflag('--smaller'): graph.node[7660]['pos'] = np.array([550, 350]) graph.node[6120]['pos'] = np.array([200, 600]) + np.array([350, -400]) graph.node[7164]['pos'] = np.array([200, 480]) + np.array([350, -400]) nx.set_node_attributes(graph, 'pin', 'true') _, layout_info = pt.nx_agraph_layout(graph, inplace=True, **layoutkw) elif ut.get_argflag('--small'): graph.node[7660]['pos'] = np.array([750, 350]) graph.node[33]['pos'] = np.array([300, 600]) + np.array([350, -400]) graph.node[6120]['pos'] = np.array([500, 600]) + np.array([350, -400]) graph.node[7164]['pos'] = np.array([410, 480]) + np.array([350, -400]) nx.set_node_attributes(graph, 'pin', 'true') _, layout_info = pt.nx_agraph_layout(graph, inplace=True, **layoutkw) if not postcut: #pt.show_nx(graph.to_undirected(), layout='agraph', layoutkw=layoutkw, # as_directed=False) #pt.show_nx(graph, layout='agraph', layoutkw=layoutkw, # as_directed=as_directed, hacknode=hacknode) pt.show_nx(graph, layout='custom', layoutkw=layoutkw, as_directed=as_directed, hacknode=hacknode) else: #explicit_graph = pt.get_explicit_graph(graph) #_, layout_info = pt.nx_agraph_layout(explicit_graph, orig_graph=graph, # **layoutkw) #layout_info['edge']['alpha'] = .8 #pt.apply_graph_layout_attrs(graph, layout_info) #graph_layout_attrs = layout_info['graph'] ##edge_layout_attrs = layout_info['edge'] ##node_layout_attrs = layout_info['node'] #for key, vals in layout_info['node'].items(): # #print('[special] key = %r' % (key,)) # nx.set_node_attributes(graph, key, vals) #for key, vals in layout_info['edge'].items(): # #print('[special] key = %r' % (key,)) # nx.set_edge_attributes(graph, key, vals) #nx.set_edge_attributes(graph, 'alpha', .8) #graph.graph['splines'] = graph_layout_attrs.get('splines', 'line') #graph.graph['splines'] = 'polyline' # graph_layout_attrs.get('splines', 'line') #graph.graph['splines'] = 'line' cut_graph = graph.copy() edge_list = list(cut_graph.edges()) edge_nids = np.array(ibs.unflat_map(ibs.get_annot_nids, edge_list)) cut_flags = edge_nids.T[0] != edge_nids.T[1] cut_edges = ut.compress(edge_list, cut_flags) cut_graph.remove_edges_from(cut_edges) ut.nx_delete_node_attr(cut_graph, 'nid') viz_graph.ensure_graph_nid_labels(cut_graph, ibs=ibs) #ut.nx_get_default_node_attributes(exemplars, 'color', None) ut.nx_delete_node_attr(cut_graph, 'color', nodes=unlabeled_graph.nodes()) aid2_color = ut.nx_get_default_node_attributes(cut_graph, 'color', None) nid2_colors = ut.group_items(aid2_color.values(), ibs.get_annot_nids(aid2_color.keys())) nid2_colors = ut.map_dict_vals(ut.filter_Nones, nid2_colors) nid2_colors = ut.map_dict_vals(ut.unique, nid2_colors) #for val in nid2_colors.values(): # assert len(val) <= 1 # Get initial colors nid2_color_ = { nid: colors_[0] for nid, colors_ in nid2_colors.items() if len(colors_) == 1 } graph = cut_graph viz_graph.color_by_nids(cut_graph, ibs=ibs, nid2_color_=nid2_color_) nx.set_node_attributes(cut_graph, 'framewidth', 4) pt.show_nx(cut_graph, layout='custom', layoutkw=layoutkw, as_directed=as_directed, hacknode=hacknode) pt.zoom_factory()
def setcover_example(): """ CommandLine: python -m ibeis.scripts.specialdraw setcover_example --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.scripts.specialdraw import * # NOQA >>> result = setcover_example() >>> print(result) >>> ut.quit_if_noshow() >>> import plottool as pt >>> ut.show_if_requested() """ import ibeis import plottool as pt from ibeis.viz import viz_graph import networkx as nx pt.ensure_pylab_qt4() ibs = ibeis.opendb(defaultdb='testdb2') if False: # Select a good set aids = ibs.get_name_aids(ibs.get_valid_nids()) # ibeis.testdata_aids('testdb2', a='default:mingt=2') aids = [a for a in aids if len(a) > 1] for a in aids: print(ut.repr3(ibs.get_annot_stats_dict(a))) print(aids[-2]) #aids = [78, 79, 80, 81, 88, 91] aids = [78, 79, 81, 88, 91] qreq_ = ibs.depc.new_request('vsone', aids, aids, cfgdict={}) cm_list = qreq_.execute() from ibeis.algo.hots import graph_iden infr = graph_iden.AnnotInference(cm_list) unique_aids, prob_annots = infr.make_prob_annots() import numpy as np print( ut.hz_str( 'prob_annots = ', ut.array2string2(prob_annots, precision=2, max_line_width=140, suppress_small=True))) # ut.setcover_greedy(candidate_sets_dict) max_weight = 3 prob_annots[np.diag_indices(len(prob_annots))] = np.inf prob_annots = prob_annots thresh_points = np.sort(prob_annots[np.isfinite(prob_annots)]) # probably not the best way to go about searching for these thresholds # but when you have a hammer... if False: quant = sorted(np.diff(thresh_points))[(len(thresh_points) - 1) // 2] candset = { point: thresh_points[np.abs(thresh_points - point) < quant] for point in thresh_points } check_thresholds = len(aids) * 2 thresh_points2 = np.array( ut.setcover_greedy(candset, max_weight=check_thresholds).keys()) thresh_points = thresh_points2 # pt.plot(sorted(thresh_points), 'rx') # pt.plot(sorted(thresh_points2), 'o') # prob_annots = prob_annots.T # thresh_start = np.mean(thresh_points) current_idxs = [] current_covers = [] current_val = np.inf for thresh in thresh_points: covering_sets = [np.where(row >= thresh)[0] for row in (prob_annots)] candidate_sets_dict = { ax: others for ax, others in enumerate(covering_sets) } soln_cover = ut.setcover_ilp(candidate_sets_dict, max_weight=max_weight) exemplar_idxs = list(soln_cover.keys()) soln_weight = len(exemplar_idxs) val = max_weight - soln_weight # print('val = %r' % (val,)) # print('soln_weight = %r' % (soln_weight,)) if val < current_val: current_val = val current_covers = covering_sets current_idxs = exemplar_idxs exemplars = ut.take(aids, current_idxs) ensure_edges = [(aids[ax], aids[ax2]) for ax, other_xs in enumerate(current_covers) for ax2 in other_xs] graph = viz_graph.make_netx_graph_from_aid_groups( ibs, [aids], allow_directed=True, ensure_edges=ensure_edges, temp_nids=[1] * len(aids)) viz_graph.ensure_node_images(ibs, graph) nx.set_node_attributes(graph, 'framewidth', False) nx.set_node_attributes(graph, 'framewidth', {aid: 4.0 for aid in exemplars}) nx.set_edge_attributes(graph, 'color', pt.ORANGE) nx.set_node_attributes(graph, 'color', pt.LIGHT_BLUE) nx.set_node_attributes(graph, 'shape', 'rect') layoutkw = { 'sep': 1 / 10, 'prog': 'neato', 'overlap': 'false', #'splines': 'ortho', 'splines': 'spline', } pt.show_nx(graph, layout='agraph', layoutkw=layoutkw) pt.zoom_factory()
def initialize_graph_and_model(infr): """ Unused in internal split stuff pt.qt4ensure() layout_info = pt.show_nx(graph, as_directed=False, fnum=1, layoutkw=dict(prog='neato'), use_image=True, verbose=0) ax = pt.gca() pt.zoom_factory() pt.interactions.PanEvents() """ #import networkx as nx #import itertools cm_list = infr.cm_list hack = True hack = False if hack: cm_list = cm_list[:10] qaid_list = [cm.qaid for cm in cm_list] daids_list = [cm.daid_list for cm in cm_list] unique_aids = sorted(ut.list_union(*daids_list + [qaid_list])) if hack: unique_aids = sorted(ut.isect(unique_aids, qaid_list)) aid2_aidx = ut.make_index_lookup(unique_aids) # Construct K-broken graph edges = [] edge_weights = [] #top = (infr.qreq_.qparams.K + 1) * 2 #top = (infr.qreq_.qparams.K) * 2 top = (infr.qreq_.qparams.K + 2) for count, cm in enumerate(cm_list): qidx = aid2_aidx[cm.qaid] score_list = cm.annot_score_list sortx = ut.argsort(score_list)[::-1] score_list = ut.take(score_list, sortx)[:top] daid_list = ut.take(cm.daid_list, sortx)[:top] for score, daid in zip(score_list, daid_list): if daid not in qaid_list: continue didx = aid2_aidx[daid] edge_weights.append(score) edges.append((qidx, didx)) # make symmetric directed_edges = dict(zip(edges, edge_weights)) # Find edges that point in both directions undirected_edges = {} for (u, v), w in directed_edges.items(): if (v, u) in undirected_edges: undirected_edges[(v, u)] += w undirected_edges[(v, u)] /= 2 else: undirected_edges[(u, v)] = w edges = list(undirected_edges.keys()) edge_weights = list(undirected_edges.values()) nodes = list(range(len(unique_aids))) nid_labeling = infr.qreq_.ibs.get_annot_nids(unique_aids) labeling = ut.rebase_labels(nid_labeling) import networkx as nx from ibeis.viz import viz_graph set_node_attrs = nx.set_node_attributes set_edge_attrs = nx.set_edge_attributes # Create match-based graph structure graph = nx.DiGraph() graph.add_nodes_from(nodes) graph.add_edges_from(edges) # Important properties nid_list = infr.qreq_.ibs.get_annot_nids(unique_aids) labeling = ut.rebase_labels(nid_list) set_node_attrs(graph, 'name_label', dict(zip(nodes, labeling))) set_edge_attrs(graph, 'weight', dict(zip(edges, edge_weights))) # Visualization properties import plottool as pt ax2_aid = ut.invert_dict(aid2_aidx) set_node_attrs(graph, 'aid', ax2_aid) viz_graph.ensure_node_images(infr.qreq_.ibs, graph) set_node_attrs(graph, 'framewidth', dict(zip(nodes, [3.0] * len(nodes)))) set_node_attrs(graph, 'framecolor', dict(zip(nodes, [pt.DARK_BLUE] * len(nodes)))) ut.color_nodes(graph, labelattr='name_label') edge_colors = pt.scores_to_color(np.array(edge_weights), cmap_='viridis') #import utool #utool.embed() #edge_colors = [pt.color_funcs.ensure_base255(color) for color in edge_colors] #print('edge_colors = %r' % (edge_colors,)) set_edge_attrs(graph, 'color', dict(zip(edges, edge_colors))) # Build inference model from ibeis.algo.hots import graph_iden #graph_iden.rrr() model = graph_iden.InfrModel(graph) #model = graph_iden.InfrModel(len(nodes), edges, edge_weights, labeling=labeling) infr.model = model
def intraoccurrence_connected(): r""" CommandLine: python -m ibeis.scripts.specialdraw intraoccurrence_connected --show python -m ibeis.scripts.specialdraw intraoccurrence_connected --show --postcut python -m ibeis.scripts.specialdraw intraoccurrence_connected --show --smaller Example: >>> # DISABLE_DOCTEST >>> from ibeis.scripts.specialdraw import * # NOQA >>> result = intraoccurrence_connected() >>> print(result) >>> ut.quit_if_noshow() >>> import plottool as pt >>> ut.show_if_requested() """ import ibeis import plottool as pt from ibeis.viz import viz_graph import networkx as nx pt.ensure_pylab_qt4() ibs = ibeis.opendb(defaultdb='PZ_Master1') nid2_aid = { #4880: [3690, 3696, 3703, 3706, 3712, 3721], 4880: [3690, 3696, 3703], 6537: [3739], 6653: [7671], 6610: [7566, 7408], #6612: [7664, 7462, 7522], #6624: [7465, 7360], #6625: [7746, 7383, 7390, 7477, 7376, 7579], 6630: [7586, 7377, 7464, 7478], #6677: [7500] } nid2_dbaids = { 4880: [33, 6120, 7164], 6537: [7017, 7206], 6653: [7660] } if ut.get_argflag('--small') or ut.get_argflag('--smaller'): del nid2_aid[6630] del nid2_aid[6537] del nid2_dbaids[6537] if ut.get_argflag('--smaller'): nid2_dbaids[4880].remove(33) nid2_aid[4880].remove(3690) nid2_aid[6610].remove(7408) #del nid2_aid[4880] #del nid2_dbaids[4880] aids = ut.flatten(nid2_aid.values()) temp_nids = [1] * len(aids) postcut = ut.get_argflag('--postcut') aids_list = ibs.group_annots_by_name(aids)[0] ensure_edges = 'all' if True or not postcut else None unlabeled_graph = viz_graph.make_netx_graph_from_aid_groups( ibs, aids_list, #invis_edges=invis_edges, ensure_edges=ensure_edges, temp_nids=temp_nids) viz_graph.color_by_nids(unlabeled_graph, unique_nids=[1] * len(list(unlabeled_graph.nodes()))) viz_graph.ensure_node_images(ibs, unlabeled_graph) nx.set_node_attributes(unlabeled_graph, 'shape', 'rect') #unlabeled_graph = unlabeled_graph.to_undirected() # Find the "database exemplars for these annots" if False: gt_aids = ibs.get_annot_groundtruth(aids) gt_aids = [ut.setdiff(s, aids) for s in gt_aids] dbaids = ut.unique(ut.flatten(gt_aids)) dbaids = ibs.filter_annots_general(dbaids, minqual='good') ibs.get_annot_quality_texts(dbaids) else: dbaids = ut.flatten(nid2_dbaids.values()) exemplars = nx.DiGraph() #graph = exemplars # NOQA exemplars.add_nodes_from(dbaids) def add_clique(graph, nodes, edgeattrs={}, nodeattrs={}): edge_list = ut.upper_diag_self_prodx(nodes) graph.add_edges_from(edge_list, **edgeattrs) return edge_list for aids_, nid in zip(*ibs.group_annots_by_name(dbaids)): add_clique(exemplars, aids_) viz_graph.ensure_node_images(ibs, exemplars) viz_graph.color_by_nids(exemplars, ibs=ibs) nx.set_node_attributes(unlabeled_graph, 'framewidth', False) nx.set_node_attributes(exemplars, 'framewidth', 4.0) nx.set_node_attributes(unlabeled_graph, 'group', 'unlab') nx.set_node_attributes(exemplars, 'group', 'exemp') #big_graph = nx.compose_all([unlabeled_graph]) big_graph = nx.compose_all([exemplars, unlabeled_graph]) # add sparse connections from unlabeled to exemplars import numpy as np rng = np.random.RandomState(0) if True or not postcut: for aid_ in unlabeled_graph.nodes(): flags = rng.rand(len(exemplars)) > .5 nid_ = ibs.get_annot_nids(aid_) exnids = np.array(ibs.get_annot_nids(list(exemplars.nodes()))) flags = np.logical_or(exnids == nid_, flags) exmatches = ut.compress(list(exemplars.nodes()), flags) big_graph.add_edges_from(list(ut.product([aid_], exmatches)), color=pt.ORANGE, implicit=True) else: for aid_ in unlabeled_graph.nodes(): flags = rng.rand(len(exemplars)) > .5 exmatches = ut.compress(list(exemplars.nodes()), flags) nid_ = ibs.get_annot_nids(aid_) exnids = np.array(ibs.get_annot_nids(exmatches)) exmatches = ut.compress(exmatches, exnids == nid_) big_graph.add_edges_from(list(ut.product([aid_], exmatches))) pass nx.set_node_attributes(big_graph, 'shape', 'rect') #if False and postcut: # ut.nx_delete_node_attr(big_graph, 'nid') # ut.nx_delete_edge_attr(big_graph, 'color') # viz_graph.ensure_graph_nid_labels(big_graph, ibs=ibs) # viz_graph.color_by_nids(big_graph, ibs=ibs) # big_graph = big_graph.to_undirected() layoutkw = { 'sep' : 1 / 5, 'prog': 'neato', 'overlap': 'false', #'splines': 'ortho', 'splines': 'spline', } as_directed = False #as_directed = True #hacknode = True hacknode = 0 graph = big_graph ut.nx_ensure_agraph_color(graph) if hacknode: nx.set_edge_attributes(graph, 'taillabel', {e: str(e[0]) for e in graph.edges()}) nx.set_edge_attributes(graph, 'headlabel', {e: str(e[1]) for e in graph.edges()}) explicit_graph = pt.get_explicit_graph(graph) _, layout_info = pt.nx_agraph_layout(explicit_graph, orig_graph=graph, inplace=True, **layoutkw) if ut.get_argflag('--smaller'): graph.node[7660]['pos'] = np.array([550, 350]) graph.node[6120]['pos'] = np.array([200, 600]) + np.array([350, -400]) graph.node[7164]['pos'] = np.array([200, 480]) + np.array([350, -400]) nx.set_node_attributes(graph, 'pin', 'true') _, layout_info = pt.nx_agraph_layout(graph, inplace=True, **layoutkw) elif ut.get_argflag('--small'): graph.node[7660]['pos'] = np.array([750, 350]) graph.node[33]['pos'] = np.array([300, 600]) + np.array([350, -400]) graph.node[6120]['pos'] = np.array([500, 600]) + np.array([350, -400]) graph.node[7164]['pos'] = np.array([410, 480]) + np.array([350, -400]) nx.set_node_attributes(graph, 'pin', 'true') _, layout_info = pt.nx_agraph_layout(graph, inplace=True, **layoutkw) if not postcut: #pt.show_nx(graph.to_undirected(), layout='agraph', layoutkw=layoutkw, # as_directed=False) #pt.show_nx(graph, layout='agraph', layoutkw=layoutkw, # as_directed=as_directed, hacknode=hacknode) pt.show_nx(graph, layout='custom', layoutkw=layoutkw, as_directed=as_directed, hacknode=hacknode) else: #explicit_graph = pt.get_explicit_graph(graph) #_, layout_info = pt.nx_agraph_layout(explicit_graph, orig_graph=graph, # **layoutkw) #layout_info['edge']['alpha'] = .8 #pt.apply_graph_layout_attrs(graph, layout_info) #graph_layout_attrs = layout_info['graph'] ##edge_layout_attrs = layout_info['edge'] ##node_layout_attrs = layout_info['node'] #for key, vals in layout_info['node'].items(): # #print('[special] key = %r' % (key,)) # nx.set_node_attributes(graph, key, vals) #for key, vals in layout_info['edge'].items(): # #print('[special] key = %r' % (key,)) # nx.set_edge_attributes(graph, key, vals) #nx.set_edge_attributes(graph, 'alpha', .8) #graph.graph['splines'] = graph_layout_attrs.get('splines', 'line') #graph.graph['splines'] = 'polyline' # graph_layout_attrs.get('splines', 'line') #graph.graph['splines'] = 'line' cut_graph = graph.copy() edge_list = list(cut_graph.edges()) edge_nids = np.array(ibs.unflat_map(ibs.get_annot_nids, edge_list)) cut_flags = edge_nids.T[0] != edge_nids.T[1] cut_edges = ut.compress(edge_list, cut_flags) cut_graph.remove_edges_from(cut_edges) ut.nx_delete_node_attr(cut_graph, 'nid') viz_graph.ensure_graph_nid_labels(cut_graph, ibs=ibs) #ut.nx_get_default_node_attributes(exemplars, 'color', None) ut.nx_delete_node_attr(cut_graph, 'color', nodes=unlabeled_graph.nodes()) aid2_color = ut.nx_get_default_node_attributes(cut_graph, 'color', None) nid2_colors = ut.group_items(aid2_color.values(), ibs.get_annot_nids(aid2_color.keys())) nid2_colors = ut.map_dict_vals(ut.filter_Nones, nid2_colors) nid2_colors = ut.map_dict_vals(ut.unique, nid2_colors) #for val in nid2_colors.values(): # assert len(val) <= 1 # Get initial colors nid2_color_ = {nid: colors_[0] for nid, colors_ in nid2_colors.items() if len(colors_) == 1} graph = cut_graph viz_graph.color_by_nids(cut_graph, ibs=ibs, nid2_color_=nid2_color_) nx.set_node_attributes(cut_graph, 'framewidth', 4) pt.show_nx(cut_graph, layout='custom', layoutkw=layoutkw, as_directed=as_directed, hacknode=hacknode) pt.zoom_factory()
def setcover_example(): """ CommandLine: python -m ibeis.scripts.specialdraw setcover_example --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.scripts.specialdraw import * # NOQA >>> result = setcover_example() >>> print(result) >>> ut.quit_if_noshow() >>> import plottool as pt >>> ut.show_if_requested() """ import ibeis import plottool as pt from ibeis.viz import viz_graph import networkx as nx pt.ensure_pylab_qt4() ibs = ibeis.opendb(defaultdb='testdb2') if False: # Select a good set aids = ibs.get_name_aids(ibs.get_valid_nids()) # ibeis.testdata_aids('testdb2', a='default:mingt=2') aids = [a for a in aids if len(a) > 1] for a in aids: print(ut.repr3(ibs.get_annot_stats_dict(a))) print(aids[-2]) #aids = [78, 79, 80, 81, 88, 91] aids = [78, 79, 81, 88, 91] qreq_ = ibs.depc.new_request('vsone', aids, aids, cfgdict={}) cm_list = qreq_.execute() from ibeis.algo.hots import graph_iden infr = graph_iden.AnnotInference(cm_list) unique_aids, prob_annots = infr.make_prob_annots() import numpy as np print(ut.hz_str('prob_annots = ', ut.array2string2(prob_annots, precision=2, max_line_width=140, suppress_small=True))) # ut.setcover_greedy(candidate_sets_dict) max_weight = 3 prob_annots[np.diag_indices(len(prob_annots))] = np.inf prob_annots = prob_annots thresh_points = np.sort(prob_annots[np.isfinite(prob_annots)]) # probably not the best way to go about searching for these thresholds # but when you have a hammer... if False: quant = sorted(np.diff(thresh_points))[(len(thresh_points) - 1) // 2 ] candset = {point: thresh_points[np.abs(thresh_points - point) < quant] for point in thresh_points} check_thresholds = len(aids) * 2 thresh_points2 = np.array(ut.setcover_greedy(candset, max_weight=check_thresholds).keys()) thresh_points = thresh_points2 # pt.plot(sorted(thresh_points), 'rx') # pt.plot(sorted(thresh_points2), 'o') # prob_annots = prob_annots.T # thresh_start = np.mean(thresh_points) current_idxs = [] current_covers = [] current_val = np.inf for thresh in thresh_points: covering_sets = [np.where(row >= thresh)[0] for row in (prob_annots)] candidate_sets_dict = {ax: others for ax, others in enumerate(covering_sets)} soln_cover = ut.setcover_ilp(candidate_sets_dict, max_weight=max_weight) exemplar_idxs = list(soln_cover.keys()) soln_weight = len(exemplar_idxs) val = max_weight - soln_weight # print('val = %r' % (val,)) # print('soln_weight = %r' % (soln_weight,)) if val < current_val: current_val = val current_covers = covering_sets current_idxs = exemplar_idxs exemplars = ut.take(aids, current_idxs) ensure_edges = [(aids[ax], aids[ax2]) for ax, other_xs in enumerate(current_covers) for ax2 in other_xs] graph = viz_graph.make_netx_graph_from_aid_groups( ibs, [aids], allow_directed=True, ensure_edges=ensure_edges, temp_nids=[1] * len(aids)) viz_graph.ensure_node_images(ibs, graph) nx.set_node_attributes(graph, 'framewidth', False) nx.set_node_attributes(graph, 'framewidth', {aid: 4.0 for aid in exemplars}) nx.set_edge_attributes(graph, 'color', pt.ORANGE) nx.set_node_attributes(graph, 'color', pt.LIGHT_BLUE) nx.set_node_attributes(graph, 'shape', 'rect') layoutkw = { 'sep' : 1 / 10, 'prog': 'neato', 'overlap': 'false', #'splines': 'ortho', 'splines': 'spline', } pt.show_nx(graph, layout='agraph', layoutkw=layoutkw) pt.zoom_factory()