File: bigbed.py

package info (click to toggle)
python-pybedtools 0.10.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 16,620 kB
  • sloc: python: 10,030; cpp: 899; makefile: 142; sh: 57
file content (83 lines) | stat: -rw-r--r-- 2,249 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import subprocess
import pybedtools


def bigbed(
    x,
    genome,
    output,
    blockSize=256,
    itemsPerSlot=512,
    bedtype=None,
    _as=None,
    unc=False,
    tab=False,
):
    """
    Converts a BedTool object to a bigBed format and returns the new filename.

    `x` is a BedTool object

    `genome` is an assembly string

    `output` is the name of the bigBed file to create.

    Other args are passed to bedToBigBed.  In particular, `bedtype` (which
    becomes the "-type=" argument) is automatically handled for you if it is
    kept as the default None.

    Assumes that a recent version of bedToBigBed from UCSC is on the path.
    """
    if isinstance(x, str):
        x = pybedtools.BedTool(x)
    if not isinstance(x.fn, str):
        x = x.saveas()
    chromsizes = pybedtools.chromsizes_to_file(pybedtools.chromsizes(genome))
    if bedtype is None:
        bedtype = "bed%s" % x.field_count()
    cmds = [
        "bedToBigBed",
        x.fn,
        chromsizes,
        output,
        "-blockSize=%s" % blockSize,
        "-itemsPerSlot=%s" % itemsPerSlot,
        "-type=%s" % bedtype,
    ]
    if unc:
        cmds.append("-unc")
    if tab:
        cmds.append("-tab")
    if _as:
        cmds.append("-as=%s" % _as)
    p = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if p.returncode:
        raise ValueError(
            "cmds: %s\nstderr:%s\nstdout:%s" % (" ".join(cmds), stderr, stdout)
        )

    return output


def bigbed_to_bed(fn, chrom=None, start=None, end=None, maxItems=None):
    cmds = ["bigBedToBed", fn]
    if chrom is not None:
        cmds.extend(["-chrom", chrom])
    if start is not None:
        cmds.extend(["-start", start])
    if end is not None:
        cmds.extend(["-end", end])
    if maxItems is not None:
        cmds.extend(["-maxItems", maxItems])

    outfn = pybedtools.BedTool._tmp()
    cmds.append(outfn)

    p = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if p.returncode:
        raise ValueError(
            "cmds: %s\nstderr:%s\nstdout:%s" % (" ".join(cmds), stderr, stdout)
        )
    return pybedtools.BedTool(outfn)