%prog sizes bedfile

    Infer the sizes for each seqid. Useful before dot plots.
176708
def sizes(args):
    
    p = OptionParser(sizes.__doc__)
    opts, args = p.parse_args(args)

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

    bedfile, = args
    assert op.exists(bedfile)

    sizesfile = bedfile.rsplit(".", 1)[0] + ".sizes"

    fw = must_open(sizesfile, "w", checkexists=True, skipcheck=True)
    if fw:
        b = Bed(bedfile)
        for s, sbeds in b.sub_beds():
            print("{0}\t{1}".format(\
                         s, max(x.end for x in sbeds)), file=fw)
        logging.debug("Sizes file written to `{0}`.".format(sizesfile))

    return sizesfile
1174234
def size(self):
        
        if self._instrs is []:
            return None

        return sum([instr.size for instr in self._instrs])
84803
def find_readlength(args):
    # type: (Namespace) -> int
    """"""

    try:
        bed_file = args.treatment[0]
    except AttributeError:
        bed_file = args.infiles[0]

    filereader = "cat "
    if bed_file.endswith(".gz") and search("linux", platform, IGNORECASE):
        filereader = "zcat "
    elif bed_file.endswith(".gz") and search("darwin", platform, IGNORECASE):
        filereader = "gzcat "
    elif bed_file.endswith(".bz2"):
        filereader = "bzgrep "

    command = filereader + "{} | head -10000".format(bed_file)
    output = check_output(command, shell=True)

    df = pd.read_table(
        BytesIO(output),
        header=None,
        usecols=[1, 2],
        sep="\t",
        names=["Start", "End"])

    readlengths = df.End - df.Start
    mean_readlength = readlengths.mean()
    median_readlength = readlengths.median()
    max_readlength = readlengths.max()
    min_readlength = readlengths.min()

    logging.info((
        "Used first 10000 reads of {} to estimate a median read length of {}\n"
        "Mean readlength: {}, max readlength: {}, min readlength: {}.").format(
            bed_file, median_readlength, mean_readlength, max_readlength,
            min_readlength))

    return median_readlength
1155209
def size(fd):
    

    if not os.isatty(fd.fileno()):
        return None

    try:
        dims = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, 'hhhh'))
    except:
        try:
            dims = (os.environ['LINES'], os.environ['COLUMNS'])
        except:
            return None

    return dims
37963
def output_size(self) -> Tuple[Sequence[Shape], Sequence[Shape], Sequence[Shape], int]:
        ''''''
        return self._cell.output_size
58146
def uniq(args):
    
    from jcvi.formats.sizes import Sizes

    p = OptionParser(uniq.__doc__)
    p.add_option("--sizes", help="Use sequence length as score")
    p.add_option("--mode", default="span", choices=("span", "score"),
                 help="Pile mode")
    opts, args = p.parse_args(args)

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

    bedfile, = args
    uniqbedfile = bedfile.split(".")[0] + ".uniq.bed"
    bed = Bed(bedfile)

    if opts.sizes:
        sizes = Sizes(opts.sizes).mapping
        ranges = [Range(x.seqid, x.start, x.end, sizes[x.accn], i) \
                    for i, x in enumerate(bed)]
    else:
        if opts.mode == "span":
            ranges = [Range(x.seqid, x.start, x.end, x.end - x.start + 1, i) \
                        for i, x in enumerate(bed)]
        else:
            ranges = [Range(x.seqid, x.start, x.end, float(x.score), i) \
                        for i, x in enumerate(bed)]

    selected, score = range_chain(ranges)
    selected = [x.id for x in selected]
    selected_ids = set(selected)
    selected = [bed[x] for x in selected]
    notselected = [x for i, x in enumerate(bed) if i not in selected_ids]

    newbed = Bed()
    newbed.extend(selected)
    newbed.print_to_file(uniqbedfile, sorted=True)

    if notselected:
        leftoverfile = bedfile.split(".")[0] + ".leftover.bed"
        leftoverbed = Bed()
        leftoverbed.extend(notselected)
        leftoverbed.print_to_file(leftoverfile, sorted=True)

    logging.debug("Imported: {0}, Exported: {1}".format(len(bed), len(newbed)))

    return uniqbedfile
649387
def frombed(args):
    
    p = OptionParser(frombed.__doc__)
    p.add_option("--gapsize", default=100, type="int",
                 help="Insert gaps of size [default: %default]")
    opts, args = p.parse_args(args)

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

    bedfile, = args
    gapsize = opts.gapsize
    agpfile = bedfile.replace(".bed", ".agp")
    fw = open(agpfile, "w")

    bed = Bed(bedfile, sorted=False)
    for object, beds in groupby(bed, key=lambda x: x.accn):
        beds = list(beds)
        for i, b in enumerate(beds):
            if gapsize and i != 0:
                print("\t".join(str(x) for x in \
                    (object, 0, 0, 0, "U", \
                     gapsize, "scaffold", "yes", "map")), file=fw)

            print("\t".join(str(x) for x in \
                    (object, 0, 0, 0, "W", \
                     b.seqid, b.start, b.end, b.strand)), file=fw)

    fw.close()

    # Reindex
    return reindex([agpfile, "--inplace"])
13945
def write_equalwidth_bedfile(bedfile, width, outfile):
    """"""

    BUFSIZE = 10000
    f = open(bedfile)
    out = open(outfile, "w")
    lines = f.readlines(BUFSIZE)
    line_count = 0
    while lines:
        for line in lines:
            line_count += 1
            if not line.startswith("#") and not line.startswith("track") and not line.startswith("browser"):
                vals = line.strip().split("\t")
                try:
                    start, end = int(vals[1]), int(vals[2])
                except ValueError:
                    print("Error on line %s while reading %s. Is the file in BED or WIG format?" % (line_count, bedfile))
                    sys.exit(1)

                start = (start + end) // 2 - (width // 2)
                # This shifts the center, but ensures the width is identical... maybe not ideal
                if start < 0:
                    start = 0
                end = start + width
                # Keep all the other information in the bedfile if it's there
                if len(vals) > 3:
                    out.write("%s\t%s\t%s\t%s\n" % (vals[0], start, end, "\t".join(vals[3:])))
                else:
                    out.write("%s\t%s\t%s\n" % (vals[0], start, end))
        lines = f.readlines(BUFSIZE)
    
    out.close()
    f.close()
1246954
def estimategaps(args):
    
    p = OptionParser(estimategaps.__doc__)
    p.add_option("--minsize", default=100, type="int",
                 help="Minimum gap size")
    p.add_option("--maxsize", default=500000, type="int",
                 help="Maximum gap size")
    p.add_option("--links", default=10, type="int",
                 help="Only use linkage grounds with matchings more than")
    p.set_verbose(help="Print details for each gap calculation")
    opts, args = p.parse_args(args)

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

    inputbed, = args
    pf = inputbed.rsplit(".", 1)[0]
    agpfile = pf + ".chr.agp"
    bedfile = pf + ".lifted.bed"

    cc = Map(bedfile, scaffold_info=True)
    agp = AGP(agpfile)
    minsize, maxsize = opts.minsize, opts.maxsize
    links = opts.links
    verbose = opts.verbose

    outagpfile = pf + ".estimategaps.agp"
    fw = must_open(outagpfile, "w")

    for ob, components in agp.iter_object():
        components = list(components)
        s = Scaffold(ob, cc)
        mlg_counts = s.mlg_counts
        gaps = [x for x in components if x.is_gap]
        gapsizes = [None] * len(gaps)   # master
        for mlg, count in mlg_counts.items():
            if count < links:
                continue
            g = GapEstimator(cc, agp, ob, mlg)
            g.compute_all_gaps(minsize=minsize, maxsize=maxsize, \
                               verbose=verbose)
            # Merge evidence from this mlg into master
            assert len(g.gapsizes) == len(gaps)
            for i, gs in enumerate(gapsizes):
                gg = g.gapsizes[i]
                if gs is None:
                    gapsizes[i] = gg
                elif gg:
                    gapsizes[i] = min(gs, gg)

        print(gapsizes)
        # Modify AGP
        i = 0
        for x in components:
            if x.is_gap:
                x.gap_length = gapsizes[i] or minsize
                x.component_type = 'U' if x.gap_length == 100 else 'N'
                i += 1
            print(x, file=fw)

    fw.close()
    reindex([outagpfile, "--inplace"])
1249399
def compute_sizes(sizes, size_fn, scaling_factor, scaling_method, base_size):
    
    if sizes.dtype.kind not in ('i', 'f'):
        return None
    if scaling_method == 'area':
        pass
    elif scaling_method == 'width':
        scaling_factor = scaling_factor**2
    else:
        raise ValueError(
            'Invalid value for argument "scaling_method": "{}". '
            'Valid values are: "width", "area".'.format(scaling_method))
    sizes = size_fn(sizes)
    return (base_size*scaling_factor*sizes)
227037
def _check_cores_output_sizes(self):
    
    for core_sizes in zip(*tuple(_get_flat_core_sizes(self._cores))):
      first_core_list = core_sizes[0][1:]
      for i, core_list in enumerate(core_sizes[1:]):
        if core_list[1:] != first_core_list:
          raise ValueError("The outputs of the provided cores are not able "
                           "to be concatenated along the first feature "
                           "dimension. Core 0 has shape %s, whereas Core %d "
                           "has shape %s - these must only differ in the first "
                           "dimension" % (core_sizes[0], i + 1, core_list))
522731
def summary(args):
    
    from jcvi.formats.base import SetFile
    from jcvi.formats.bed import BedSummary
    from jcvi.utils.table import tabulate

    p = OptionParser(summary.__doc__)
    p.add_option("--isoform", default=False, action="store_true",
                 help="Find longest isoform of each id")
    p.add_option("--ids", help="Only include features from certain IDs")
    opts, args = p.parse_args(args)

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

    gff_file, = args
    ids = opts.ids

    if ids:
        ids = SetFile(ids)
        logging.debug("Total ids loaded: {0}".format(len(ids)))

        if opts.isoform:
            pids = set()
            gff = Gff(gff_file)
            for g in gff:
                if g.type != "mRNA":
                    continue
                if g.parent not in ids:
                    continue
                if "longest" not in g.attributes:
                    pids = set(x + ".1" for x in ids)
                    break
                if g.attributes["longest"][0] == "0":
                    continue
                pids.add(g.id)
            ids = pids
            logging.debug("After checking longest: {0}".format(len(ids)))

        # Collects aliases
        gff = Gff(gff_file)
        for g in gff:
            if g.name in ids:
                ids.add(g.id)
        logging.debug("Total ids including aliases: {0}".format(len(ids)))

    gff = Gff(gff_file)
    beds = defaultdict(list)
    for g in gff:
        if ids and not (g.id in ids or g.name in ids or g.parent in ids):
            continue

        beds[g.type].append(g.bedline)

    table = {}
    for type, bb in sorted(beds.items()):
        bs = BedSummary(bb)
        table[(type, "Features")] = bs.nfeats
        table[(type, "Unique bases")] = bs.unique_bases
        table[(type, "Total bases")] = bs.total_bases

    print(tabulate(table), file=sys.stdout)
633932
def Size(self):
        
        return s.uint8 + s.uint8 + GetVarSize(self.Attributes) + GetVarSize(self.inputs) + GetVarSize(self.outputs) + GetVarSize(self.Scripts)
302731
def sizes(self: Any) -> Mapping[Hashable, int]:
        
        return Frozen(OrderedDict(zip(self.dims, self.shape)))
901376
def __shpFileLength(self):
        """"""
        # Remember starting position
        start = self.shp.tell()
        # Calculate size of all shapes
        self.shp.seek(0,2)
        size = self.shp.tell()
        # Calculate size as 16-bit words
        size //= 2
        # Return to start
        self.shp.seek(start)
        return size
250196
def check_sizes(size, width, height):
    
    if not size:
        return width, height

    if len(size) != 2:
        raise ValueError(
          "size argument should be a pair (width, height)")
    if width is not None and width != size[0]:
        raise ValueError(
          "size[0] (%r) and width (%r) should match when both are used."
          % (size[0], width))
    if height is not None and height != size[1]:
        raise ValueError(
          "size[1] (%r) and height (%r) should match when both are used."
          % (size[1], height))
    return size
1081573
def get_size(self):
        """"""
        self.curses.setupterm()
        return self.curses.tigetnum('cols'), self.curses.tigetnum('lines')