%prog prune best.edges

    Prune overlap graph.
545094
def prune(args):
    
    from collections import defaultdict

    p = OptionParser(prune.__doc__)
    add_graph_options(p)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    bestedges, = args
    G = read_graph(bestedges, maxerr=opts.maxerr)
    reads_to_ctgs = parse_ctgs(bestedges, opts.frgctg)
    edges = defaultdict(int)
    r = defaultdict(int)
    for a, b, d in G.edges_iter(data=True):
        ua, ub = reads_to_ctgs.get(a), reads_to_ctgs.get(b)
        nn = (ua, ub).count(None)
        if nn == 0:
            if ua == ub:
                r["Same tigs"] += 1
            else:
                r["Diff tigs"] += 1
                if ua > ub:
                    ua, ub = ub, ua
                edges[(ua, ub)] += 1
        elif nn == 1:
            r["One null"] += 1
        else:
            assert nn == 2
            r["Two nulls"] += 1

    U = nx.Graph()
    difftigs = "diff_tigs.txt"
    neighbors = defaultdict(list)
    fw = open(difftigs, "w")
    for (ua, ub), count in edges.items():
        print("\t".join((ua, ub, str(count))), file=fw)
        U.add_edge(ua, ub, weight=count)
        neighbors[ua].append((ub, count))
        neighbors[ub].append((ua, count))
    fw.close()

    print("[Unitig edge property]", file=sys.stderr)
    for k, v in r.items():
        print(": ".join((k, str(v))), file=sys.stderr)
    print("Total: {0}".format(sum(r.values())), file=sys.stderr)

    print("[Unitig degree distribution]", file=sys.stderr)
    degrees = U.degree()
    degree_counter = Counter(degrees.values())
    for degree, count in sorted(degree_counter.items()):
        print("{0}\t{1}".format(degree, count), file=sys.stderr)

    # To find associative contigs, one look for a contig that is connected and
    # only connected to another single contig - and do that recursively until no
    # more contigs can be found
    associative = {}
    for ua, ubs in neighbors.items():
        if len(ubs) == 1:   # Only one neighbor
            ub, count = ubs[0]
            if count >= 2:  # Bubble
                associative[ua] = (ub, count)
    print("A total of {0} associative contigs found"\
                        .format(len(associative)), file=sys.stderr)

    # Keep only one for mutual associative
    for ua, ub in associative.items():
        if ub in associative and ua < ub:
            print(ua, "mutually associative with", ub, file=sys.stderr)
            del associative[ub]
    print("A total of {0} associative contigs retained"\
                        .format(len(associative)), file=sys.stderr)

    assids = "associative.ids"
    fw = open(assids, "w")
    for ua, (ub, count) in sorted(associative.items(), key=lambda x:(x[1], x[0])):
        print("\t".join((ua, ub, str(count))), file=fw)
    fw.close()
    logging.debug("Associative contigs written to `{0}`".format(assids))
670375
def filter(args):
    
    p = OptionParser(filter.__doc__)
    p.set_align(pctid=0, hitlen=0)
    p.add_option("--overlap", default=False, action="store_true",
            help="Print overlap status (e.g. terminal, contained)")

    opts, args = p.parse_args(args)
    if len(args) != 1:
        sys.exit(not p.print_help())

    pctid = opts.pctid
    hitlen = opts.hitlen

    filename, = args
    if pctid == 0 and hitlen == 0:
        return filename

    pf, suffix = filename.rsplit(".", 1)
    outfile = "".join((pf, ".P{0}L{1}.".format(int(pctid), int(hitlen)), suffix))
    if not need_update(filename, outfile):
        return outfile

    if suffix == "delta":
        cmd = "delta-filter -i {0} -l {1} {2}".format(pctid, hitlen, filename)
        sh(cmd, outfile=outfile)
        return outfile

    fp = open(filename)
    fw = must_open(outfile, "w")
    for row in fp:
        try:
            c = CoordsLine(row)
        except AssertionError:
            continue

        if c.identity < pctid:
            continue
        if c.len2 < hitlen:
            continue
        if opts.overlap and not c.overlap:
            continue

        outrow = row.rstrip()
        if opts.overlap:
            ov = Overlap_types[c.overlap]
            outrow += "\t" + ov
        print(outrow, file=fw)

    return outfile
129846
def slice(self, x, y, width):
        
        return self._double_buffer[y][x:x + width]
1342828
def prune_tour(self, tour, cpus):
        
        while True:
            tour_score, = self.evaluate_tour_M(tour)
            logging.debug("Starting score: {}".format(tour_score))
            active_sizes = self.active_sizes
            M = self.M
            args = []
            for i, t in enumerate(tour):
                stour = tour[:i] + tour[i + 1:]
                args.append((t, stour, tour_score, active_sizes, M))

            # Parallel run
            p = Pool(processes=cpus)
            results = list(p.imap(prune_tour_worker, args))
            assert len(tour) == len(results), \
                "Array size mismatch, tour({}) != results({})"\
                .format(len(tour), len(results))

            # Identify outliers
            active_contigs = self.active_contigs
            idx, log10deltas = zip(*results)
            lb, ub = outlier_cutoff(log10deltas)
            logging.debug("Log10(delta_score) ~ [{}, {}]".format(lb, ub))

            remove = set(active_contigs[x] for (x, d) in results if d < lb)
            self.active -= remove
            self.report_active()

            tig_to_idx = self.tig_to_idx
            tour = [active_contigs[x] for x in tour]
            tour = array.array('i', [tig_to_idx[x] for x in tour
                                     if x not in remove])
            if not remove:
                break

        self.tour = tour
        self.flip_all(tour)

        return tour
1061010
void pruneNearlyIdenticalAngles() {
		for (int i = 0; i < listInfo.size(); i++) {
			NodeInfo infoN = listInfo.get(i);

			for (int j = 0; j < infoN.edges.size(); ) {
				int k = (j+1)%infoN.edges.size;

				double angularDiff = UtilAngle.dist(infoN.edges.get(j).angle,infoN.edges.get(k).angle);
				if( angularDiff < UtilAngle.radian(5)) {
					NodeInfo infoJ = infoN.edges.get(j).target;
					NodeInfo infoK = infoN.edges.get(k).target;

					double distJ = infoN.ellipse.center.distance(infoJ.ellipse.center);
					double distK = infoN.ellipse.center.distance(infoK.ellipse.center);

					if( distJ < distK ) {
						infoN.edges.remove(k);
					} else {
						infoN.edges.remove(j);
					}

				} else {
					j++;
				}
			}
		}
	}
431800
def prune(manager: Manager):
    """"""
    nodes_to_delete = [
        node
        for node in tqdm(manager.session.query(Node), total=manager.count_nodes())
        if not node.networks
    ]
    manager.session.delete(nodes_to_delete)
    manager.session.commit()
1263445
def remove_neighbours(self):
        
        time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order))

        intervals_arr = self._interval_set._intervals
        intervals_arr[:, 0] = np.minimum(intervals_arr[:, 0] + time_delta, (1 << 58) - 1)
        intervals_arr[:, 1] = np.maximum(intervals_arr[:, 1] - time_delta, 0)

        good_intervals = intervals_arr[:, 1] > intervals_arr[:, 0]

        self._interval_set = IntervalSet(intervals_arr[good_intervals])
452794
def truncateGraph(graph, root_nodes):
		
		subgraph = Graph()
		for node in root_nodes:
			subgraph = GraphUtils.joinGraphs(subgraph, GraphUtils.getReacheableSubgraph(graph, node))

		return subgraph
9589
function slice(str, beginSlice, endSlice) {
  return GraphemeBreaker.break(str)
    .slice(beginSlice, endSlice)
    .join('');
}
625513
private void pruneMatches() {
		int index = 0;
		while( index < matches.size ) {
			AssociatedTripleIndex a = matches.get(index);
			// not matched. Remove it from the list by copying that last element over it
			if( a.c == -1 ) {
				a.set(matches.get(matches.size-1));
				matches.size--;
			} else {
				index++;
			}
		}
	}
777010
def findOverlap(x_mins, y_mins, min_distance):
    
    n = len(x_mins)
    idex = []
    for i in range(n):
        if i == 0:
            pass
        else:
            for j in range(0, i):
                if (abs(x_mins[i] - x_mins[j]) < min_distance and abs(y_mins[i] - y_mins[j]) < min_distance):
                    idex.append(i)
                    break
    x_mins = np.delete(x_mins, idex, axis=0)
    y_mins = np.delete(y_mins, idex, axis=0)
    return x_mins, y_mins
704703
def remove_edge(self, u, v):
        
        # Remove (u, v) from represented graph
        print('Dynamically removing uv=(%r, %r)' % (u, v))
        self.graph.remove_edge(u, v)
        e = (u, v)
        # Remove edge e = (u, v) from all graphs.
        if not self.forests[0].has_edge(u, v):
            # If (u, v) is a non-tree edge, simply delete it.
            # Nothing else to do.
            return
        # If (u, v) is a tree edge we delete it and search for a replacement.
        # Delete from all higher levels
        for i in reversed(range(0, self.level[e] + 1)):
            self.forests[i].remove_edge(u, v)

        # Determine if another edge that connects u and v exists.
        # (This must be an edge r, level[r] <= level[e])
        # (Find max possible level[r] <= level[e])
        for i in reversed(range(0, self.level[e] + 1)):
            # Tu != Tw b/c (u, v) was just deleted from all forests
            Tu = self.forests[i].subtree(u)
            print('Tu = %r' % (list(Tu.nodes()),))
            Tv = self.forests[i].subtree(v)
            print('Tv = %r' % (list(Tv.nodes()),))
            # Relabel so len(Tu) <= len(Tv)
            # This ensures len(Tu) < 2 ** (floor(log(n)) - i)
            if len(Tu) > len(Tv):
                Tu, Tv = Tv, Tu
                # Note len(Tu) <= 2 * (len(Tu) + len(Tv) + 1)
            # We can afford to push all of Tu's edges to the next level and
            # still preserve invariant 1.
            seen_ = set([])
            for x in Tu.nodes():
                # Visit all edges INCIDENT (in real graph) to nodes in Tu.
                # This lets us find non-tree edges to make a tree edge
                seen_.add(x)
                for y in self.graph.neighbors(x):
                    if y in seen_:
                        continue
                    # print('Check replacement edge xy=(%r, %r)' % (x, y))
                    if y in Tv:
                        print('* Found replacement xy=(%r, %r)' % (x, y))
                        # edge (x, y) is a replacement edge.
                        # add (x, y) to prev forests F[0:i+1]
                        # This is the only place edges are added to forets of
                        # higher levels.
                        if len(self.forests) == i + 1:
                            self.forests.append(DummyEulerTourForest(self.graph.nodes()))
                        for j in range(0, i + 2):
                            print('* Add replacment to F[j=%r]' % (j,))
                            # Need euler tree augmentation for outgoing level edges
                            self.forests[j].add_edge(x, y)
                        return
                    else:
                        print('* Charging xy=(%r, %r)' % (x, y))
                        # charge --- add (x, y) to next level
                        # this pays for our search in an amortized sense
                        # (ie, the next search at this level wont consider this)
                        if len(self.forests) == i + 1:
                            self.forests.append(DummyEulerTourForest(self.graph.nodes()))
                        if self.forests[i].has_edge(x, y):
                            self.forests[i + 1].add_edge(x, y)
                        #     # assert False, 'we got it, should add it?'
                        self.level[(x, y)] = i + 1
272190
def out_edges(self, node):
        
        try:
            return list(self.nodes[node][1])
        except KeyError:
            raise GraphError('Invalid node %s' % node)

        return None
869531
def overlaps(self, *args):
        
        self.op = '&&'
        self.negate_op = None
        self.value = self._array_value(args)
        return self
1290294
def cut(args):
    
    p = OptionParser(cut.__doc__)
    p.add_option("--sep", default=".", help="Separator for splits")
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    agpfile, bedfile = args
    sep = opts.sep

    agp = AGP(agpfile)
    bed = Bed(bedfile)
    simple_agp = agp.order
    newagpfile = agpfile.replace(".agp", ".cut.agp")
    fw = open(newagpfile, "w")

    agp_fixes = defaultdict(list)
    for component, intervals in bed.sub_beds():
        i, a = simple_agp[component]
        object = a.object
        component_span = a.component_span
        orientation = a.orientation

        assert a.component_beg, a.component_end
        cuts = set()
        for i in intervals:
            start, end = i.start, i.end
            end -= 1

            assert start <= end
            cuts.add(start)
            cuts.add(end)

        cuts.add(0)
        cuts.add(component_span)
        cuts = list(sorted(cuts))

        sum_of_spans = 0
        for i, (a, b) in enumerate(pairwise(cuts)):
            oid = object + "{0}{1}".format(sep, i + 1)
            aline = [oid, 0, 0, 0]
            cspan = b - a
            aline += ['D', component, a + 1, b, orientation]
            sum_of_spans += cspan

            aline = "\t".join(str(x) for x in aline)
            agp_fixes[component].append(aline)

        assert component_span == sum_of_spans

    # Finally write the masked agp
    for a in agp:
        if not a.is_gap and a.component_id in agp_fixes:
            print("\n".join(agp_fixes[a.component_id]), file=fw)
        else:
            print(a, file=fw)

    fw.close()
    # Reindex
    reindex([newagpfile, "--inplace"])

    return newagpfile
377065
def remove_edge(self, u, v):
        
        try:
            del self.succ[u][v]
        except KeyError:
            raise NetworkXError(
                "The edge {}-{} is not in the graph.".format(u, v)
            )
1029256
def sort(self):
        
        while self.nodes:
            iterated = False
            for node in self.leaf_nodes():
                iterated = True
                self.prune_node(node)
                yield node
            if not iterated:
                raise CyclicGraphError("Sorting has found a cyclic graph.")