strip a BED file down to its three necessary columns: chrom start end
171599
def minimize(bed_file):
    
    if not bed_file:
        return bed_file
    else:
        sorted_bed = bt.BedTool(bed_file).cut(range(3)).sort()
        if not sorted_bed.fn.endswith(".bed"):
            return sorted_bed.moveto(sorted_bed.fn + ".bed")
        else:
            return sorted_bed
773194
def _strip_space(x):
    """"""
    r = repr(x)
    space_repr = '{!r}.element('.format(x.space)
    if r.startswith(space_repr) and r.endswith(')'):
        r = r[len(space_repr):-1]
    return r
619050
def strip_cols(self):
        
        cols = {}
        skipped = []
        for col in self.df.columns.values:
            try:
                cols[col] = col.strip()
            except Exception:
                skipped.append(str(col))
        self.df = self.df.rename(columns=cols)
        self.ok("White spaces removed in columns names")
        if len(skipped) > 0:
            self.info("Skipped columns", ','.join(
                skipped), "while removing white spaces")
1010313
def bed(self, *attrs, **kwargs):
        
        exclude = ("chrom", "start", "end", "txStart", "txEnd", "chromStart",
                "chromEnd")
        if self.is_gene_pred:
            return self.bed12(**kwargs)
        return "\t".join(map(str, (
                 [self.chrom, self.start, self.end] +
                 [getattr(self, attr) for attr in attrs if not attr in exclude]
                         )))
687969
static void bottomTwoColumns(NodeInfo first, NodeInfo second, List<NodeInfo> column0, List<NodeInfo> column1) {
		column0.add(first);
		column0.add(second);

		NodeInfo a = selectClosestN(first,second);
		if( a == null ) {
			return;
		}
		a.marked = true;
		column1.add(a);
		NodeInfo b = second;

		while( true ) {
			NodeInfo t = selectClosestN(a,b);
			if( t == null ) break;
			t.marked = true;
			column1.add(t);

			a = t;
			t = selectClosestN(a,b);
			if( t == null ) break;
			t.marked = true;
			column0.add(t);
			b = t;
		}
	}
1044155
def _cnvbed_to_bed(in_file, caller, out_file):
    
    with open(out_file, "w") as out_handle:
        for feat in pybedtools.BedTool(in_file):
            out_handle.write("\t".join([feat.chrom, str(feat.start), str(feat.end),
                                        "cnv%s_%s" % (feat.score, caller)])
                             + "\n")
1066080
def csv_column_cleaner(rows):
    

    # check columns if there was empty columns
    result = [[] for x in range(0, len(rows))]
    for i_index in range(0, len(rows[0])):

        partial_values = []

        for x_row in rows:
            partial_values.append(
                x_row[i_index] if len(x_row) > i_index else '')

        colum_rows = exclude_empty_values(partial_values)

        if len(colum_rows) > len(rows) / 5:  # adjust this value
            for index in range(0, len(rows)):
                result[index].append(
                    rows[index][i_index] if len(rows[index]) > i_index else '')
    return result
135922
def bed(args):
    
    p = OptionParser(bed.__doc__)

    opts, args = p.parse_args(args)

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

    flist = args
    prefix = flist[0].split(".")[0]

    j = 0
    for f in flist:
        reader = Maf(f).reader
        for rec in reader:
            a, b = rec.components

            for a, tag in zip((a, b), "ab"):
                name = "{0}_{1:07d}{2}".format(prefix, j, tag)
                print("\t".join(str(x) for x in (a.src, a.forward_strand_start, \
                        a.forward_strand_end, name)))

            j += 1
756115
def clean_up(self):#, grid):
        
        if self.selected_col:
            col_label_value = self.grid.GetColLabelValue(self.selected_col)
            col_label_value = col_label_value.strip('\nEDIT ALL')
            self.grid.SetColLabelValue(self.selected_col, col_label_value)
            for row in range(self.grid.GetNumberRows()):
                self.grid.SetCellBackgroundColour(row, self.selected_col, 'white')
        self.grid.ForceRefresh()
658677
def trim(self, start, stop):
        """"""
        return self.client.ltrim(self.name, start, stop - 1)
1031070
def strip(notebook):
    """"""
    for cell in notebook.cells:
        if cell.cell_type == 'code':
            cell.outputs = []
            cell.execution_count = None
960489
def prep_seq2c_bed(data):
    
    if dd.get_background_cnv_reference(data, "seq2c"):
        bed_file = _background_to_bed(dd.get_background_cnv_reference(data, "seq2c"), data)
    else:
        bed_file = regions.get_sv_bed(data)
    if bed_file:
        bed_file = bedutils.clean_file(bed_file, data, prefix="svregions-")
    else:
        bed_file = bedutils.clean_file(dd.get_variant_regions(data), data)
    if not bed_file:
        return None

    col_num = bt.BedTool(bed_file).field_count()
    if col_num < 4:
        annotated_file = annotate.add_genes(bed_file, data, max_distance=0)
        if annotated_file == bed_file:
            raise ValueError("BED file for Seq2C must be annotated with gene names, "
                             "however the input BED is 3-columns and we have no transcript "
                             "data to annotate with " + bed_file)
        annotated_file = annotate.gene_one_per_line(annotated_file, data)
    else:
        annotated_file = bed_file

    ready_file = "%s-seq2cclean.bed" % (utils.splitext_plus(annotated_file)[0])
    if not utils.file_uptodate(ready_file, annotated_file):
        bed = bt.BedTool(annotated_file)
        if col_num > 4 and col_num != 8:
            bed = bed.cut(range(4))
        bed = bed.filter(lambda x: x.name not in ["", ".", "-"])
        with file_transaction(data, ready_file) as tx_out_file:
            bed.saveas(tx_out_file)
        logger.debug("Saved Seq2C clean annotated ready input BED into " + ready_file)

    return ready_file
1034359
def cleanup():
    """"""
    if _output_dir and os.path.exists(_output_dir):
        log.msg_warn("Cleaning up output directory at '{output_dir}' ..."
                     .format(output_dir=_output_dir))
        if not _dry_run:
            shutil.rmtree(_output_dir)
454514
def _prepare_bam(bam_file, bed_file, config):
    """"""
    if not bam_file or not bed_file:
        return bam_file
    out_file = utils.append_stem(bam_file, '_filter')
    bedtools = config_utils.get_program("bedtools", config)
    if not utils.file_exists(out_file):
        with file_transaction(out_file) as tx_out:
            cmd = "{bedtools} subtract -nonamecheck -A -a {bam_file} -b {bed_file} > {tx_out}"
            do.run(cmd.format(**locals()), "Remove blacklist regions from %s" % bam_file)
    return out_file
322893
def erase_start_of_line (self): # <ESC>[1K
        ''''''

        self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c)
1034078
def remove_nopairs(in_bam, out_dir, config):
    
    runner = broad.runner_from_config(config)
    out_bam = os.path.join(out_dir, "{}-safepair{}".format(*os.path.splitext(os.path.basename(in_bam))))
    if not utils.file_exists(out_bam):
        read_counts = collections.defaultdict(int)
        with pysam.Samfile(in_bam, "rb") as in_pysam:
            for read in in_pysam:
                if read.is_paired:
                    read_counts[read.qname] += 1
        with pysam.Samfile(in_bam, "rb") as in_pysam:
            with file_transaction(out_bam) as tx_out_bam:
                with pysam.Samfile(tx_out_bam, "wb", template=in_pysam) as out_pysam:
                    for read in in_pysam:
                        if read_counts[read.qname] == 2:
                            out_pysam.write(read)
    return runner.run_fn("picard_sort", out_bam, "queryname")
1127384
def decomment(bed_file, out_file):
    
    if file_exists(out_file):
        return out_file

    with utils.open_gzipsafe(bed_file) as in_handle, open(out_file, "w") as out_handle:
        for line in in_handle:
            if line.startswith("#") or line.startswith("browser") or line.startswith("track"):
                continue
            else:
                out_handle.write(line)
    return out_file