id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
223,500
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
BlobHandle._chunk_iter
def _chunk_iter(self): """Iterator over the blob file.""" for chunk_offset in self._chunk_offsets(): yield self._download_chunk(chunk_offset=chunk_offset, chunk_size=self._chunk_size)
python
def _chunk_iter(self): """Iterator over the blob file.""" for chunk_offset in self._chunk_offsets(): yield self._download_chunk(chunk_offset=chunk_offset, chunk_size=self._chunk_size)
[ "def", "_chunk_iter", "(", "self", ")", ":", "for", "chunk_offset", "in", "self", ".", "_chunk_offsets", "(", ")", ":", "yield", "self", ".", "_download_chunk", "(", "chunk_offset", "=", "chunk_offset", ",", "chunk_size", "=", "self", ".", "_chunk_size", ")"...
Iterator over the blob file.
[ "Iterator", "over", "the", "blob", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L172-L176
223,501
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AmazonS3.parse_remote
def parse_remote(cls, filename): """Parses a remote filename into bucket and key information. Handles S3 with optional region name specified in key: BUCKETNAME@REGIONNAME/KEY """ parts = filename.split("//")[-1].split("/", 1) bucket, key = parts if len(parts) == 2 else (parts[0], None) if bucket.find("@") > 0: bucket, region = bucket.split("@") else: region = None return cls._REMOTE_FILE("s3", bucket, key, region)
python
def parse_remote(cls, filename): """Parses a remote filename into bucket and key information. Handles S3 with optional region name specified in key: BUCKETNAME@REGIONNAME/KEY """ parts = filename.split("//")[-1].split("/", 1) bucket, key = parts if len(parts) == 2 else (parts[0], None) if bucket.find("@") > 0: bucket, region = bucket.split("@") else: region = None return cls._REMOTE_FILE("s3", bucket, key, region)
[ "def", "parse_remote", "(", "cls", ",", "filename", ")", ":", "parts", "=", "filename", ".", "split", "(", "\"//\"", ")", "[", "-", "1", "]", ".", "split", "(", "\"/\"", ",", "1", ")", "bucket", ",", "key", "=", "parts", "if", "len", "(", "parts"...
Parses a remote filename into bucket and key information. Handles S3 with optional region name specified in key: BUCKETNAME@REGIONNAME/KEY
[ "Parses", "a", "remote", "filename", "into", "bucket", "and", "key", "information", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L281-L294
223,502
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AmazonS3._cl_aws_cli
def _cl_aws_cli(cls, file_info, region): """Command line required for download using the standard AWS command line interface. """ s3file = cls._S3_FILE % {"bucket": file_info.bucket, "key": file_info.key, "region": ""} command = [os.path.join(os.path.dirname(sys.executable), "aws"), "s3", "cp", "--region", region, s3file] return (command, "awscli")
python
def _cl_aws_cli(cls, file_info, region): """Command line required for download using the standard AWS command line interface. """ s3file = cls._S3_FILE % {"bucket": file_info.bucket, "key": file_info.key, "region": ""} command = [os.path.join(os.path.dirname(sys.executable), "aws"), "s3", "cp", "--region", region, s3file] return (command, "awscli")
[ "def", "_cl_aws_cli", "(", "cls", ",", "file_info", ",", "region", ")", ":", "s3file", "=", "cls", ".", "_S3_FILE", "%", "{", "\"bucket\"", ":", "file_info", ".", "bucket", ",", "\"key\"", ":", "file_info", ".", "key", ",", "\"region\"", ":", "\"\"", "...
Command line required for download using the standard AWS command line interface.
[ "Command", "line", "required", "for", "download", "using", "the", "standard", "AWS", "command", "line", "interface", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L297-L306
223,503
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AmazonS3._cl_gof3r
def _cl_gof3r(file_info, region): """Command line required for download using gof3r.""" command = ["gof3r", "get", "--no-md5", "-k", file_info.key, "-b", file_info.bucket] if region != "us-east-1": command += ["--endpoint=s3-%s.amazonaws.com" % region] return (command, "gof3r")
python
def _cl_gof3r(file_info, region): """Command line required for download using gof3r.""" command = ["gof3r", "get", "--no-md5", "-k", file_info.key, "-b", file_info.bucket] if region != "us-east-1": command += ["--endpoint=s3-%s.amazonaws.com" % region] return (command, "gof3r")
[ "def", "_cl_gof3r", "(", "file_info", ",", "region", ")", ":", "command", "=", "[", "\"gof3r\"", ",", "\"get\"", ",", "\"--no-md5\"", ",", "\"-k\"", ",", "file_info", ".", "key", ",", "\"-b\"", ",", "file_info", ".", "bucket", "]", "if", "region", "!=", ...
Command line required for download using gof3r.
[ "Command", "line", "required", "for", "download", "using", "gof3r", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L309-L316
223,504
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AmazonS3.get_region
def get_region(cls, resource=None): """Retrieve region from standard environmental variables or file name. More information of the following link: http://goo.gl/Vb9Jky """ if resource: resource_info = cls.parse_remote(resource) if resource_info.region: return resource_info.region return os.environ.get("AWS_DEFAULT_REGION", cls._DEFAULT_REGION)
python
def get_region(cls, resource=None): """Retrieve region from standard environmental variables or file name. More information of the following link: http://goo.gl/Vb9Jky """ if resource: resource_info = cls.parse_remote(resource) if resource_info.region: return resource_info.region return os.environ.get("AWS_DEFAULT_REGION", cls._DEFAULT_REGION)
[ "def", "get_region", "(", "cls", ",", "resource", "=", "None", ")", ":", "if", "resource", ":", "resource_info", "=", "cls", ".", "parse_remote", "(", "resource", ")", "if", "resource_info", ".", "region", ":", "return", "resource_info", ".", "region", "re...
Retrieve region from standard environmental variables or file name. More information of the following link: http://goo.gl/Vb9Jky
[ "Retrieve", "region", "from", "standard", "environmental", "variables", "or", "file", "name", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L338-L349
223,505
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AmazonS3.connect
def connect(cls, resource): """Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource. """ import boto return boto.s3.connect_to_region(cls.get_region(resource))
python
def connect(cls, resource): """Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource. """ import boto return boto.s3.connect_to_region(cls.get_region(resource))
[ "def", "connect", "(", "cls", ",", "resource", ")", ":", "import", "boto", "return", "boto", ".", "s3", ".", "connect_to_region", "(", "cls", ".", "get_region", "(", "resource", ")", ")" ]
Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource.
[ "Connect", "to", "this", "Region", "s", "endpoint", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L362-L369
223,506
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AmazonS3.open
def open(cls, filename): """Return a handle like object for streaming from S3.""" import boto file_info = cls.parse_remote(filename) connection = cls.connect(filename) try: s3_bucket = connection.get_bucket(file_info.bucket) except boto.exception.S3ResponseError as error: # if we don't have bucket permissions but folder permissions, # try without validation if error.status == 403: s3_bucket = connection.get_bucket(file_info.bucket, validate=False) else: raise s3_key = s3_bucket.get_key(file_info.key) if s3_key is None: raise ValueError("Did not find S3 key: %s" % filename) return S3Handle(s3_key)
python
def open(cls, filename): """Return a handle like object for streaming from S3.""" import boto file_info = cls.parse_remote(filename) connection = cls.connect(filename) try: s3_bucket = connection.get_bucket(file_info.bucket) except boto.exception.S3ResponseError as error: # if we don't have bucket permissions but folder permissions, # try without validation if error.status == 403: s3_bucket = connection.get_bucket(file_info.bucket, validate=False) else: raise s3_key = s3_bucket.get_key(file_info.key) if s3_key is None: raise ValueError("Did not find S3 key: %s" % filename) return S3Handle(s3_key)
[ "def", "open", "(", "cls", ",", "filename", ")", ":", "import", "boto", "file_info", "=", "cls", ".", "parse_remote", "(", "filename", ")", "connection", "=", "cls", ".", "connect", "(", "filename", ")", "try", ":", "s3_bucket", "=", "connection", ".", ...
Return a handle like object for streaming from S3.
[ "Return", "a", "handle", "like", "object", "for", "streaming", "from", "S3", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L434-L453
223,507
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AzureBlob.parse_remote
def parse_remote(cls, filename): """Parses a remote filename into blob information.""" blob_file = cls._URL_FORMAT.search(filename) return cls._REMOTE_FILE("blob", storage=blob_file.group("storage"), container=blob_file.group("container"), blob=blob_file.group("blob"))
python
def parse_remote(cls, filename): """Parses a remote filename into blob information.""" blob_file = cls._URL_FORMAT.search(filename) return cls._REMOTE_FILE("blob", storage=blob_file.group("storage"), container=blob_file.group("container"), blob=blob_file.group("blob"))
[ "def", "parse_remote", "(", "cls", ",", "filename", ")", ":", "blob_file", "=", "cls", ".", "_URL_FORMAT", ".", "search", "(", "filename", ")", "return", "cls", ".", "_REMOTE_FILE", "(", "\"blob\"", ",", "storage", "=", "blob_file", ".", "group", "(", "\...
Parses a remote filename into blob information.
[ "Parses", "a", "remote", "filename", "into", "blob", "information", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L479-L485
223,508
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AzureBlob.connect
def connect(cls, resource): """Returns a connection object pointing to the endpoint associated to the received resource. """ from azure import storage as azure_storage file_info = cls.parse_remote(resource) return azure_storage.BlobService(file_info.storage)
python
def connect(cls, resource): """Returns a connection object pointing to the endpoint associated to the received resource. """ from azure import storage as azure_storage file_info = cls.parse_remote(resource) return azure_storage.BlobService(file_info.storage)
[ "def", "connect", "(", "cls", ",", "resource", ")", ":", "from", "azure", "import", "storage", "as", "azure_storage", "file_info", "=", "cls", ".", "parse_remote", "(", "resource", ")", "return", "azure_storage", ".", "BlobService", "(", "file_info", ".", "s...
Returns a connection object pointing to the endpoint associated to the received resource.
[ "Returns", "a", "connection", "object", "pointing", "to", "the", "endpoint", "associated", "to", "the", "received", "resource", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L488-L494
223,509
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
AzureBlob.open
def open(cls, filename): """Provide a handle-like object for streaming.""" file_info = cls.parse_remote(filename) blob_service = cls.connect(filename) return BlobHandle(blob_service=blob_service, container=file_info.container, blob=file_info.blob, chunk_size=cls._BLOB_CHUNK_DATA_SIZE)
python
def open(cls, filename): """Provide a handle-like object for streaming.""" file_info = cls.parse_remote(filename) blob_service = cls.connect(filename) return BlobHandle(blob_service=blob_service, container=file_info.container, blob=file_info.blob, chunk_size=cls._BLOB_CHUNK_DATA_SIZE)
[ "def", "open", "(", "cls", ",", "filename", ")", ":", "file_info", "=", "cls", ".", "parse_remote", "(", "filename", ")", "blob_service", "=", "cls", ".", "connect", "(", "filename", ")", "return", "BlobHandle", "(", "blob_service", "=", "blob_service", ",...
Provide a handle-like object for streaming.
[ "Provide", "a", "handle", "-", "like", "object", "for", "streaming", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L538-L545
223,510
bcbio/bcbio-nextgen
bcbio/bam/cram.py
compress
def compress(in_bam, data): """Compress a BAM file to CRAM, providing indexed CRAM file. Does 8 bin compression of quality score and read name removal using bamUtils squeeze if `cram` specified: http://genome.sph.umich.edu/wiki/BamUtil:_squeeze Otherwise does `cram-lossless` which only converts to CRAM. """ out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "archive")) out_file = os.path.join(out_dir, "%s.cram" % os.path.splitext(os.path.basename(in_bam))[0]) cores = dd.get_num_cores(data) ref_file = dd.get_ref_file(data) if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: compress_type = dd.get_archive(data) samtools = config_utils.get_program("samtools", data["config"]) try: bam_cmd = config_utils.get_program("bam", data["config"]) except config_utils.CmdNotFound: bam_cmd = None to_cram = ("{samtools} view -T {ref_file} -@ {cores} " "-C -x BD -x BI -o {tx_out_file}") compressed = False if "cram" in compress_type and bam_cmd: try: cmd = ("{bam_cmd} squeeze --in {in_bam} --out -.ubam --keepDups " "--binQualS=2,10,20,25,30,35,70 --binMid | " + to_cram) do.run(cmd.format(**locals()), "Compress BAM to CRAM: quality score binning") compressed = True # Retry failures avoiding using bam squeeze which can cause issues except subprocess.CalledProcessError: pass if not compressed: cmd = (to_cram + " {in_bam}") do.run(cmd.format(**locals()), "Compress BAM to CRAM: lossless") index(out_file, data["config"]) return out_file
python
def compress(in_bam, data): """Compress a BAM file to CRAM, providing indexed CRAM file. Does 8 bin compression of quality score and read name removal using bamUtils squeeze if `cram` specified: http://genome.sph.umich.edu/wiki/BamUtil:_squeeze Otherwise does `cram-lossless` which only converts to CRAM. """ out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "archive")) out_file = os.path.join(out_dir, "%s.cram" % os.path.splitext(os.path.basename(in_bam))[0]) cores = dd.get_num_cores(data) ref_file = dd.get_ref_file(data) if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: compress_type = dd.get_archive(data) samtools = config_utils.get_program("samtools", data["config"]) try: bam_cmd = config_utils.get_program("bam", data["config"]) except config_utils.CmdNotFound: bam_cmd = None to_cram = ("{samtools} view -T {ref_file} -@ {cores} " "-C -x BD -x BI -o {tx_out_file}") compressed = False if "cram" in compress_type and bam_cmd: try: cmd = ("{bam_cmd} squeeze --in {in_bam} --out -.ubam --keepDups " "--binQualS=2,10,20,25,30,35,70 --binMid | " + to_cram) do.run(cmd.format(**locals()), "Compress BAM to CRAM: quality score binning") compressed = True # Retry failures avoiding using bam squeeze which can cause issues except subprocess.CalledProcessError: pass if not compressed: cmd = (to_cram + " {in_bam}") do.run(cmd.format(**locals()), "Compress BAM to CRAM: lossless") index(out_file, data["config"]) return out_file
[ "def", "compress", "(", "in_bam", ",", "data", ")", ":", "out_dir", "=", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "dd", ".", "get_work_dir", "(", "data", ")", ",", "\"archive\"", ")", ")", "out_file", "=", "os", ".", ...
Compress a BAM file to CRAM, providing indexed CRAM file. Does 8 bin compression of quality score and read name removal using bamUtils squeeze if `cram` specified: http://genome.sph.umich.edu/wiki/BamUtil:_squeeze Otherwise does `cram-lossless` which only converts to CRAM.
[ "Compress", "a", "BAM", "file", "to", "CRAM", "providing", "indexed", "CRAM", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L14-L52
223,511
bcbio/bcbio-nextgen
bcbio/bam/cram.py
index
def index(in_cram, config): """Ensure CRAM file has a .crai index file. """ out_file = in_cram + ".crai" if not utils.file_uptodate(out_file, in_cram): with file_transaction(config, in_cram + ".crai") as tx_out_file: tx_in_file = os.path.splitext(tx_out_file)[0] utils.symlink_plus(in_cram, tx_in_file) cmd = "samtools index {tx_in_file}" do.run(cmd.format(**locals()), "Index CRAM file") return out_file
python
def index(in_cram, config): """Ensure CRAM file has a .crai index file. """ out_file = in_cram + ".crai" if not utils.file_uptodate(out_file, in_cram): with file_transaction(config, in_cram + ".crai") as tx_out_file: tx_in_file = os.path.splitext(tx_out_file)[0] utils.symlink_plus(in_cram, tx_in_file) cmd = "samtools index {tx_in_file}" do.run(cmd.format(**locals()), "Index CRAM file") return out_file
[ "def", "index", "(", "in_cram", ",", "config", ")", ":", "out_file", "=", "in_cram", "+", "\".crai\"", "if", "not", "utils", ".", "file_uptodate", "(", "out_file", ",", "in_cram", ")", ":", "with", "file_transaction", "(", "config", ",", "in_cram", "+", ...
Ensure CRAM file has a .crai index file.
[ "Ensure", "CRAM", "file", "has", "a", ".", "crai", "index", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L54-L64
223,512
bcbio/bcbio-nextgen
bcbio/bam/cram.py
to_bam
def to_bam(in_file, out_file, data): """Convert CRAM file into BAM. """ if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: cmd = ["samtools", "view", "-O", "BAM", "-o", tx_out_file, in_file] do.run(cmd, "Convert CRAM to BAM") bam.index(out_file, data["config"]) return out_file
python
def to_bam(in_file, out_file, data): """Convert CRAM file into BAM. """ if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: cmd = ["samtools", "view", "-O", "BAM", "-o", tx_out_file, in_file] do.run(cmd, "Convert CRAM to BAM") bam.index(out_file, data["config"]) return out_file
[ "def", "to_bam", "(", "in_file", ",", "out_file", ",", "data", ")", ":", "if", "not", "utils", ".", "file_uptodate", "(", "out_file", ",", "in_file", ")", ":", "with", "file_transaction", "(", "data", ",", "out_file", ")", "as", "tx_out_file", ":", "cmd"...
Convert CRAM file into BAM.
[ "Convert", "CRAM", "file", "into", "BAM", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/cram.py#L66-L74
223,513
bcbio/bcbio-nextgen
bcbio/distributed/prun.py
start
def start(parallel, items, config, dirs=None, name=None, multiplier=1, max_multicore=None): """Start a parallel cluster or machines to be used for running remote functions. Returns a function used to process, in parallel items with a given function. Allows sharing of a single cluster across multiple functions with identical resource requirements. Uses local execution for non-distributed clusters or completed jobs. A checkpoint directory keeps track of finished tasks, avoiding spinning up clusters for sections that have been previous processed. multiplier - Number of expected jobs per initial input item. Used to avoid underscheduling cores when an item is split during processing. max_multicore -- The maximum number of cores to use for each process. Can be used to process less multicore usage when jobs run faster on more single cores. """ if name: checkpoint_dir = utils.safe_makedir(os.path.join(dirs["work"], "checkpoints_parallel")) checkpoint_file = os.path.join(checkpoint_dir, "%s.done" % name) else: checkpoint_file = None sysinfo = system.get_info(dirs, parallel, config.get("resources", {})) items = [x for x in items if x is not None] if items else [] max_multicore = int(max_multicore or sysinfo.get("cores", 1)) parallel = resources.calculate(parallel, items, sysinfo, config, multiplier=multiplier, max_multicore=max_multicore) try: view = None if parallel["type"] == "ipython": if checkpoint_file and os.path.exists(checkpoint_file): logger.info("Running locally instead of distributed -- checkpoint passed: %s" % name) parallel["cores_per_job"] = 1 parallel["num_jobs"] = 1 parallel["checkpointed"] = True yield multi.runner(parallel, config) else: from bcbio.distributed import ipython with ipython.create(parallel, dirs, config) as view: yield ipython.runner(view, parallel, dirs, config) else: yield multi.runner(parallel, config) except: if view is not None: from bcbio.distributed import ipython ipython.stop(view) raise else: for x in ["cores_per_job", "num_jobs", "mem"]: parallel.pop(x, None) if checkpoint_file: with open(checkpoint_file, "w") as out_handle: out_handle.write("done\n")
python
def start(parallel, items, config, dirs=None, name=None, multiplier=1, max_multicore=None): """Start a parallel cluster or machines to be used for running remote functions. Returns a function used to process, in parallel items with a given function. Allows sharing of a single cluster across multiple functions with identical resource requirements. Uses local execution for non-distributed clusters or completed jobs. A checkpoint directory keeps track of finished tasks, avoiding spinning up clusters for sections that have been previous processed. multiplier - Number of expected jobs per initial input item. Used to avoid underscheduling cores when an item is split during processing. max_multicore -- The maximum number of cores to use for each process. Can be used to process less multicore usage when jobs run faster on more single cores. """ if name: checkpoint_dir = utils.safe_makedir(os.path.join(dirs["work"], "checkpoints_parallel")) checkpoint_file = os.path.join(checkpoint_dir, "%s.done" % name) else: checkpoint_file = None sysinfo = system.get_info(dirs, parallel, config.get("resources", {})) items = [x for x in items if x is not None] if items else [] max_multicore = int(max_multicore or sysinfo.get("cores", 1)) parallel = resources.calculate(parallel, items, sysinfo, config, multiplier=multiplier, max_multicore=max_multicore) try: view = None if parallel["type"] == "ipython": if checkpoint_file and os.path.exists(checkpoint_file): logger.info("Running locally instead of distributed -- checkpoint passed: %s" % name) parallel["cores_per_job"] = 1 parallel["num_jobs"] = 1 parallel["checkpointed"] = True yield multi.runner(parallel, config) else: from bcbio.distributed import ipython with ipython.create(parallel, dirs, config) as view: yield ipython.runner(view, parallel, dirs, config) else: yield multi.runner(parallel, config) except: if view is not None: from bcbio.distributed import ipython ipython.stop(view) raise else: for x in ["cores_per_job", "num_jobs", "mem"]: parallel.pop(x, None) if checkpoint_file: with open(checkpoint_file, "w") as out_handle: out_handle.write("done\n")
[ "def", "start", "(", "parallel", ",", "items", ",", "config", ",", "dirs", "=", "None", ",", "name", "=", "None", ",", "multiplier", "=", "1", ",", "max_multicore", "=", "None", ")", ":", "if", "name", ":", "checkpoint_dir", "=", "utils", ".", "safe_...
Start a parallel cluster or machines to be used for running remote functions. Returns a function used to process, in parallel items with a given function. Allows sharing of a single cluster across multiple functions with identical resource requirements. Uses local execution for non-distributed clusters or completed jobs. A checkpoint directory keeps track of finished tasks, avoiding spinning up clusters for sections that have been previous processed. multiplier - Number of expected jobs per initial input item. Used to avoid underscheduling cores when an item is split during processing. max_multicore -- The maximum number of cores to use for each process. Can be used to process less multicore usage when jobs run faster on more single cores.
[ "Start", "a", "parallel", "cluster", "or", "machines", "to", "be", "used", "for", "running", "remote", "functions", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/prun.py#L12-L69
223,514
bcbio/bcbio-nextgen
scripts/utils/broad_redo_analysis.py
recalibrate_quality
def recalibrate_quality(bam_file, sam_ref, dbsnp_file, picard_dir): """Recalibrate alignments with GATK and provide pdf summary. """ cl = ["picard_gatk_recalibrate.py", picard_dir, sam_ref, bam_file] if dbsnp_file: cl.append(dbsnp_file) subprocess.check_call(cl) out_file = glob.glob("%s*gatkrecal.bam" % os.path.splitext(bam_file)[0])[0] return out_file
python
def recalibrate_quality(bam_file, sam_ref, dbsnp_file, picard_dir): """Recalibrate alignments with GATK and provide pdf summary. """ cl = ["picard_gatk_recalibrate.py", picard_dir, sam_ref, bam_file] if dbsnp_file: cl.append(dbsnp_file) subprocess.check_call(cl) out_file = glob.glob("%s*gatkrecal.bam" % os.path.splitext(bam_file)[0])[0] return out_file
[ "def", "recalibrate_quality", "(", "bam_file", ",", "sam_ref", ",", "dbsnp_file", ",", "picard_dir", ")", ":", "cl", "=", "[", "\"picard_gatk_recalibrate.py\"", ",", "picard_dir", ",", "sam_ref", ",", "bam_file", "]", "if", "dbsnp_file", ":", "cl", ".", "appen...
Recalibrate alignments with GATK and provide pdf summary.
[ "Recalibrate", "alignments", "with", "GATK", "and", "provide", "pdf", "summary", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/broad_redo_analysis.py#L98-L106
223,515
bcbio/bcbio-nextgen
scripts/utils/broad_redo_analysis.py
run_genotyper
def run_genotyper(bam_file, ref_file, dbsnp_file, config_file): """Perform SNP genotyping and analysis using GATK. """ cl = ["gatk_genotyper.py", config_file, ref_file, bam_file] if dbsnp_file: cl.append(dbsnp_file) subprocess.check_call(cl)
python
def run_genotyper(bam_file, ref_file, dbsnp_file, config_file): """Perform SNP genotyping and analysis using GATK. """ cl = ["gatk_genotyper.py", config_file, ref_file, bam_file] if dbsnp_file: cl.append(dbsnp_file) subprocess.check_call(cl)
[ "def", "run_genotyper", "(", "bam_file", ",", "ref_file", ",", "dbsnp_file", ",", "config_file", ")", ":", "cl", "=", "[", "\"gatk_genotyper.py\"", ",", "config_file", ",", "ref_file", ",", "bam_file", "]", "if", "dbsnp_file", ":", "cl", ".", "append", "(", ...
Perform SNP genotyping and analysis using GATK.
[ "Perform", "SNP", "genotyping", "and", "analysis", "using", "GATK", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/broad_redo_analysis.py#L108-L114
223,516
bcbio/bcbio-nextgen
bcbio/structural/battenberg.py
_do_run
def _do_run(paired): """Perform Battenberg caling with the paired dataset. This purposely does not use a temporary directory for the output since Battenberg does smart restarts. """ work_dir = _sv_workdir(paired.tumor_data) out = _get_battenberg_out(paired, work_dir) ignore_file = os.path.join(work_dir, "ignore_chromosomes.txt") if len(_missing_files(out)) > 0: ref_file = dd.get_ref_file(paired.tumor_data) bat_datadir = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir, "battenberg")) ignore_file, gl_file = _make_ignore_file(work_dir, ref_file, ignore_file, os.path.join(bat_datadir, "impute", "impute_info.txt")) tumor_bam = paired.tumor_bam normal_bam = paired.normal_bam platform = dd.get_platform(paired.tumor_data) genome_build = paired.tumor_data["genome_build"] # scale cores to avoid over-using memory during imputation cores = max(1, int(dd.get_num_cores(paired.tumor_data) * 0.5)) gender = {"male": "XY", "female": "XX", "unknown": "L"}.get(population.get_gender(paired.tumor_data)) if gender == "L": gender_str = "-ge %s -gl %s" % (gender, gl_file) else: gender_str = "-ge %s" % (gender) r_export_cmd = utils.get_R_exports() local_sitelib = utils.R_sitelib() cmd = ("export R_LIBS_USER={local_sitelib} && {r_export_cmd} && " "battenberg.pl -t {cores} -o {work_dir} -r {ref_file}.fai " "-tb {tumor_bam} -nb {normal_bam} -e {bat_datadir}/impute/impute_info.txt " "-u {bat_datadir}/1000genomesloci -c {bat_datadir}/probloci.txt " "-ig {ignore_file} {gender_str} " "-assembly {genome_build} -species Human -platform {platform}") do.run(cmd.format(**locals()), "Battenberg CNV calling") assert len(_missing_files(out)) == 0, "Missing Battenberg output: %s" % _missing_files(out) out["plot"] = _get_battenberg_out_plots(paired, work_dir) out["ignore"] = ignore_file return out
python
def _do_run(paired): """Perform Battenberg caling with the paired dataset. This purposely does not use a temporary directory for the output since Battenberg does smart restarts. """ work_dir = _sv_workdir(paired.tumor_data) out = _get_battenberg_out(paired, work_dir) ignore_file = os.path.join(work_dir, "ignore_chromosomes.txt") if len(_missing_files(out)) > 0: ref_file = dd.get_ref_file(paired.tumor_data) bat_datadir = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir, "battenberg")) ignore_file, gl_file = _make_ignore_file(work_dir, ref_file, ignore_file, os.path.join(bat_datadir, "impute", "impute_info.txt")) tumor_bam = paired.tumor_bam normal_bam = paired.normal_bam platform = dd.get_platform(paired.tumor_data) genome_build = paired.tumor_data["genome_build"] # scale cores to avoid over-using memory during imputation cores = max(1, int(dd.get_num_cores(paired.tumor_data) * 0.5)) gender = {"male": "XY", "female": "XX", "unknown": "L"}.get(population.get_gender(paired.tumor_data)) if gender == "L": gender_str = "-ge %s -gl %s" % (gender, gl_file) else: gender_str = "-ge %s" % (gender) r_export_cmd = utils.get_R_exports() local_sitelib = utils.R_sitelib() cmd = ("export R_LIBS_USER={local_sitelib} && {r_export_cmd} && " "battenberg.pl -t {cores} -o {work_dir} -r {ref_file}.fai " "-tb {tumor_bam} -nb {normal_bam} -e {bat_datadir}/impute/impute_info.txt " "-u {bat_datadir}/1000genomesloci -c {bat_datadir}/probloci.txt " "-ig {ignore_file} {gender_str} " "-assembly {genome_build} -species Human -platform {platform}") do.run(cmd.format(**locals()), "Battenberg CNV calling") assert len(_missing_files(out)) == 0, "Missing Battenberg output: %s" % _missing_files(out) out["plot"] = _get_battenberg_out_plots(paired, work_dir) out["ignore"] = ignore_file return out
[ "def", "_do_run", "(", "paired", ")", ":", "work_dir", "=", "_sv_workdir", "(", "paired", ".", "tumor_data", ")", "out", "=", "_get_battenberg_out", "(", "paired", ",", "work_dir", ")", "ignore_file", "=", "os", ".", "path", ".", "join", "(", "work_dir", ...
Perform Battenberg caling with the paired dataset. This purposely does not use a temporary directory for the output since Battenberg does smart restarts.
[ "Perform", "Battenberg", "caling", "with", "the", "paired", "dataset", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/battenberg.py#L40-L77
223,517
bcbio/bcbio-nextgen
bcbio/structural/battenberg.py
_make_ignore_file
def _make_ignore_file(work_dir, ref_file, ignore_file, impute_file): """Create input files with chromosomes to ignore and gender loci. """ gl_file = os.path.join(work_dir, "gender_loci.txt") chroms = set([]) with open(impute_file) as in_handle: for line in in_handle: chrom = line.split()[0] chroms.add(chrom) if not chrom.startswith("chr"): chroms.add("chr%s" % chrom) with open(ignore_file, "w") as out_handle: for contig in ref.file_contigs(ref_file): if contig.name not in chroms: out_handle.write("%s\n" % contig.name) with open(gl_file, "w") as out_handle: for contig in ref.file_contigs(ref_file): if contig.name in ["Y", "chrY"]: # From https://github.com/cancerit/cgpBattenberg/blob/dev/perl/share/gender/GRCh37d5_Y.loci positions = [2934912, 4546684, 4549638, 4550107] for pos in positions: out_handle.write("%s\t%s\n" % (contig.name, pos)) return ignore_file, gl_file
python
def _make_ignore_file(work_dir, ref_file, ignore_file, impute_file): """Create input files with chromosomes to ignore and gender loci. """ gl_file = os.path.join(work_dir, "gender_loci.txt") chroms = set([]) with open(impute_file) as in_handle: for line in in_handle: chrom = line.split()[0] chroms.add(chrom) if not chrom.startswith("chr"): chroms.add("chr%s" % chrom) with open(ignore_file, "w") as out_handle: for contig in ref.file_contigs(ref_file): if contig.name not in chroms: out_handle.write("%s\n" % contig.name) with open(gl_file, "w") as out_handle: for contig in ref.file_contigs(ref_file): if contig.name in ["Y", "chrY"]: # From https://github.com/cancerit/cgpBattenberg/blob/dev/perl/share/gender/GRCh37d5_Y.loci positions = [2934912, 4546684, 4549638, 4550107] for pos in positions: out_handle.write("%s\t%s\n" % (contig.name, pos)) return ignore_file, gl_file
[ "def", "_make_ignore_file", "(", "work_dir", ",", "ref_file", ",", "ignore_file", ",", "impute_file", ")", ":", "gl_file", "=", "os", ".", "path", ".", "join", "(", "work_dir", ",", "\"gender_loci.txt\"", ")", "chroms", "=", "set", "(", "[", "]", ")", "w...
Create input files with chromosomes to ignore and gender loci.
[ "Create", "input", "files", "with", "chromosomes", "to", "ignore", "and", "gender", "loci", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/battenberg.py#L79-L101
223,518
bcbio/bcbio-nextgen
bcbio/illumina/transfer.py
copy_flowcell
def copy_flowcell(dname, fastq_dir, sample_cfile, config): """Copy required files for processing using rsync, potentially to a remote server. """ with utils.chdir(dname): reports = reduce(operator.add, [glob.glob("*.xml"), glob.glob("Data/Intensities/BaseCalls/*.xml"), glob.glob("Data/Intensities/BaseCalls/*.xsl"), glob.glob("Data/Intensities/BaseCalls/*.htm"), ["Data/Intensities/BaseCalls/Plots", "Data/reports", "Data/Status.htm", "Data/Status_Files", "InterOp"]]) run_info = reduce(operator.add, [glob.glob("run_info.yaml"), glob.glob("*.csv")]) fastq = glob.glob(os.path.join(fastq_dir.replace(dname + "/", "", 1), "*.gz")) configs = [sample_cfile.replace(dname + "/", "", 1)] include_file = os.path.join(dname, "transfer_files.txt") with open(include_file, "w") as out_handle: out_handle.write("+ */\n") for fname in configs + fastq + run_info + reports: out_handle.write("+ %s\n" % fname) out_handle.write("- *\n") # remote transfer if utils.get_in(config, ("process", "host")): dest = "%s@%s:%s" % (utils.get_in(config, ("process", "username")), utils.get_in(config, ("process", "host")), utils.get_in(config, ("process", "dir"))) # local transfer else: dest = utils.get_in(config, ("process", "dir")) cmd = ["rsync", "-akmrtv", "--include-from=%s" % include_file, dname, dest] logger.info("Copying files to analysis machine") logger.info(" ".join(cmd)) subprocess.check_call(cmd)
python
def copy_flowcell(dname, fastq_dir, sample_cfile, config): """Copy required files for processing using rsync, potentially to a remote server. """ with utils.chdir(dname): reports = reduce(operator.add, [glob.glob("*.xml"), glob.glob("Data/Intensities/BaseCalls/*.xml"), glob.glob("Data/Intensities/BaseCalls/*.xsl"), glob.glob("Data/Intensities/BaseCalls/*.htm"), ["Data/Intensities/BaseCalls/Plots", "Data/reports", "Data/Status.htm", "Data/Status_Files", "InterOp"]]) run_info = reduce(operator.add, [glob.glob("run_info.yaml"), glob.glob("*.csv")]) fastq = glob.glob(os.path.join(fastq_dir.replace(dname + "/", "", 1), "*.gz")) configs = [sample_cfile.replace(dname + "/", "", 1)] include_file = os.path.join(dname, "transfer_files.txt") with open(include_file, "w") as out_handle: out_handle.write("+ */\n") for fname in configs + fastq + run_info + reports: out_handle.write("+ %s\n" % fname) out_handle.write("- *\n") # remote transfer if utils.get_in(config, ("process", "host")): dest = "%s@%s:%s" % (utils.get_in(config, ("process", "username")), utils.get_in(config, ("process", "host")), utils.get_in(config, ("process", "dir"))) # local transfer else: dest = utils.get_in(config, ("process", "dir")) cmd = ["rsync", "-akmrtv", "--include-from=%s" % include_file, dname, dest] logger.info("Copying files to analysis machine") logger.info(" ".join(cmd)) subprocess.check_call(cmd)
[ "def", "copy_flowcell", "(", "dname", ",", "fastq_dir", ",", "sample_cfile", ",", "config", ")", ":", "with", "utils", ".", "chdir", "(", "dname", ")", ":", "reports", "=", "reduce", "(", "operator", ".", "add", ",", "[", "glob", ".", "glob", "(", "\...
Copy required files for processing using rsync, potentially to a remote server.
[ "Copy", "required", "files", "for", "processing", "using", "rsync", "potentially", "to", "a", "remote", "server", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/transfer.py#L12-L46
223,519
bcbio/bcbio-nextgen
bcbio/rnaseq/umi.py
_umis_cmd
def _umis_cmd(data): """Return umis command line argument, with correct python and locale. """ return "%s %s %s" % (utils.locale_export(), utils.get_program_python("umis"), config_utils.get_program("umis", data["config"], default="umis"))
python
def _umis_cmd(data): """Return umis command line argument, with correct python and locale. """ return "%s %s %s" % (utils.locale_export(), utils.get_program_python("umis"), config_utils.get_program("umis", data["config"], default="umis"))
[ "def", "_umis_cmd", "(", "data", ")", ":", "return", "\"%s %s %s\"", "%", "(", "utils", ".", "locale_export", "(", ")", ",", "utils", ".", "get_program_python", "(", "\"umis\"", ")", ",", "config_utils", ".", "get_program", "(", "\"umis\"", ",", "data", "[...
Return umis command line argument, with correct python and locale.
[ "Return", "umis", "command", "line", "argument", "with", "correct", "python", "and", "locale", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L119-L124
223,520
bcbio/bcbio-nextgen
bcbio/rnaseq/umi.py
demultiplex_samples
def demultiplex_samples(data): """ demultiplex a fastqtransformed FASTQ file into separate sample barcode files """ work_dir = os.path.join(dd.get_work_dir(data), "umis") sample_dir = os.path.join(work_dir, dd.get_sample_name(data)) demulti_dir = os.path.join(sample_dir, "demultiplexed") files = data["files"] if len(files) == 2: logger.error("Sample demultiplexing doesn't handle paired-end reads, but " "we can add it. Open an issue here https://github.com/bcbio/bcbio-nextgen/issues if you need this and we'll add it.") sys.exit(1) else: fq1 = files[0] # check if samples need to be demultiplexed with open_fastq(fq1) as in_handle: read = next(in_handle) if "SAMPLE_" not in read: return [[data]] bcfile = get_sample_barcodes(dd.get_sample_barcodes(data), sample_dir) demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*")) if demultiplexed: return [split_demultiplexed_sampledata(data, demultiplexed)] umis = _umis_cmd(data) cmd = ("{umis} demultiplex_samples --nedit 1 --barcodes {bcfile} " "--out_dir {tx_dir} {fq1}") msg = "Demultiplexing {fq1}." with file_transaction(data, demulti_dir) as tx_dir: do.run(cmd.format(**locals()), msg.format(**locals())) demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*")) return [split_demultiplexed_sampledata(data, demultiplexed)]
python
def demultiplex_samples(data): """ demultiplex a fastqtransformed FASTQ file into separate sample barcode files """ work_dir = os.path.join(dd.get_work_dir(data), "umis") sample_dir = os.path.join(work_dir, dd.get_sample_name(data)) demulti_dir = os.path.join(sample_dir, "demultiplexed") files = data["files"] if len(files) == 2: logger.error("Sample demultiplexing doesn't handle paired-end reads, but " "we can add it. Open an issue here https://github.com/bcbio/bcbio-nextgen/issues if you need this and we'll add it.") sys.exit(1) else: fq1 = files[0] # check if samples need to be demultiplexed with open_fastq(fq1) as in_handle: read = next(in_handle) if "SAMPLE_" not in read: return [[data]] bcfile = get_sample_barcodes(dd.get_sample_barcodes(data), sample_dir) demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*")) if demultiplexed: return [split_demultiplexed_sampledata(data, demultiplexed)] umis = _umis_cmd(data) cmd = ("{umis} demultiplex_samples --nedit 1 --barcodes {bcfile} " "--out_dir {tx_dir} {fq1}") msg = "Demultiplexing {fq1}." with file_transaction(data, demulti_dir) as tx_dir: do.run(cmd.format(**locals()), msg.format(**locals())) demultiplexed = glob.glob(os.path.join(demulti_dir, "*.fq*")) return [split_demultiplexed_sampledata(data, demultiplexed)]
[ "def", "demultiplex_samples", "(", "data", ")", ":", "work_dir", "=", "os", ".", "path", ".", "join", "(", "dd", ".", "get_work_dir", "(", "data", ")", ",", "\"umis\"", ")", "sample_dir", "=", "os", ".", "path", ".", "join", "(", "work_dir", ",", "dd...
demultiplex a fastqtransformed FASTQ file into separate sample barcode files
[ "demultiplex", "a", "fastqtransformed", "FASTQ", "file", "into", "separate", "sample", "barcode", "files" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L359-L391
223,521
bcbio/bcbio-nextgen
bcbio/rnaseq/umi.py
split_demultiplexed_sampledata
def split_demultiplexed_sampledata(data, demultiplexed): """ splits demultiplexed samples into separate entries in the global sample datadict """ datadicts = [] samplename = dd.get_sample_name(data) for fastq in demultiplexed: barcode = os.path.basename(fastq).split(".")[0] datadict = copy.deepcopy(data) datadict = dd.set_sample_name(datadict, samplename + "-" + barcode) datadict = dd.set_description(datadict, samplename + "-" + barcode) datadict["rgnames"]["rg"] = samplename + "-" + barcode datadict["name"]= ["", samplename + "-" + barcode] datadict["files"] = [fastq] datadicts.append(datadict) return datadicts
python
def split_demultiplexed_sampledata(data, demultiplexed): """ splits demultiplexed samples into separate entries in the global sample datadict """ datadicts = [] samplename = dd.get_sample_name(data) for fastq in demultiplexed: barcode = os.path.basename(fastq).split(".")[0] datadict = copy.deepcopy(data) datadict = dd.set_sample_name(datadict, samplename + "-" + barcode) datadict = dd.set_description(datadict, samplename + "-" + barcode) datadict["rgnames"]["rg"] = samplename + "-" + barcode datadict["name"]= ["", samplename + "-" + barcode] datadict["files"] = [fastq] datadicts.append(datadict) return datadicts
[ "def", "split_demultiplexed_sampledata", "(", "data", ",", "demultiplexed", ")", ":", "datadicts", "=", "[", "]", "samplename", "=", "dd", ".", "get_sample_name", "(", "data", ")", "for", "fastq", "in", "demultiplexed", ":", "barcode", "=", "os", ".", "path"...
splits demultiplexed samples into separate entries in the global sample datadict
[ "splits", "demultiplexed", "samples", "into", "separate", "entries", "in", "the", "global", "sample", "datadict" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L393-L409
223,522
bcbio/bcbio-nextgen
bcbio/rnaseq/umi.py
is_transformed
def is_transformed(fastq): """ check the first 100 reads to see if a FASTQ file has already been transformed by umis """ with open_fastq(fastq) as in_handle: for line in islice(in_handle, 400): if "UMI_" in line: return True return False
python
def is_transformed(fastq): """ check the first 100 reads to see if a FASTQ file has already been transformed by umis """ with open_fastq(fastq) as in_handle: for line in islice(in_handle, 400): if "UMI_" in line: return True return False
[ "def", "is_transformed", "(", "fastq", ")", ":", "with", "open_fastq", "(", "fastq", ")", "as", "in_handle", ":", "for", "line", "in", "islice", "(", "in_handle", ",", "400", ")", ":", "if", "\"UMI_\"", "in", "line", ":", "return", "True", "return", "F...
check the first 100 reads to see if a FASTQ file has already been transformed by umis
[ "check", "the", "first", "100", "reads", "to", "see", "if", "a", "FASTQ", "file", "has", "already", "been", "transformed", "by", "umis" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L504-L514
223,523
bcbio/bcbio-nextgen
bcbio/rnaseq/umi.py
SparseMatrix.read
def read(self, filename, rowprefix=None, colprefix=None, delim=":"): """read a sparse matrix, loading row and column name files. if specified, will add a prefix to the row or column names""" self.matrix = scipy.io.mmread(filename) with open(filename + ".rownames") as in_handle: self.rownames = [x.strip() for x in in_handle] if rowprefix: self.rownames = [rowprefix + delim + x for x in self.rownames] with open(filename + ".colnames") as in_handle: self.colnames = [x.strip() for x in in_handle] if colprefix: self.colnames = [colprefix + delim + x for x in self.colnames]
python
def read(self, filename, rowprefix=None, colprefix=None, delim=":"): """read a sparse matrix, loading row and column name files. if specified, will add a prefix to the row or column names""" self.matrix = scipy.io.mmread(filename) with open(filename + ".rownames") as in_handle: self.rownames = [x.strip() for x in in_handle] if rowprefix: self.rownames = [rowprefix + delim + x for x in self.rownames] with open(filename + ".colnames") as in_handle: self.colnames = [x.strip() for x in in_handle] if colprefix: self.colnames = [colprefix + delim + x for x in self.colnames]
[ "def", "read", "(", "self", ",", "filename", ",", "rowprefix", "=", "None", ",", "colprefix", "=", "None", ",", "delim", "=", "\":\"", ")", ":", "self", ".", "matrix", "=", "scipy", ".", "io", ".", "mmread", "(", "filename", ")", "with", "open", "(...
read a sparse matrix, loading row and column name files. if specified, will add a prefix to the row or column names
[ "read", "a", "sparse", "matrix", "loading", "row", "and", "column", "name", "files", ".", "if", "specified", "will", "add", "a", "prefix", "to", "the", "row", "or", "column", "names" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L42-L54
223,524
bcbio/bcbio-nextgen
bcbio/rnaseq/umi.py
SparseMatrix.write
def write(self, filename): """read a sparse matrix, loading row and column name files""" if file_exists(filename): return filename out_files = [filename, filename + ".rownames", filename + ".colnames"] with file_transaction(out_files) as tx_out_files: with open(tx_out_files[0], "wb") as out_handle: scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(self.matrix)) pd.Series(self.rownames).to_csv(tx_out_files[1], index=False) pd.Series(self.colnames).to_csv(tx_out_files[2], index=False) return filename
python
def write(self, filename): """read a sparse matrix, loading row and column name files""" if file_exists(filename): return filename out_files = [filename, filename + ".rownames", filename + ".colnames"] with file_transaction(out_files) as tx_out_files: with open(tx_out_files[0], "wb") as out_handle: scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(self.matrix)) pd.Series(self.rownames).to_csv(tx_out_files[1], index=False) pd.Series(self.colnames).to_csv(tx_out_files[2], index=False) return filename
[ "def", "write", "(", "self", ",", "filename", ")", ":", "if", "file_exists", "(", "filename", ")", ":", "return", "filename", "out_files", "=", "[", "filename", ",", "filename", "+", "\".rownames\"", ",", "filename", "+", "\".colnames\"", "]", "with", "fil...
read a sparse matrix, loading row and column name files
[ "read", "a", "sparse", "matrix", "loading", "row", "and", "column", "name", "files" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/umi.py#L56-L66
223,525
bcbio/bcbio-nextgen
bcbio/srna/sample.py
sample_annotation
def sample_annotation(data): """ Annotate miRNAs using miRBase database with seqbuster tool """ names = data["rgnames"]['sample'] tools = dd.get_expression_caller(data) work_dir = os.path.join(dd.get_work_dir(data), "mirbase") out_dir = os.path.join(work_dir, names) utils.safe_makedir(out_dir) out_file = op.join(out_dir, names) if dd.get_mirbase_hairpin(data): mirbase = op.abspath(op.dirname(dd.get_mirbase_hairpin(data))) if utils.file_exists(data["collapse"]): data['transcriptome_bam'] = _align(data["collapse"], dd.get_mirbase_hairpin(data), out_file, data) data['seqbuster'] = _miraligner(data["collapse"], out_file, dd.get_species(data), mirbase, data['config']) data["mirtop"] = _mirtop(data['seqbuster'], dd.get_species(data), mirbase, out_dir, data['config']) else: logger.debug("Trimmed collapsed file is empty for %s." % names) else: logger.debug("No annotation file from miRBase.") sps = dd.get_species(data) if dd.get_species(data) else "None" logger.debug("Looking for mirdeep2 database for %s" % names) if file_exists(op.join(dd.get_work_dir(data), "mirdeep2", "novel", "hairpin.fa")): data['seqbuster_novel'] = _miraligner(data["collapse"], "%s_novel" % out_file, sps, op.join(dd.get_work_dir(data), "mirdeep2", "novel"), data['config']) if "trna" in tools: data['trna'] = _mint_trna_annotation(data) data = spikein.counts_spikein(data) return [[data]]
python
def sample_annotation(data): """ Annotate miRNAs using miRBase database with seqbuster tool """ names = data["rgnames"]['sample'] tools = dd.get_expression_caller(data) work_dir = os.path.join(dd.get_work_dir(data), "mirbase") out_dir = os.path.join(work_dir, names) utils.safe_makedir(out_dir) out_file = op.join(out_dir, names) if dd.get_mirbase_hairpin(data): mirbase = op.abspath(op.dirname(dd.get_mirbase_hairpin(data))) if utils.file_exists(data["collapse"]): data['transcriptome_bam'] = _align(data["collapse"], dd.get_mirbase_hairpin(data), out_file, data) data['seqbuster'] = _miraligner(data["collapse"], out_file, dd.get_species(data), mirbase, data['config']) data["mirtop"] = _mirtop(data['seqbuster'], dd.get_species(data), mirbase, out_dir, data['config']) else: logger.debug("Trimmed collapsed file is empty for %s." % names) else: logger.debug("No annotation file from miRBase.") sps = dd.get_species(data) if dd.get_species(data) else "None" logger.debug("Looking for mirdeep2 database for %s" % names) if file_exists(op.join(dd.get_work_dir(data), "mirdeep2", "novel", "hairpin.fa")): data['seqbuster_novel'] = _miraligner(data["collapse"], "%s_novel" % out_file, sps, op.join(dd.get_work_dir(data), "mirdeep2", "novel"), data['config']) if "trna" in tools: data['trna'] = _mint_trna_annotation(data) data = spikein.counts_spikein(data) return [[data]]
[ "def", "sample_annotation", "(", "data", ")", ":", "names", "=", "data", "[", "\"rgnames\"", "]", "[", "'sample'", "]", "tools", "=", "dd", ".", "get_expression_caller", "(", "data", ")", "work_dir", "=", "os", ".", "path", ".", "join", "(", "dd", ".",...
Annotate miRNAs using miRBase database with seqbuster tool
[ "Annotate", "miRNAs", "using", "miRBase", "database", "with", "seqbuster", "tool" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L106-L149
223,526
bcbio/bcbio-nextgen
bcbio/srna/sample.py
_prepare_file
def _prepare_file(fn, out_dir): """Cut the beginning of the reads to avoid detection of miRNAs""" atropos = _get_atropos() cmd = "{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}" out_file = os.path.join(out_dir, append_stem(os.path.basename(fn), "end")) if file_exists(out_file): return out_file with file_transaction(out_file) as tx_file: do.run(cmd.format(**locals())) return out_file
python
def _prepare_file(fn, out_dir): """Cut the beginning of the reads to avoid detection of miRNAs""" atropos = _get_atropos() cmd = "{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}" out_file = os.path.join(out_dir, append_stem(os.path.basename(fn), "end")) if file_exists(out_file): return out_file with file_transaction(out_file) as tx_file: do.run(cmd.format(**locals())) return out_file
[ "def", "_prepare_file", "(", "fn", ",", "out_dir", ")", ":", "atropos", "=", "_get_atropos", "(", ")", "cmd", "=", "\"{atropos} trim --max-reads 500000 -u 22 -se {fn} -o {tx_file}\"", "out_file", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "append_st...
Cut the beginning of the reads to avoid detection of miRNAs
[ "Cut", "the", "beginning", "of", "the", "reads", "to", "avoid", "detection", "of", "miRNAs" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L151-L160
223,527
bcbio/bcbio-nextgen
bcbio/srna/sample.py
_collapse
def _collapse(in_file): """ Collpase reads into unique sequences with seqcluster """ seqcluster = op.join(utils.get_bcbio_bin(), "seqcluster") out_file = "%s.fastq" % utils.splitext_plus(append_stem(in_file, "_trimmed"))[0] out_dir = os.path.dirname(in_file) if file_exists(out_file): return out_file cmd = ("{seqcluster} collapse -o {out_dir} -f {in_file} -m 1 --min_size 16") do.run(cmd.format(**locals()), "Running seqcluster collapse in %s." % in_file) return out_file
python
def _collapse(in_file): """ Collpase reads into unique sequences with seqcluster """ seqcluster = op.join(utils.get_bcbio_bin(), "seqcluster") out_file = "%s.fastq" % utils.splitext_plus(append_stem(in_file, "_trimmed"))[0] out_dir = os.path.dirname(in_file) if file_exists(out_file): return out_file cmd = ("{seqcluster} collapse -o {out_dir} -f {in_file} -m 1 --min_size 16") do.run(cmd.format(**locals()), "Running seqcluster collapse in %s." % in_file) return out_file
[ "def", "_collapse", "(", "in_file", ")", ":", "seqcluster", "=", "op", ".", "join", "(", "utils", ".", "get_bcbio_bin", "(", ")", ",", "\"seqcluster\"", ")", "out_file", "=", "\"%s.fastq\"", "%", "utils", ".", "splitext_plus", "(", "append_stem", "(", "in_...
Collpase reads into unique sequences with seqcluster
[ "Collpase", "reads", "into", "unique", "sequences", "with", "seqcluster" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L180-L191
223,528
bcbio/bcbio-nextgen
bcbio/srna/sample.py
_summary
def _summary(in_file): """ Calculate size distribution after adapter removal """ data = Counter() out_file = in_file + "_size_stats" if file_exists(out_file): return out_file with open(in_file) as in_handle: for line in in_handle: counts = int(line.strip().split("_x")[1]) line = next(in_handle) l = len(line.strip()) next(in_handle) next(in_handle) data[l] += counts with file_transaction(out_file) as tx_out_file: with open(tx_out_file, 'w') as out_handle: for l, c in data.items(): out_handle.write("%s %s\n" % (l, c)) return out_file
python
def _summary(in_file): """ Calculate size distribution after adapter removal """ data = Counter() out_file = in_file + "_size_stats" if file_exists(out_file): return out_file with open(in_file) as in_handle: for line in in_handle: counts = int(line.strip().split("_x")[1]) line = next(in_handle) l = len(line.strip()) next(in_handle) next(in_handle) data[l] += counts with file_transaction(out_file) as tx_out_file: with open(tx_out_file, 'w') as out_handle: for l, c in data.items(): out_handle.write("%s %s\n" % (l, c)) return out_file
[ "def", "_summary", "(", "in_file", ")", ":", "data", "=", "Counter", "(", ")", "out_file", "=", "in_file", "+", "\"_size_stats\"", "if", "file_exists", "(", "out_file", ")", ":", "return", "out_file", "with", "open", "(", "in_file", ")", "as", "in_handle",...
Calculate size distribution after adapter removal
[ "Calculate", "size", "distribution", "after", "adapter", "removal" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L193-L213
223,529
bcbio/bcbio-nextgen
bcbio/srna/sample.py
_mirtop
def _mirtop(input_fn, sps, db, out_dir, config): """ Convert to GFF3 standard format """ hairpin = os.path.join(db, "hairpin.fa") gtf = os.path.join(db, "mirbase.gff3") if not file_exists(hairpin) or not file_exists(gtf): logger.warning("%s or %s are not installed. Skipping." % (hairpin, gtf)) return None out_gtf_fn = "%s.gtf" % utils.splitext_plus(os.path.basename(input_fn))[0] out_gff_fn = "%s.gff" % utils.splitext_plus(os.path.basename(input_fn))[0] export = _get_env() cmd = ("{export} mirtop gff --sps {sps} --hairpin {hairpin} " "--gtf {gtf} --format seqbuster -o {out_tx} {input_fn}") if not file_exists(os.path.join(out_dir, out_gtf_fn)) and \ not file_exists(os.path.join(out_dir, out_gff_fn)): with tx_tmpdir() as out_tx: do.run(cmd.format(**locals()), "Do miRNA annotation for %s" % input_fn) with utils.chdir(out_tx): out_fn = out_gtf_fn if utils.file_exists(out_gtf_fn) \ else out_gff_fn if utils.file_exists(out_fn): shutil.move(os.path.join(out_tx, out_fn), os.path.join(out_dir, out_fn)) out_fn = out_gtf_fn if utils.file_exists(os.path.join(out_dir, out_gtf_fn)) \ else os.path.join(out_dir, out_gff_fn) if utils.file_exists(os.path.join(out_dir, out_fn)): return os.path.join(out_dir, out_fn)
python
def _mirtop(input_fn, sps, db, out_dir, config): """ Convert to GFF3 standard format """ hairpin = os.path.join(db, "hairpin.fa") gtf = os.path.join(db, "mirbase.gff3") if not file_exists(hairpin) or not file_exists(gtf): logger.warning("%s or %s are not installed. Skipping." % (hairpin, gtf)) return None out_gtf_fn = "%s.gtf" % utils.splitext_plus(os.path.basename(input_fn))[0] out_gff_fn = "%s.gff" % utils.splitext_plus(os.path.basename(input_fn))[0] export = _get_env() cmd = ("{export} mirtop gff --sps {sps} --hairpin {hairpin} " "--gtf {gtf} --format seqbuster -o {out_tx} {input_fn}") if not file_exists(os.path.join(out_dir, out_gtf_fn)) and \ not file_exists(os.path.join(out_dir, out_gff_fn)): with tx_tmpdir() as out_tx: do.run(cmd.format(**locals()), "Do miRNA annotation for %s" % input_fn) with utils.chdir(out_tx): out_fn = out_gtf_fn if utils.file_exists(out_gtf_fn) \ else out_gff_fn if utils.file_exists(out_fn): shutil.move(os.path.join(out_tx, out_fn), os.path.join(out_dir, out_fn)) out_fn = out_gtf_fn if utils.file_exists(os.path.join(out_dir, out_gtf_fn)) \ else os.path.join(out_dir, out_gff_fn) if utils.file_exists(os.path.join(out_dir, out_fn)): return os.path.join(out_dir, out_fn)
[ "def", "_mirtop", "(", "input_fn", ",", "sps", ",", "db", ",", "out_dir", ",", "config", ")", ":", "hairpin", "=", "os", ".", "path", ".", "join", "(", "db", ",", "\"hairpin.fa\"", ")", "gtf", "=", "os", ".", "path", ".", "join", "(", "db", ",", ...
Convert to GFF3 standard format
[ "Convert", "to", "GFF3", "standard", "format" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L254-L281
223,530
bcbio/bcbio-nextgen
bcbio/srna/sample.py
_trna_annotation
def _trna_annotation(data): """ use tDRmapper to quantify tRNAs """ trna_ref = op.join(dd.get_srna_trna_file(data)) name = dd.get_sample_name(data) work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna", name)) in_file = op.basename(data["clean_fastq"]) tdrmapper = os.path.join(os.path.dirname(sys.executable), "TdrMappingScripts.pl") perl_export = utils.get_perl_exports() if not file_exists(trna_ref) or not file_exists(tdrmapper): logger.info("There is no tRNA annotation to run TdrMapper.") return work_dir out_file = op.join(work_dir, in_file + ".hq_cs.mapped") if not file_exists(out_file): with tx_tmpdir(data) as txdir: with utils.chdir(txdir): utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file)) cmd = ("{perl_export} && perl {tdrmapper} {trna_ref} {in_file}").format(**locals()) do.run(cmd, "tRNA for %s" % name) for filename in glob.glob("*mapped*"): shutil.move(filename, work_dir) return work_dir
python
def _trna_annotation(data): """ use tDRmapper to quantify tRNAs """ trna_ref = op.join(dd.get_srna_trna_file(data)) name = dd.get_sample_name(data) work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna", name)) in_file = op.basename(data["clean_fastq"]) tdrmapper = os.path.join(os.path.dirname(sys.executable), "TdrMappingScripts.pl") perl_export = utils.get_perl_exports() if not file_exists(trna_ref) or not file_exists(tdrmapper): logger.info("There is no tRNA annotation to run TdrMapper.") return work_dir out_file = op.join(work_dir, in_file + ".hq_cs.mapped") if not file_exists(out_file): with tx_tmpdir(data) as txdir: with utils.chdir(txdir): utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file)) cmd = ("{perl_export} && perl {tdrmapper} {trna_ref} {in_file}").format(**locals()) do.run(cmd, "tRNA for %s" % name) for filename in glob.glob("*mapped*"): shutil.move(filename, work_dir) return work_dir
[ "def", "_trna_annotation", "(", "data", ")", ":", "trna_ref", "=", "op", ".", "join", "(", "dd", ".", "get_srna_trna_file", "(", "data", ")", ")", "name", "=", "dd", ".", "get_sample_name", "(", "data", ")", "work_dir", "=", "utils", ".", "safe_makedir",...
use tDRmapper to quantify tRNAs
[ "use", "tDRmapper", "to", "quantify", "tRNAs" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L283-L305
223,531
bcbio/bcbio-nextgen
bcbio/srna/sample.py
_mint_trna_annotation
def _mint_trna_annotation(data): """ use MINTmap to quantify tRNAs """ trna_lookup = op.join(dd.get_srna_mint_lookup(data)) trna_space = op.join(dd.get_srna_mint_space(data)) trna_other = op.join(dd.get_srna_mint_other(data)) name = dd.get_sample_name(data) work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna_mint", name)) in_file = op.basename(data["clean_fastq"]) mintmap = os.path.realpath(os.path.join(os.path.dirname(sys.executable), "MINTmap.pl")) perl_export = utils.get_perl_exports() if not file_exists(trna_lookup) or not file_exists(mintmap): logger.info("There is no tRNA annotation to run MINTmap.") return work_dir jar_folder = os.path.join(os.path.dirname(mintmap), "MINTplates") out_file = op.join(work_dir, name + "-MINTmap_v1-exclusive-tRFs.expression.txt") if not file_exists(out_file): with tx_tmpdir(data) as txdir: with utils.chdir(txdir): utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file)) cmd = ("{perl_export} && {mintmap} -f {in_file} -p {name} " "-l {trna_lookup} -s {trna_space} -j {jar_folder} " "-o {trna_other}").format(**locals()) do.run(cmd, "tRNA for %s" % name) for filename in glob.glob("*MINTmap*"): shutil.move(filename, work_dir) return work_dir
python
def _mint_trna_annotation(data): """ use MINTmap to quantify tRNAs """ trna_lookup = op.join(dd.get_srna_mint_lookup(data)) trna_space = op.join(dd.get_srna_mint_space(data)) trna_other = op.join(dd.get_srna_mint_other(data)) name = dd.get_sample_name(data) work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "trna_mint", name)) in_file = op.basename(data["clean_fastq"]) mintmap = os.path.realpath(os.path.join(os.path.dirname(sys.executable), "MINTmap.pl")) perl_export = utils.get_perl_exports() if not file_exists(trna_lookup) or not file_exists(mintmap): logger.info("There is no tRNA annotation to run MINTmap.") return work_dir jar_folder = os.path.join(os.path.dirname(mintmap), "MINTplates") out_file = op.join(work_dir, name + "-MINTmap_v1-exclusive-tRFs.expression.txt") if not file_exists(out_file): with tx_tmpdir(data) as txdir: with utils.chdir(txdir): utils.symlink_plus(data["clean_fastq"], op.join(txdir, in_file)) cmd = ("{perl_export} && {mintmap} -f {in_file} -p {name} " "-l {trna_lookup} -s {trna_space} -j {jar_folder} " "-o {trna_other}").format(**locals()) do.run(cmd, "tRNA for %s" % name) for filename in glob.glob("*MINTmap*"): shutil.move(filename, work_dir) return work_dir
[ "def", "_mint_trna_annotation", "(", "data", ")", ":", "trna_lookup", "=", "op", ".", "join", "(", "dd", ".", "get_srna_mint_lookup", "(", "data", ")", ")", "trna_space", "=", "op", ".", "join", "(", "dd", ".", "get_srna_mint_space", "(", "data", ")", ")...
use MINTmap to quantify tRNAs
[ "use", "MINTmap", "to", "quantify", "tRNAs" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/sample.py#L307-L334
223,532
bcbio/bcbio-nextgen
bcbio/bam/fasta.py
sequence_length
def sequence_length(fasta): """ return a dict of the lengths of sequences in a fasta file """ sequences = SeqIO.parse(fasta, "fasta") records = {record.id: len(record) for record in sequences} return records
python
def sequence_length(fasta): """ return a dict of the lengths of sequences in a fasta file """ sequences = SeqIO.parse(fasta, "fasta") records = {record.id: len(record) for record in sequences} return records
[ "def", "sequence_length", "(", "fasta", ")", ":", "sequences", "=", "SeqIO", ".", "parse", "(", "fasta", ",", "\"fasta\"", ")", "records", "=", "{", "record", ".", "id", ":", "len", "(", "record", ")", "for", "record", "in", "sequences", "}", "return",...
return a dict of the lengths of sequences in a fasta file
[ "return", "a", "dict", "of", "the", "lengths", "of", "sequences", "in", "a", "fasta", "file" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fasta.py#L5-L11
223,533
bcbio/bcbio-nextgen
bcbio/bam/fasta.py
sequence_names
def sequence_names(fasta): """ return a list of the sequence IDs in a FASTA file """ sequences = SeqIO.parse(fasta, "fasta") records = [record.id for record in sequences] return records
python
def sequence_names(fasta): """ return a list of the sequence IDs in a FASTA file """ sequences = SeqIO.parse(fasta, "fasta") records = [record.id for record in sequences] return records
[ "def", "sequence_names", "(", "fasta", ")", ":", "sequences", "=", "SeqIO", ".", "parse", "(", "fasta", ",", "\"fasta\"", ")", "records", "=", "[", "record", ".", "id", "for", "record", "in", "sequences", "]", "return", "records" ]
return a list of the sequence IDs in a FASTA file
[ "return", "a", "list", "of", "the", "sequence", "IDs", "in", "a", "FASTA", "file" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fasta.py#L13-L19
223,534
bcbio/bcbio-nextgen
bcbio/srna/mirdeep.py
_prepare_inputs
def _prepare_inputs(ma_fn, bam_file, out_dir): """ Convert to fastq with counts """ fixed_fa = os.path.join(out_dir, "file_reads.fa") count_name =dict() with file_transaction(fixed_fa) as out_tx: with open(out_tx, 'w') as out_handle: with open(ma_fn) as in_handle: h = next(in_handle) for line in in_handle: cols = line.split("\t") name_with_counts = "%s_x%s" % (cols[0], sum(map(int, cols[2:]))) count_name[cols[0]] = name_with_counts out_handle.write(">%s\n%s\n" % (name_with_counts, cols[1])) fixed_bam = os.path.join(out_dir, "align.bam") bam_handle = pysam.AlignmentFile(bam_file, "rb") with pysam.AlignmentFile(fixed_bam, "wb", template=bam_handle) as out_handle: for read in bam_handle.fetch(): read.query_name = count_name[read.query_name] out_handle.write(read) return fixed_fa, fixed_bam
python
def _prepare_inputs(ma_fn, bam_file, out_dir): """ Convert to fastq with counts """ fixed_fa = os.path.join(out_dir, "file_reads.fa") count_name =dict() with file_transaction(fixed_fa) as out_tx: with open(out_tx, 'w') as out_handle: with open(ma_fn) as in_handle: h = next(in_handle) for line in in_handle: cols = line.split("\t") name_with_counts = "%s_x%s" % (cols[0], sum(map(int, cols[2:]))) count_name[cols[0]] = name_with_counts out_handle.write(">%s\n%s\n" % (name_with_counts, cols[1])) fixed_bam = os.path.join(out_dir, "align.bam") bam_handle = pysam.AlignmentFile(bam_file, "rb") with pysam.AlignmentFile(fixed_bam, "wb", template=bam_handle) as out_handle: for read in bam_handle.fetch(): read.query_name = count_name[read.query_name] out_handle.write(read) return fixed_fa, fixed_bam
[ "def", "_prepare_inputs", "(", "ma_fn", ",", "bam_file", ",", "out_dir", ")", ":", "fixed_fa", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "\"file_reads.fa\"", ")", "count_name", "=", "dict", "(", ")", "with", "file_transaction", "(", "fixed_...
Convert to fastq with counts
[ "Convert", "to", "fastq", "with", "counts" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/mirdeep.py#L52-L74
223,535
bcbio/bcbio-nextgen
bcbio/srna/mirdeep.py
_parse_novel
def _parse_novel(csv_file, sps="new"): """Create input of novel miRNAs from miRDeep2""" read = 0 seen = set() safe_makedir("novel") with open("novel/hairpin.fa", "w") as fa_handle, open("novel/miRNA.str", "w") as str_handle: with open(csv_file) as in_handle: for line in in_handle: if line.startswith("mature miRBase miRNAs detected by miRDeep2"): break if line.startswith("novel miRNAs predicted"): read = 1 line = next(in_handle) continue if read and line.strip(): cols = line.strip().split("\t") name, start, score = cols[0], cols[16], cols[1] if float(score) < 1: continue m5p, m3p, pre = cols[13], cols[14], cols[15].replace('u', 't').upper() m5p_start = cols[15].find(m5p) + 1 m3p_start = cols[15].find(m3p) + 1 m5p_end = m5p_start + len(m5p) - 1 m3p_end = m3p_start + len(m3p) - 1 if m5p in seen: continue fa_handle.write(">{sps}-{name} {start}\n{pre}\n".format(**locals())) str_handle.write(">{sps}-{name} ({score}) [{sps}-{name}-5p:{m5p_start}-{m5p_end}] [{sps}-{name}-3p:{m3p_start}-{m3p_end}]\n".format(**locals())) seen.add(m5p) return op.abspath("novel")
python
def _parse_novel(csv_file, sps="new"): """Create input of novel miRNAs from miRDeep2""" read = 0 seen = set() safe_makedir("novel") with open("novel/hairpin.fa", "w") as fa_handle, open("novel/miRNA.str", "w") as str_handle: with open(csv_file) as in_handle: for line in in_handle: if line.startswith("mature miRBase miRNAs detected by miRDeep2"): break if line.startswith("novel miRNAs predicted"): read = 1 line = next(in_handle) continue if read and line.strip(): cols = line.strip().split("\t") name, start, score = cols[0], cols[16], cols[1] if float(score) < 1: continue m5p, m3p, pre = cols[13], cols[14], cols[15].replace('u', 't').upper() m5p_start = cols[15].find(m5p) + 1 m3p_start = cols[15].find(m3p) + 1 m5p_end = m5p_start + len(m5p) - 1 m3p_end = m3p_start + len(m3p) - 1 if m5p in seen: continue fa_handle.write(">{sps}-{name} {start}\n{pre}\n".format(**locals())) str_handle.write(">{sps}-{name} ({score}) [{sps}-{name}-5p:{m5p_start}-{m5p_end}] [{sps}-{name}-3p:{m3p_start}-{m3p_end}]\n".format(**locals())) seen.add(m5p) return op.abspath("novel")
[ "def", "_parse_novel", "(", "csv_file", ",", "sps", "=", "\"new\"", ")", ":", "read", "=", "0", "seen", "=", "set", "(", ")", "safe_makedir", "(", "\"novel\"", ")", "with", "open", "(", "\"novel/hairpin.fa\"", ",", "\"w\"", ")", "as", "fa_handle", ",", ...
Create input of novel miRNAs from miRDeep2
[ "Create", "input", "of", "novel", "miRNAs", "from", "miRDeep2" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/srna/mirdeep.py#L76-L105
223,536
bcbio/bcbio-nextgen
bcbio/structural/lumpy.py
_run_smoove
def _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items): """Run lumpy-sv using smoove. """ batch = sshared.get_cur_batch(items) ext = "-%s-svs" % batch if batch else "-svs" name = "%s%s" % (dd.get_sample_name(items[0]), ext) out_file = os.path.join(work_dir, "%s-smoove.genotyped.vcf.gz" % name) sv_exclude_bed = sshared.prepare_exclude_file(items, out_file) old_out_file = os.path.join(work_dir, "%s%s-prep.vcf.gz" % (os.path.splitext(os.path.basename(items[0]["align_bam"]))[0], ext)) if utils.file_exists(old_out_file): return old_out_file, sv_exclude_bed if not utils.file_exists(out_file): with file_transaction(items[0], out_file) as tx_out_file: cores = dd.get_num_cores(items[0]) out_dir = os.path.dirname(tx_out_file) ref_file = dd.get_ref_file(items[0]) full_bams = " ".join(_prepare_smoove_bams(full_bams, sr_bams, disc_bams, items, os.path.dirname(tx_out_file))) std_excludes = ["~^GL", "~^HLA", "~_random", "~^chrUn", "~alt", "~decoy"] def _is_std_exclude(n): clean_excludes = [x.replace("~", "").replace("^", "") for x in std_excludes] return any([n.startswith(x) or n.endswith(x) for x in clean_excludes]) exclude_chrs = [c.name for c in ref.file_contigs(ref_file) if not chromhacks.is_nonalt(c.name) and not _is_std_exclude(c.name)] exclude_chrs = "--excludechroms '%s'" % ",".join(std_excludes + exclude_chrs) exclude_bed = ("--exclude %s" % sv_exclude_bed) if utils.file_exists(sv_exclude_bed) else "" tempdir = os.path.dirname(tx_out_file) cmd = ("export TMPDIR={tempdir} && " "smoove call --processes {cores} --genotype --removepr --fasta {ref_file} " "--name {name} --outdir {out_dir} " "{exclude_bed} {exclude_chrs} {full_bams}") with utils.chdir(tempdir): try: do.run(cmd.format(**locals()), "smoove lumpy calling", items[0]) except subprocess.CalledProcessError as msg: if _allowed_errors(msg): vcfutils.write_empty_vcf(tx_out_file, config=items[0]["config"], samples=[dd.get_sample_name(d) for d in items]) else: logger.exception() raise vcfutils.bgzip_and_index(out_file, items[0]["config"]) return out_file, sv_exclude_bed
python
def _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items): """Run lumpy-sv using smoove. """ batch = sshared.get_cur_batch(items) ext = "-%s-svs" % batch if batch else "-svs" name = "%s%s" % (dd.get_sample_name(items[0]), ext) out_file = os.path.join(work_dir, "%s-smoove.genotyped.vcf.gz" % name) sv_exclude_bed = sshared.prepare_exclude_file(items, out_file) old_out_file = os.path.join(work_dir, "%s%s-prep.vcf.gz" % (os.path.splitext(os.path.basename(items[0]["align_bam"]))[0], ext)) if utils.file_exists(old_out_file): return old_out_file, sv_exclude_bed if not utils.file_exists(out_file): with file_transaction(items[0], out_file) as tx_out_file: cores = dd.get_num_cores(items[0]) out_dir = os.path.dirname(tx_out_file) ref_file = dd.get_ref_file(items[0]) full_bams = " ".join(_prepare_smoove_bams(full_bams, sr_bams, disc_bams, items, os.path.dirname(tx_out_file))) std_excludes = ["~^GL", "~^HLA", "~_random", "~^chrUn", "~alt", "~decoy"] def _is_std_exclude(n): clean_excludes = [x.replace("~", "").replace("^", "") for x in std_excludes] return any([n.startswith(x) or n.endswith(x) for x in clean_excludes]) exclude_chrs = [c.name for c in ref.file_contigs(ref_file) if not chromhacks.is_nonalt(c.name) and not _is_std_exclude(c.name)] exclude_chrs = "--excludechroms '%s'" % ",".join(std_excludes + exclude_chrs) exclude_bed = ("--exclude %s" % sv_exclude_bed) if utils.file_exists(sv_exclude_bed) else "" tempdir = os.path.dirname(tx_out_file) cmd = ("export TMPDIR={tempdir} && " "smoove call --processes {cores} --genotype --removepr --fasta {ref_file} " "--name {name} --outdir {out_dir} " "{exclude_bed} {exclude_chrs} {full_bams}") with utils.chdir(tempdir): try: do.run(cmd.format(**locals()), "smoove lumpy calling", items[0]) except subprocess.CalledProcessError as msg: if _allowed_errors(msg): vcfutils.write_empty_vcf(tx_out_file, config=items[0]["config"], samples=[dd.get_sample_name(d) for d in items]) else: logger.exception() raise vcfutils.bgzip_and_index(out_file, items[0]["config"]) return out_file, sv_exclude_bed
[ "def", "_run_smoove", "(", "full_bams", ",", "sr_bams", ",", "disc_bams", ",", "work_dir", ",", "items", ")", ":", "batch", "=", "sshared", ".", "get_cur_batch", "(", "items", ")", "ext", "=", "\"-%s-svs\"", "%", "batch", "if", "batch", "else", "\"-svs\"",...
Run lumpy-sv using smoove.
[ "Run", "lumpy", "-", "sv", "using", "smoove", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L28-L71
223,537
bcbio/bcbio-nextgen
bcbio/structural/lumpy.py
_filter_by_support
def _filter_by_support(in_file, data): """Filter call file based on supporting evidence, adding FILTER annotations to VCF. Filters based on the following criteria: - Minimum read support for the call (SU = total support) - Large calls need split read evidence. """ rc_filter = ("FORMAT/SU < 4 || " "(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || " "(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || " "(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)<300)") return vfilter.cutoff_w_expression(in_file, rc_filter, data, name="ReadCountSupport", limit_regions=None)
python
def _filter_by_support(in_file, data): """Filter call file based on supporting evidence, adding FILTER annotations to VCF. Filters based on the following criteria: - Minimum read support for the call (SU = total support) - Large calls need split read evidence. """ rc_filter = ("FORMAT/SU < 4 || " "(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || " "(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || " "(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)<300)") return vfilter.cutoff_w_expression(in_file, rc_filter, data, name="ReadCountSupport", limit_regions=None)
[ "def", "_filter_by_support", "(", "in_file", ",", "data", ")", ":", "rc_filter", "=", "(", "\"FORMAT/SU < 4 || \"", "\"(FORMAT/SR == 0 && FORMAT/SU < 15 && ABS(SVLEN)>50000) || \"", "\"(FORMAT/SR == 0 && FORMAT/SU < 5 && ABS(SVLEN)<2000) || \"", "\"(FORMAT/SR == 0 && FORMAT/SU < 15 && AB...
Filter call file based on supporting evidence, adding FILTER annotations to VCF. Filters based on the following criteria: - Minimum read support for the call (SU = total support) - Large calls need split read evidence.
[ "Filter", "call", "file", "based", "on", "supporting", "evidence", "adding", "FILTER", "annotations", "to", "VCF", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L104-L116
223,538
bcbio/bcbio-nextgen
bcbio/structural/lumpy.py
_filter_by_background
def _filter_by_background(base_name, back_samples, gt_vcfs, data): """Filter base samples, marking any also present in the background. """ filtname = "InBackground" filtdoc = "Variant also present in background samples with same genotype" orig_vcf = gt_vcfs[base_name] out_file = "%s-backfilter.vcf" % (utils.splitext_plus(orig_vcf)[0]) if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"): with file_transaction(data, out_file) as tx_out_file: with utils.open_gzipsafe(orig_vcf) as in_handle: inp = vcf.Reader(in_handle, orig_vcf) inp.filters[filtname] = vcf.parser._Filter(filtname, filtdoc) with open(tx_out_file, "w") as out_handle: outp = vcf.Writer(out_handle, inp) for rec in inp: if _genotype_in_background(rec, base_name, back_samples): rec.add_filter(filtname) outp.write_record(rec) if utils.file_exists(out_file + ".gz"): out_file = out_file + ".gz" gt_vcfs[base_name] = vcfutils.bgzip_and_index(out_file, data["config"]) return gt_vcfs
python
def _filter_by_background(base_name, back_samples, gt_vcfs, data): """Filter base samples, marking any also present in the background. """ filtname = "InBackground" filtdoc = "Variant also present in background samples with same genotype" orig_vcf = gt_vcfs[base_name] out_file = "%s-backfilter.vcf" % (utils.splitext_plus(orig_vcf)[0]) if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"): with file_transaction(data, out_file) as tx_out_file: with utils.open_gzipsafe(orig_vcf) as in_handle: inp = vcf.Reader(in_handle, orig_vcf) inp.filters[filtname] = vcf.parser._Filter(filtname, filtdoc) with open(tx_out_file, "w") as out_handle: outp = vcf.Writer(out_handle, inp) for rec in inp: if _genotype_in_background(rec, base_name, back_samples): rec.add_filter(filtname) outp.write_record(rec) if utils.file_exists(out_file + ".gz"): out_file = out_file + ".gz" gt_vcfs[base_name] = vcfutils.bgzip_and_index(out_file, data["config"]) return gt_vcfs
[ "def", "_filter_by_background", "(", "base_name", ",", "back_samples", ",", "gt_vcfs", ",", "data", ")", ":", "filtname", "=", "\"InBackground\"", "filtdoc", "=", "\"Variant also present in background samples with same genotype\"", "orig_vcf", "=", "gt_vcfs", "[", "base_n...
Filter base samples, marking any also present in the background.
[ "Filter", "base", "samples", "marking", "any", "also", "present", "in", "the", "background", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L118-L139
223,539
bcbio/bcbio-nextgen
bcbio/structural/lumpy.py
_genotype_in_background
def _genotype_in_background(rec, base_name, back_samples): """Check if the genotype in the record of interest is present in the background records. """ def passes(rec): return not rec.FILTER or len(rec.FILTER) == 0 return (passes(rec) and any(rec.genotype(base_name).gt_alleles == rec.genotype(back_name).gt_alleles for back_name in back_samples))
python
def _genotype_in_background(rec, base_name, back_samples): """Check if the genotype in the record of interest is present in the background records. """ def passes(rec): return not rec.FILTER or len(rec.FILTER) == 0 return (passes(rec) and any(rec.genotype(base_name).gt_alleles == rec.genotype(back_name).gt_alleles for back_name in back_samples))
[ "def", "_genotype_in_background", "(", "rec", ",", "base_name", ",", "back_samples", ")", ":", "def", "passes", "(", "rec", ")", ":", "return", "not", "rec", ".", "FILTER", "or", "len", "(", "rec", ".", "FILTER", ")", "==", "0", "return", "(", "passes"...
Check if the genotype in the record of interest is present in the background records.
[ "Check", "if", "the", "genotype", "in", "the", "record", "of", "interest", "is", "present", "in", "the", "background", "records", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L141-L148
223,540
bcbio/bcbio-nextgen
bcbio/structural/lumpy.py
run
def run(items): """Perform detection of structural variations with lumpy. """ paired = vcfutils.get_paired(items) work_dir = _sv_workdir(paired.tumor_data if paired and paired.tumor_data else items[0]) previous_evidence = {} full_bams, sr_bams, disc_bams = [], [], [] for data in items: full_bams.append(dd.get_align_bam(data)) sr_bam, disc_bam = sshared.find_existing_split_discordants(data) sr_bams.append(sr_bam) disc_bams.append(disc_bam) cur_dels, cur_dups = _bedpes_from_cnv_caller(data, work_dir) previous_evidence[dd.get_sample_name(data)] = {} if cur_dels and utils.file_exists(cur_dels): previous_evidence[dd.get_sample_name(data)]["dels"] = cur_dels if cur_dups and utils.file_exists(cur_dups): previous_evidence[dd.get_sample_name(data)]["dups"] = cur_dups lumpy_vcf, exclude_file = _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items) lumpy_vcf = sshared.annotate_with_depth(lumpy_vcf, items) gt_vcfs = {} # Retain paired samples with tumor/normal genotyped in one file if paired and paired.normal_name: batches = [[paired.tumor_data, paired.normal_data]] else: batches = [[x] for x in items] for batch_items in batches: for data in batch_items: gt_vcfs[dd.get_sample_name(data)] = _filter_by_support(lumpy_vcf, data) if paired and paired.normal_name: gt_vcfs = _filter_by_background(paired.tumor_name, [paired.normal_name], gt_vcfs, paired.tumor_data) out = [] upload_counts = collections.defaultdict(int) for data in items: if "sv" not in data: data["sv"] = [] vcf_file = gt_vcfs.get(dd.get_sample_name(data)) if vcf_file: effects_vcf, _ = effects.add_to_vcf(vcf_file, data, "snpeff") data["sv"].append({"variantcaller": "lumpy", "vrn_file": effects_vcf or vcf_file, "do_upload": upload_counts[vcf_file] == 0, # only upload a single file per batch "exclude_file": exclude_file}) upload_counts[vcf_file] += 1 out.append(data) return out
python
def run(items): """Perform detection of structural variations with lumpy. """ paired = vcfutils.get_paired(items) work_dir = _sv_workdir(paired.tumor_data if paired and paired.tumor_data else items[0]) previous_evidence = {} full_bams, sr_bams, disc_bams = [], [], [] for data in items: full_bams.append(dd.get_align_bam(data)) sr_bam, disc_bam = sshared.find_existing_split_discordants(data) sr_bams.append(sr_bam) disc_bams.append(disc_bam) cur_dels, cur_dups = _bedpes_from_cnv_caller(data, work_dir) previous_evidence[dd.get_sample_name(data)] = {} if cur_dels and utils.file_exists(cur_dels): previous_evidence[dd.get_sample_name(data)]["dels"] = cur_dels if cur_dups and utils.file_exists(cur_dups): previous_evidence[dd.get_sample_name(data)]["dups"] = cur_dups lumpy_vcf, exclude_file = _run_smoove(full_bams, sr_bams, disc_bams, work_dir, items) lumpy_vcf = sshared.annotate_with_depth(lumpy_vcf, items) gt_vcfs = {} # Retain paired samples with tumor/normal genotyped in one file if paired and paired.normal_name: batches = [[paired.tumor_data, paired.normal_data]] else: batches = [[x] for x in items] for batch_items in batches: for data in batch_items: gt_vcfs[dd.get_sample_name(data)] = _filter_by_support(lumpy_vcf, data) if paired and paired.normal_name: gt_vcfs = _filter_by_background(paired.tumor_name, [paired.normal_name], gt_vcfs, paired.tumor_data) out = [] upload_counts = collections.defaultdict(int) for data in items: if "sv" not in data: data["sv"] = [] vcf_file = gt_vcfs.get(dd.get_sample_name(data)) if vcf_file: effects_vcf, _ = effects.add_to_vcf(vcf_file, data, "snpeff") data["sv"].append({"variantcaller": "lumpy", "vrn_file": effects_vcf or vcf_file, "do_upload": upload_counts[vcf_file] == 0, # only upload a single file per batch "exclude_file": exclude_file}) upload_counts[vcf_file] += 1 out.append(data) return out
[ "def", "run", "(", "items", ")", ":", "paired", "=", "vcfutils", ".", "get_paired", "(", "items", ")", "work_dir", "=", "_sv_workdir", "(", "paired", ".", "tumor_data", "if", "paired", "and", "paired", ".", "tumor_data", "else", "items", "[", "0", "]", ...
Perform detection of structural variations with lumpy.
[ "Perform", "detection", "of", "structural", "variations", "with", "lumpy", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L154-L200
223,541
bcbio/bcbio-nextgen
bcbio/structural/lumpy.py
_bedpes_from_cnv_caller
def _bedpes_from_cnv_caller(data, work_dir): """Retrieve BEDPEs deletion and duplications from CNV callers. Currently integrates with CNVkit. """ supported = set(["cnvkit"]) cns_file = None for sv in data.get("sv", []): if sv["variantcaller"] in supported and "cns" in sv and "lumpy_usecnv" in dd.get_tools_on(data): cns_file = sv["cns"] break if not cns_file: return None, None else: out_base = os.path.join(work_dir, utils.splitext_plus(os.path.basename(cns_file))[0]) out_dels = out_base + "-dels.bedpe" out_dups = out_base + "-dups.bedpe" if not os.path.exists(out_dels) or not os.path.exists(out_dups): with file_transaction(data, out_dels, out_dups) as (tx_out_dels, tx_out_dups): try: cnvanator_path = config_utils.get_program("cnvanator_to_bedpes.py", data) except config_utils.CmdNotFound: return None, None cmd = [cnvanator_path, "-c", cns_file, "--cnvkit", "--del_o=%s" % tx_out_dels, "--dup_o=%s" % tx_out_dups, "-b", "250"] # XXX Uses default piece size for CNVkit. Right approach? do.run(cmd, "Prepare CNVkit as input for lumpy", data) return out_dels, out_dups
python
def _bedpes_from_cnv_caller(data, work_dir): """Retrieve BEDPEs deletion and duplications from CNV callers. Currently integrates with CNVkit. """ supported = set(["cnvkit"]) cns_file = None for sv in data.get("sv", []): if sv["variantcaller"] in supported and "cns" in sv and "lumpy_usecnv" in dd.get_tools_on(data): cns_file = sv["cns"] break if not cns_file: return None, None else: out_base = os.path.join(work_dir, utils.splitext_plus(os.path.basename(cns_file))[0]) out_dels = out_base + "-dels.bedpe" out_dups = out_base + "-dups.bedpe" if not os.path.exists(out_dels) or not os.path.exists(out_dups): with file_transaction(data, out_dels, out_dups) as (tx_out_dels, tx_out_dups): try: cnvanator_path = config_utils.get_program("cnvanator_to_bedpes.py", data) except config_utils.CmdNotFound: return None, None cmd = [cnvanator_path, "-c", cns_file, "--cnvkit", "--del_o=%s" % tx_out_dels, "--dup_o=%s" % tx_out_dups, "-b", "250"] # XXX Uses default piece size for CNVkit. Right approach? do.run(cmd, "Prepare CNVkit as input for lumpy", data) return out_dels, out_dups
[ "def", "_bedpes_from_cnv_caller", "(", "data", ",", "work_dir", ")", ":", "supported", "=", "set", "(", "[", "\"cnvkit\"", "]", ")", "cns_file", "=", "None", "for", "sv", "in", "data", ".", "get", "(", "\"sv\"", ",", "[", "]", ")", ":", "if", "sv", ...
Retrieve BEDPEs deletion and duplications from CNV callers. Currently integrates with CNVkit.
[ "Retrieve", "BEDPEs", "deletion", "and", "duplications", "from", "CNV", "callers", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/lumpy.py#L202-L229
223,542
bcbio/bcbio-nextgen
bcbio/setpath.py
_prepend
def _prepend(original, to_prepend): """Prepend paths in a string representing a list of paths to another. original and to_prepend are expected to be strings representing os.pathsep-separated lists of filepaths. If to_prepend is None, original is returned. The list of paths represented in the returned value consists of the first of occurrences of each non-empty path in the list obtained by prepending the paths in to_prepend to the paths in original. examples: # Unix _prepend('/b:/d:/a:/d', '/a:/b:/c:/a') -> '/a:/b:/c:/d' _prepend('/a:/b:/a', '/a:/c:/c') -> '/a:/c:/b' _prepend('/c', '/a::/b:/a') -> '/a:/b:/c' _prepend('/a:/b:/a', None) -> '/a:/b:/a' _prepend('/a:/b:/a', '') -> '/a:/b' """ if to_prepend is None: return original sep = os.pathsep def split_path_value(path_value): return [] if path_value == '' else path_value.split(sep) seen = set() components = [] for path in split_path_value(to_prepend) + split_path_value(original): if path not in seen and path != '': components.append(path) seen.add(path) return sep.join(components)
python
def _prepend(original, to_prepend): """Prepend paths in a string representing a list of paths to another. original and to_prepend are expected to be strings representing os.pathsep-separated lists of filepaths. If to_prepend is None, original is returned. The list of paths represented in the returned value consists of the first of occurrences of each non-empty path in the list obtained by prepending the paths in to_prepend to the paths in original. examples: # Unix _prepend('/b:/d:/a:/d', '/a:/b:/c:/a') -> '/a:/b:/c:/d' _prepend('/a:/b:/a', '/a:/c:/c') -> '/a:/c:/b' _prepend('/c', '/a::/b:/a') -> '/a:/b:/c' _prepend('/a:/b:/a', None) -> '/a:/b:/a' _prepend('/a:/b:/a', '') -> '/a:/b' """ if to_prepend is None: return original sep = os.pathsep def split_path_value(path_value): return [] if path_value == '' else path_value.split(sep) seen = set() components = [] for path in split_path_value(to_prepend) + split_path_value(original): if path not in seen and path != '': components.append(path) seen.add(path) return sep.join(components)
[ "def", "_prepend", "(", "original", ",", "to_prepend", ")", ":", "if", "to_prepend", "is", "None", ":", "return", "original", "sep", "=", "os", ".", "pathsep", "def", "split_path_value", "(", "path_value", ")", ":", "return", "[", "]", "if", "path_value", ...
Prepend paths in a string representing a list of paths to another. original and to_prepend are expected to be strings representing os.pathsep-separated lists of filepaths. If to_prepend is None, original is returned. The list of paths represented in the returned value consists of the first of occurrences of each non-empty path in the list obtained by prepending the paths in to_prepend to the paths in original. examples: # Unix _prepend('/b:/d:/a:/d', '/a:/b:/c:/a') -> '/a:/b:/c:/d' _prepend('/a:/b:/a', '/a:/c:/c') -> '/a:/c:/b' _prepend('/c', '/a::/b:/a') -> '/a:/b:/c' _prepend('/a:/b:/a', None) -> '/a:/b:/a' _prepend('/a:/b:/a', '') -> '/a:/b'
[ "Prepend", "paths", "in", "a", "string", "representing", "a", "list", "of", "paths", "to", "another", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/setpath.py#L10-L48
223,543
bcbio/bcbio-nextgen
bcbio/setpath.py
remove_bcbiopath
def remove_bcbiopath(): """Remove bcbio internal path from first element in PATH. Useful when we need to access remote programs, like Java 7 for older installations. """ to_remove = os.environ.get("BCBIOPATH", utils.get_bcbio_bin()) + ":" if os.environ["PATH"].startswith(to_remove): os.environ["PATH"] = os.environ["PATH"][len(to_remove):]
python
def remove_bcbiopath(): """Remove bcbio internal path from first element in PATH. Useful when we need to access remote programs, like Java 7 for older installations. """ to_remove = os.environ.get("BCBIOPATH", utils.get_bcbio_bin()) + ":" if os.environ["PATH"].startswith(to_remove): os.environ["PATH"] = os.environ["PATH"][len(to_remove):]
[ "def", "remove_bcbiopath", "(", ")", ":", "to_remove", "=", "os", ".", "environ", ".", "get", "(", "\"BCBIOPATH\"", ",", "utils", ".", "get_bcbio_bin", "(", ")", ")", "+", "\":\"", "if", "os", ".", "environ", "[", "\"PATH\"", "]", ".", "startswith", "(...
Remove bcbio internal path from first element in PATH. Useful when we need to access remote programs, like Java 7 for older installations.
[ "Remove", "bcbio", "internal", "path", "from", "first", "element", "in", "PATH", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/setpath.py#L64-L72
223,544
bcbio/bcbio-nextgen
bcbio/structural/regions.py
calculate_sv_bins
def calculate_sv_bins(*items): """Determine bin sizes and regions to use for samples. Unified approach to prepare regional bins for coverage calculations across multiple CNV callers. Splits into target and antitarget regions allowing callers to take advantage of both. Provides consistent target/anti-target bin sizes across batches. Uses callable_regions as the access BED file and mosdepth regions in variant_regions to estimate depth for bin sizes. """ calcfns = {"cnvkit": _calculate_sv_bins_cnvkit, "gatk-cnv": _calculate_sv_bins_gatk} from bcbio.structural import cnvkit items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)] if all(not cnvkit.use_general_sv_bins(x) for x in items): return [[d] for d in items] out = [] for i, cnv_group in enumerate(_group_by_cnv_method(multi.group_by_batch(items, False))): size_calc_fn = MemoizedSizes(cnv_group.region_file, cnv_group.items).get_target_antitarget_bin_sizes for data in cnv_group.items: if cnvkit.use_general_sv_bins(data): target_bed, anti_bed, gcannotated_tsv = calcfns[cnvkit.bin_approach(data)](data, cnv_group, size_calc_fn) if not data.get("regions"): data["regions"] = {} data["regions"]["bins"] = {"target": target_bed, "antitarget": anti_bed, "group": str(i), "gcannotated": gcannotated_tsv} out.append([data]) if not len(out) == len(items): raise AssertionError("Inconsistent samples in and out of SV bin calculation:\nout: %s\nin : %s" % (sorted([dd.get_sample_name(utils.to_single_data(x)) for x in out]), sorted([dd.get_sample_name(x) for x in items]))) return out
python
def calculate_sv_bins(*items): """Determine bin sizes and regions to use for samples. Unified approach to prepare regional bins for coverage calculations across multiple CNV callers. Splits into target and antitarget regions allowing callers to take advantage of both. Provides consistent target/anti-target bin sizes across batches. Uses callable_regions as the access BED file and mosdepth regions in variant_regions to estimate depth for bin sizes. """ calcfns = {"cnvkit": _calculate_sv_bins_cnvkit, "gatk-cnv": _calculate_sv_bins_gatk} from bcbio.structural import cnvkit items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)] if all(not cnvkit.use_general_sv_bins(x) for x in items): return [[d] for d in items] out = [] for i, cnv_group in enumerate(_group_by_cnv_method(multi.group_by_batch(items, False))): size_calc_fn = MemoizedSizes(cnv_group.region_file, cnv_group.items).get_target_antitarget_bin_sizes for data in cnv_group.items: if cnvkit.use_general_sv_bins(data): target_bed, anti_bed, gcannotated_tsv = calcfns[cnvkit.bin_approach(data)](data, cnv_group, size_calc_fn) if not data.get("regions"): data["regions"] = {} data["regions"]["bins"] = {"target": target_bed, "antitarget": anti_bed, "group": str(i), "gcannotated": gcannotated_tsv} out.append([data]) if not len(out) == len(items): raise AssertionError("Inconsistent samples in and out of SV bin calculation:\nout: %s\nin : %s" % (sorted([dd.get_sample_name(utils.to_single_data(x)) for x in out]), sorted([dd.get_sample_name(x) for x in items]))) return out
[ "def", "calculate_sv_bins", "(", "*", "items", ")", ":", "calcfns", "=", "{", "\"cnvkit\"", ":", "_calculate_sv_bins_cnvkit", ",", "\"gatk-cnv\"", ":", "_calculate_sv_bins_gatk", "}", "from", "bcbio", ".", "structural", "import", "cnvkit", "items", "=", "[", "ut...
Determine bin sizes and regions to use for samples. Unified approach to prepare regional bins for coverage calculations across multiple CNV callers. Splits into target and antitarget regions allowing callers to take advantage of both. Provides consistent target/anti-target bin sizes across batches. Uses callable_regions as the access BED file and mosdepth regions in variant_regions to estimate depth for bin sizes.
[ "Determine", "bin", "sizes", "and", "regions", "to", "use", "for", "samples", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L27-L59
223,545
bcbio/bcbio-nextgen
bcbio/structural/regions.py
_calculate_sv_bins_gatk
def _calculate_sv_bins_gatk(data, cnv_group, size_calc_fn): """Calculate structural variant bins using GATK4 CNV callers region or even intervals approach. """ if dd.get_background_cnv_reference(data, "gatk-cnv"): target_bed = gatkcnv.pon_to_bed(dd.get_background_cnv_reference(data, "gatk-cnv"), cnv_group.work_dir, data) else: target_bed = gatkcnv.prepare_intervals(data, cnv_group.region_file, cnv_group.work_dir) gc_annotated_tsv = gatkcnv.annotate_intervals(target_bed, data) return target_bed, None, gc_annotated_tsv
python
def _calculate_sv_bins_gatk(data, cnv_group, size_calc_fn): """Calculate structural variant bins using GATK4 CNV callers region or even intervals approach. """ if dd.get_background_cnv_reference(data, "gatk-cnv"): target_bed = gatkcnv.pon_to_bed(dd.get_background_cnv_reference(data, "gatk-cnv"), cnv_group.work_dir, data) else: target_bed = gatkcnv.prepare_intervals(data, cnv_group.region_file, cnv_group.work_dir) gc_annotated_tsv = gatkcnv.annotate_intervals(target_bed, data) return target_bed, None, gc_annotated_tsv
[ "def", "_calculate_sv_bins_gatk", "(", "data", ",", "cnv_group", ",", "size_calc_fn", ")", ":", "if", "dd", ".", "get_background_cnv_reference", "(", "data", ",", "\"gatk-cnv\"", ")", ":", "target_bed", "=", "gatkcnv", ".", "pon_to_bed", "(", "dd", ".", "get_b...
Calculate structural variant bins using GATK4 CNV callers region or even intervals approach.
[ "Calculate", "structural", "variant", "bins", "using", "GATK4", "CNV", "callers", "region", "or", "even", "intervals", "approach", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L61-L69
223,546
bcbio/bcbio-nextgen
bcbio/structural/regions.py
calculate_sv_coverage
def calculate_sv_coverage(data): """Calculate coverage within bins for downstream CNV calling. Creates corrected cnr files with log2 ratios and depths. """ calcfns = {"cnvkit": _calculate_sv_coverage_cnvkit, "gatk-cnv": _calculate_sv_coverage_gatk} from bcbio.structural import cnvkit data = utils.to_single_data(data) if not cnvkit.use_general_sv_bins(data): out_target_file, out_anti_file = (None, None) else: work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", dd.get_sample_name(data), "bins")) out_target_file, out_anti_file = calcfns[cnvkit.bin_approach(data)](data, work_dir) if not os.path.exists(out_target_file): out_target_file, out_anti_file = (None, None) if "seq2c" in dd.get_svcaller(data): from bcbio.structural import seq2c seq2c_target = seq2c.precall(data) else: seq2c_target = None if not tz.get_in(["depth", "bins"], data): data = tz.update_in(data, ["depth", "bins"], lambda x: {}) data["depth"]["bins"] = {"target": out_target_file, "antitarget": out_anti_file, "seq2c": seq2c_target} return [[data]]
python
def calculate_sv_coverage(data): """Calculate coverage within bins for downstream CNV calling. Creates corrected cnr files with log2 ratios and depths. """ calcfns = {"cnvkit": _calculate_sv_coverage_cnvkit, "gatk-cnv": _calculate_sv_coverage_gatk} from bcbio.structural import cnvkit data = utils.to_single_data(data) if not cnvkit.use_general_sv_bins(data): out_target_file, out_anti_file = (None, None) else: work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", dd.get_sample_name(data), "bins")) out_target_file, out_anti_file = calcfns[cnvkit.bin_approach(data)](data, work_dir) if not os.path.exists(out_target_file): out_target_file, out_anti_file = (None, None) if "seq2c" in dd.get_svcaller(data): from bcbio.structural import seq2c seq2c_target = seq2c.precall(data) else: seq2c_target = None if not tz.get_in(["depth", "bins"], data): data = tz.update_in(data, ["depth", "bins"], lambda x: {}) data["depth"]["bins"] = {"target": out_target_file, "antitarget": out_anti_file, "seq2c": seq2c_target} return [[data]]
[ "def", "calculate_sv_coverage", "(", "data", ")", ":", "calcfns", "=", "{", "\"cnvkit\"", ":", "_calculate_sv_coverage_cnvkit", ",", "\"gatk-cnv\"", ":", "_calculate_sv_coverage_gatk", "}", "from", "bcbio", ".", "structural", "import", "cnvkit", "data", "=", "utils"...
Calculate coverage within bins for downstream CNV calling. Creates corrected cnr files with log2 ratios and depths.
[ "Calculate", "coverage", "within", "bins", "for", "downstream", "CNV", "calling", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L168-L193
223,547
bcbio/bcbio-nextgen
bcbio/structural/regions.py
_calculate_sv_coverage_gatk
def _calculate_sv_coverage_gatk(data, work_dir): """Calculate coverage in defined regions using GATK tools TODO: This does double calculations to get GATK4 compatible HDF read counts and then depth and gene annotations. Both are needed for creating heterogeneity inputs. Ideally replace with a single mosdepth coverage calculation, and creat GATK4 TSV format: CONTIG START END COUNT chrM 1 1000 13268 """ from bcbio.variation import coverage from bcbio.structural import annotate # GATK compatible target_file = gatkcnv.collect_read_counts(data, work_dir) # heterogeneity compatible target_in = bedutils.clean_file(tz.get_in(["regions", "bins", "target"], data), data, bedprep_dir=work_dir) target_cov = coverage.run_mosdepth(data, "target-gatk", target_in) target_cov_genes = annotate.add_genes(target_cov.regions, data, max_distance=0) return target_file, target_cov_genes
python
def _calculate_sv_coverage_gatk(data, work_dir): """Calculate coverage in defined regions using GATK tools TODO: This does double calculations to get GATK4 compatible HDF read counts and then depth and gene annotations. Both are needed for creating heterogeneity inputs. Ideally replace with a single mosdepth coverage calculation, and creat GATK4 TSV format: CONTIG START END COUNT chrM 1 1000 13268 """ from bcbio.variation import coverage from bcbio.structural import annotate # GATK compatible target_file = gatkcnv.collect_read_counts(data, work_dir) # heterogeneity compatible target_in = bedutils.clean_file(tz.get_in(["regions", "bins", "target"], data), data, bedprep_dir=work_dir) target_cov = coverage.run_mosdepth(data, "target-gatk", target_in) target_cov_genes = annotate.add_genes(target_cov.regions, data, max_distance=0) return target_file, target_cov_genes
[ "def", "_calculate_sv_coverage_gatk", "(", "data", ",", "work_dir", ")", ":", "from", "bcbio", ".", "variation", "import", "coverage", "from", "bcbio", ".", "structural", "import", "annotate", "# GATK compatible", "target_file", "=", "gatkcnv", ".", "collect_read_co...
Calculate coverage in defined regions using GATK tools TODO: This does double calculations to get GATK4 compatible HDF read counts and then depth and gene annotations. Both are needed for creating heterogeneity inputs. Ideally replace with a single mosdepth coverage calculation, and creat GATK4 TSV format: CONTIG START END COUNT chrM 1 1000 13268
[ "Calculate", "coverage", "in", "defined", "regions", "using", "GATK", "tools" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L195-L213
223,548
bcbio/bcbio-nextgen
bcbio/structural/regions.py
_calculate_sv_coverage_cnvkit
def _calculate_sv_coverage_cnvkit(data, work_dir): """Calculate coverage in an CNVkit ready format using mosdepth. """ from bcbio.variation import coverage from bcbio.structural import annotate out_target_file = os.path.join(work_dir, "%s-target-coverage.cnn" % dd.get_sample_name(data)) out_anti_file = os.path.join(work_dir, "%s-antitarget-coverage.cnn" % dd.get_sample_name(data)) if ((not utils.file_exists(out_target_file) or not utils.file_exists(out_anti_file)) and (dd.get_align_bam(data) or dd.get_work_bam(data))): target_cov = coverage.run_mosdepth(data, "target", tz.get_in(["regions", "bins", "target"], data)) anti_cov = coverage.run_mosdepth(data, "antitarget", tz.get_in(["regions", "bins", "antitarget"], data)) target_cov_genes = annotate.add_genes(target_cov.regions, data, max_distance=0) out_target_file = _add_log2_depth(target_cov_genes, out_target_file, data) out_anti_file = _add_log2_depth(anti_cov.regions, out_anti_file, data) return out_target_file, out_anti_file
python
def _calculate_sv_coverage_cnvkit(data, work_dir): """Calculate coverage in an CNVkit ready format using mosdepth. """ from bcbio.variation import coverage from bcbio.structural import annotate out_target_file = os.path.join(work_dir, "%s-target-coverage.cnn" % dd.get_sample_name(data)) out_anti_file = os.path.join(work_dir, "%s-antitarget-coverage.cnn" % dd.get_sample_name(data)) if ((not utils.file_exists(out_target_file) or not utils.file_exists(out_anti_file)) and (dd.get_align_bam(data) or dd.get_work_bam(data))): target_cov = coverage.run_mosdepth(data, "target", tz.get_in(["regions", "bins", "target"], data)) anti_cov = coverage.run_mosdepth(data, "antitarget", tz.get_in(["regions", "bins", "antitarget"], data)) target_cov_genes = annotate.add_genes(target_cov.regions, data, max_distance=0) out_target_file = _add_log2_depth(target_cov_genes, out_target_file, data) out_anti_file = _add_log2_depth(anti_cov.regions, out_anti_file, data) return out_target_file, out_anti_file
[ "def", "_calculate_sv_coverage_cnvkit", "(", "data", ",", "work_dir", ")", ":", "from", "bcbio", ".", "variation", "import", "coverage", "from", "bcbio", ".", "structural", "import", "annotate", "out_target_file", "=", "os", ".", "path", ".", "join", "(", "wor...
Calculate coverage in an CNVkit ready format using mosdepth.
[ "Calculate", "coverage", "in", "an", "CNVkit", "ready", "format", "using", "mosdepth", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L215-L229
223,549
bcbio/bcbio-nextgen
bcbio/structural/regions.py
normalize_sv_coverage
def normalize_sv_coverage(*items): """Normalize CNV coverage, providing flexible point for multiple methods. """ calcfns = {"cnvkit": _normalize_sv_coverage_cnvkit, "gatk-cnv": _normalize_sv_coverage_gatk} from bcbio.structural import cnvkit from bcbio.structural import shared as sshared items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)] if all(not cnvkit.use_general_sv_bins(x) for x in items): return [[d] for d in items] out_files = {} back_files = {} for group_id, gitems in itertools.groupby(items, lambda x: tz.get_in(["regions", "bins", "group"], x)): # No CNVkit calling for this particular set of samples if group_id is None: continue inputs, backgrounds = sshared.find_case_control(list(gitems)) assert inputs, "Did not find inputs for sample batch: %s" % (" ".join(dd.get_sample_name(x) for x in items)) work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(inputs[0]), "structural", dd.get_sample_name(inputs[0]), "bins")) back_files, out_files = calcfns[cnvkit.bin_approach(inputs[0])](group_id, inputs, backgrounds, work_dir, back_files, out_files) out = [] for data in items: if dd.get_sample_name(data) in out_files: data["depth"]["bins"]["background"] = back_files[dd.get_sample_name(data)] data["depth"]["bins"]["normalized"] = out_files[dd.get_sample_name(data)] out.append([data]) return out
python
def normalize_sv_coverage(*items): """Normalize CNV coverage, providing flexible point for multiple methods. """ calcfns = {"cnvkit": _normalize_sv_coverage_cnvkit, "gatk-cnv": _normalize_sv_coverage_gatk} from bcbio.structural import cnvkit from bcbio.structural import shared as sshared items = [utils.to_single_data(x) for x in cwlutils.handle_combined_input(items)] if all(not cnvkit.use_general_sv_bins(x) for x in items): return [[d] for d in items] out_files = {} back_files = {} for group_id, gitems in itertools.groupby(items, lambda x: tz.get_in(["regions", "bins", "group"], x)): # No CNVkit calling for this particular set of samples if group_id is None: continue inputs, backgrounds = sshared.find_case_control(list(gitems)) assert inputs, "Did not find inputs for sample batch: %s" % (" ".join(dd.get_sample_name(x) for x in items)) work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(inputs[0]), "structural", dd.get_sample_name(inputs[0]), "bins")) back_files, out_files = calcfns[cnvkit.bin_approach(inputs[0])](group_id, inputs, backgrounds, work_dir, back_files, out_files) out = [] for data in items: if dd.get_sample_name(data) in out_files: data["depth"]["bins"]["background"] = back_files[dd.get_sample_name(data)] data["depth"]["bins"]["normalized"] = out_files[dd.get_sample_name(data)] out.append([data]) return out
[ "def", "normalize_sv_coverage", "(", "*", "items", ")", ":", "calcfns", "=", "{", "\"cnvkit\"", ":", "_normalize_sv_coverage_cnvkit", ",", "\"gatk-cnv\"", ":", "_normalize_sv_coverage_gatk", "}", "from", "bcbio", ".", "structural", "import", "cnvkit", "from", "bcbio...
Normalize CNV coverage, providing flexible point for multiple methods.
[ "Normalize", "CNV", "coverage", "providing", "flexible", "point", "for", "multiple", "methods", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L256-L283
223,550
bcbio/bcbio-nextgen
bcbio/structural/regions.py
_normalize_sv_coverage_gatk
def _normalize_sv_coverage_gatk(group_id, inputs, backgrounds, work_dir, back_files, out_files): """Normalize CNV coverage using panel of normals with GATK's de-noise approaches. """ input_backs = set(filter(lambda x: x is not None, [dd.get_background_cnv_reference(d, "gatk-cnv") for d in inputs])) if input_backs: assert len(input_backs) == 1, "Multiple backgrounds in group: %s" % list(input_backs) pon = list(input_backs)[0] elif backgrounds: pon = gatkcnv.create_panel_of_normals(backgrounds, group_id, work_dir) else: pon = None for data in inputs: work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", dd.get_sample_name(data), "bins")) denoise_file = gatkcnv.denoise(data, pon, work_dir) out_files[dd.get_sample_name(data)] = denoise_file back_files[dd.get_sample_name(data)] = pon return back_files, out_files
python
def _normalize_sv_coverage_gatk(group_id, inputs, backgrounds, work_dir, back_files, out_files): """Normalize CNV coverage using panel of normals with GATK's de-noise approaches. """ input_backs = set(filter(lambda x: x is not None, [dd.get_background_cnv_reference(d, "gatk-cnv") for d in inputs])) if input_backs: assert len(input_backs) == 1, "Multiple backgrounds in group: %s" % list(input_backs) pon = list(input_backs)[0] elif backgrounds: pon = gatkcnv.create_panel_of_normals(backgrounds, group_id, work_dir) else: pon = None for data in inputs: work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", dd.get_sample_name(data), "bins")) denoise_file = gatkcnv.denoise(data, pon, work_dir) out_files[dd.get_sample_name(data)] = denoise_file back_files[dd.get_sample_name(data)] = pon return back_files, out_files
[ "def", "_normalize_sv_coverage_gatk", "(", "group_id", ",", "inputs", ",", "backgrounds", ",", "work_dir", ",", "back_files", ",", "out_files", ")", ":", "input_backs", "=", "set", "(", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "[",...
Normalize CNV coverage using panel of normals with GATK's de-noise approaches.
[ "Normalize", "CNV", "coverage", "using", "panel", "of", "normals", "with", "GATK", "s", "de", "-", "noise", "approaches", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L285-L303
223,551
bcbio/bcbio-nextgen
bcbio/structural/regions.py
_normalize_sv_coverage_cnvkit
def _normalize_sv_coverage_cnvkit(group_id, inputs, backgrounds, work_dir, back_files, out_files): """Normalize CNV coverage depths by GC, repeats and background using CNVkit - reference: calculates reference backgrounds from normals and pools including GC and repeat information - fix: Uses background to normalize coverage estimations http://cnvkit.readthedocs.io/en/stable/pipeline.html#fix """ from bcbio.structural import cnvkit cnns = reduce(operator.add, [[tz.get_in(["depth", "bins", "target"], x), tz.get_in(["depth", "bins", "antitarget"], x)] for x in backgrounds], []) for d in inputs: if tz.get_in(["depth", "bins", "target"], d): target_bed = tz.get_in(["depth", "bins", "target"], d) antitarget_bed = tz.get_in(["depth", "bins", "antitarget"], d) input_backs = set(filter(lambda x: x is not None, [dd.get_background_cnv_reference(d, "cnvkit") for d in inputs])) if input_backs: assert len(input_backs) == 1, "Multiple backgrounds in group: %s" % list(input_backs) back_file = list(input_backs)[0] else: back_file = cnvkit.cnvkit_background(cnns, os.path.join(work_dir, "background-%s-cnvkit.cnn" % (group_id)), backgrounds or inputs, target_bed, antitarget_bed) fix_cmd_inputs = [] for data in inputs: work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", dd.get_sample_name(data), "bins")) if tz.get_in(["depth", "bins", "target"], data): fix_file = os.path.join(work_dir, "%s-normalized.cnr" % (dd.get_sample_name(data))) fix_cmd_inputs.append((tz.get_in(["depth", "bins", "target"], data), tz.get_in(["depth", "bins", "antitarget"], data), back_file, fix_file, data)) out_files[dd.get_sample_name(data)] = fix_file back_files[dd.get_sample_name(data)] = back_file parallel = {"type": "local", "cores": dd.get_cores(inputs[0]), "progs": ["cnvkit"]} run_multicore(cnvkit.run_fix_parallel, fix_cmd_inputs, inputs[0]["config"], parallel) return back_files, out_files
python
def _normalize_sv_coverage_cnvkit(group_id, inputs, backgrounds, work_dir, back_files, out_files): """Normalize CNV coverage depths by GC, repeats and background using CNVkit - reference: calculates reference backgrounds from normals and pools including GC and repeat information - fix: Uses background to normalize coverage estimations http://cnvkit.readthedocs.io/en/stable/pipeline.html#fix """ from bcbio.structural import cnvkit cnns = reduce(operator.add, [[tz.get_in(["depth", "bins", "target"], x), tz.get_in(["depth", "bins", "antitarget"], x)] for x in backgrounds], []) for d in inputs: if tz.get_in(["depth", "bins", "target"], d): target_bed = tz.get_in(["depth", "bins", "target"], d) antitarget_bed = tz.get_in(["depth", "bins", "antitarget"], d) input_backs = set(filter(lambda x: x is not None, [dd.get_background_cnv_reference(d, "cnvkit") for d in inputs])) if input_backs: assert len(input_backs) == 1, "Multiple backgrounds in group: %s" % list(input_backs) back_file = list(input_backs)[0] else: back_file = cnvkit.cnvkit_background(cnns, os.path.join(work_dir, "background-%s-cnvkit.cnn" % (group_id)), backgrounds or inputs, target_bed, antitarget_bed) fix_cmd_inputs = [] for data in inputs: work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", dd.get_sample_name(data), "bins")) if tz.get_in(["depth", "bins", "target"], data): fix_file = os.path.join(work_dir, "%s-normalized.cnr" % (dd.get_sample_name(data))) fix_cmd_inputs.append((tz.get_in(["depth", "bins", "target"], data), tz.get_in(["depth", "bins", "antitarget"], data), back_file, fix_file, data)) out_files[dd.get_sample_name(data)] = fix_file back_files[dd.get_sample_name(data)] = back_file parallel = {"type": "local", "cores": dd.get_cores(inputs[0]), "progs": ["cnvkit"]} run_multicore(cnvkit.run_fix_parallel, fix_cmd_inputs, inputs[0]["config"], parallel) return back_files, out_files
[ "def", "_normalize_sv_coverage_cnvkit", "(", "group_id", ",", "inputs", ",", "backgrounds", ",", "work_dir", ",", "back_files", ",", "out_files", ")", ":", "from", "bcbio", ".", "structural", "import", "cnvkit", "cnns", "=", "reduce", "(", "operator", ".", "ad...
Normalize CNV coverage depths by GC, repeats and background using CNVkit - reference: calculates reference backgrounds from normals and pools including GC and repeat information - fix: Uses background to normalize coverage estimations http://cnvkit.readthedocs.io/en/stable/pipeline.html#fix
[ "Normalize", "CNV", "coverage", "depths", "by", "GC", "repeats", "and", "background", "using", "CNVkit" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L305-L342
223,552
bcbio/bcbio-nextgen
bcbio/structural/regions.py
get_base_cnv_regions
def get_base_cnv_regions(data, work_dir, genome_default="transcripts1e4", include_gene_names=True): """Retrieve set of target regions for CNV analysis. Subsets to extended transcript regions for WGS experiments to avoid long runtimes. """ cov_interval = dd.get_coverage_interval(data) base_regions = get_sv_bed(data, include_gene_names=include_gene_names) # if we don't have a configured BED or regions to use for SV caling if not base_regions: # For genome calls, subset to regions near genes as targets if cov_interval == "genome": base_regions = get_sv_bed(data, genome_default, work_dir, include_gene_names=include_gene_names) if base_regions: base_regions = remove_exclude_regions(base_regions, base_regions, [data]) # Finally, default to the defined variant regions if not base_regions: base_regions = dd.get_variant_regions(data) or dd.get_sample_callable(data) return bedutils.clean_file(base_regions, data)
python
def get_base_cnv_regions(data, work_dir, genome_default="transcripts1e4", include_gene_names=True): """Retrieve set of target regions for CNV analysis. Subsets to extended transcript regions for WGS experiments to avoid long runtimes. """ cov_interval = dd.get_coverage_interval(data) base_regions = get_sv_bed(data, include_gene_names=include_gene_names) # if we don't have a configured BED or regions to use for SV caling if not base_regions: # For genome calls, subset to regions near genes as targets if cov_interval == "genome": base_regions = get_sv_bed(data, genome_default, work_dir, include_gene_names=include_gene_names) if base_regions: base_regions = remove_exclude_regions(base_regions, base_regions, [data]) # Finally, default to the defined variant regions if not base_regions: base_regions = dd.get_variant_regions(data) or dd.get_sample_callable(data) return bedutils.clean_file(base_regions, data)
[ "def", "get_base_cnv_regions", "(", "data", ",", "work_dir", ",", "genome_default", "=", "\"transcripts1e4\"", ",", "include_gene_names", "=", "True", ")", ":", "cov_interval", "=", "dd", ".", "get_coverage_interval", "(", "data", ")", "base_regions", "=", "get_sv...
Retrieve set of target regions for CNV analysis. Subsets to extended transcript regions for WGS experiments to avoid long runtimes.
[ "Retrieve", "set", "of", "target", "regions", "for", "CNV", "analysis", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L346-L364
223,553
bcbio/bcbio-nextgen
bcbio/structural/regions.py
remove_exclude_regions
def remove_exclude_regions(orig_bed, base_file, items, remove_entire_feature=False): """Remove centromere and short end regions from an existing BED file of regions to target. """ from bcbio.structural import shared as sshared out_bed = os.path.join("%s-noexclude.bed" % (utils.splitext_plus(base_file)[0])) if not utils.file_uptodate(out_bed, orig_bed): exclude_bed = sshared.prepare_exclude_file(items, base_file) with file_transaction(items[0], out_bed) as tx_out_bed: pybedtools.BedTool(orig_bed).subtract(pybedtools.BedTool(exclude_bed), A=remove_entire_feature, nonamecheck=True).saveas(tx_out_bed) if utils.file_exists(out_bed): return out_bed else: return orig_bed
python
def remove_exclude_regions(orig_bed, base_file, items, remove_entire_feature=False): """Remove centromere and short end regions from an existing BED file of regions to target. """ from bcbio.structural import shared as sshared out_bed = os.path.join("%s-noexclude.bed" % (utils.splitext_plus(base_file)[0])) if not utils.file_uptodate(out_bed, orig_bed): exclude_bed = sshared.prepare_exclude_file(items, base_file) with file_transaction(items[0], out_bed) as tx_out_bed: pybedtools.BedTool(orig_bed).subtract(pybedtools.BedTool(exclude_bed), A=remove_entire_feature, nonamecheck=True).saveas(tx_out_bed) if utils.file_exists(out_bed): return out_bed else: return orig_bed
[ "def", "remove_exclude_regions", "(", "orig_bed", ",", "base_file", ",", "items", ",", "remove_entire_feature", "=", "False", ")", ":", "from", "bcbio", ".", "structural", "import", "shared", "as", "sshared", "out_bed", "=", "os", ".", "path", ".", "join", "...
Remove centromere and short end regions from an existing BED file of regions to target.
[ "Remove", "centromere", "and", "short", "end", "regions", "from", "an", "existing", "BED", "file", "of", "regions", "to", "target", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L366-L379
223,554
bcbio/bcbio-nextgen
bcbio/structural/regions.py
get_sv_bed
def get_sv_bed(data, method=None, out_dir=None, include_gene_names=True): """Retrieve a BED file of regions for SV and heterogeneity calling using the provided method. method choices: - exons: Raw BED file of exon regions - transcripts: Full collapsed regions with the min and max of each transcript. - transcriptsXXXX: Collapsed regions around transcripts with a window size of XXXX. - A custom BED file of regions """ if method is None: method = (tz.get_in(["config", "algorithm", "sv_regions"], data) or dd.get_variant_regions(data) or dd.get_sample_callable(data)) gene_file = dd.get_gene_bed(data) if method and os.path.isfile(method): return method elif not gene_file or not method: return None elif method == "exons": return gene_file elif method.startswith("transcripts"): window = method.split("transcripts")[-1] window = int(float(window)) if window else 0 return _collapse_transcripts(gene_file, window, data, out_dir, include_gene_names=include_gene_names) else: raise ValueError("Unexpected transcript retrieval method: %s" % method)
python
def get_sv_bed(data, method=None, out_dir=None, include_gene_names=True): """Retrieve a BED file of regions for SV and heterogeneity calling using the provided method. method choices: - exons: Raw BED file of exon regions - transcripts: Full collapsed regions with the min and max of each transcript. - transcriptsXXXX: Collapsed regions around transcripts with a window size of XXXX. - A custom BED file of regions """ if method is None: method = (tz.get_in(["config", "algorithm", "sv_regions"], data) or dd.get_variant_regions(data) or dd.get_sample_callable(data)) gene_file = dd.get_gene_bed(data) if method and os.path.isfile(method): return method elif not gene_file or not method: return None elif method == "exons": return gene_file elif method.startswith("transcripts"): window = method.split("transcripts")[-1] window = int(float(window)) if window else 0 return _collapse_transcripts(gene_file, window, data, out_dir, include_gene_names=include_gene_names) else: raise ValueError("Unexpected transcript retrieval method: %s" % method)
[ "def", "get_sv_bed", "(", "data", ",", "method", "=", "None", ",", "out_dir", "=", "None", ",", "include_gene_names", "=", "True", ")", ":", "if", "method", "is", "None", ":", "method", "=", "(", "tz", ".", "get_in", "(", "[", "\"config\"", ",", "\"a...
Retrieve a BED file of regions for SV and heterogeneity calling using the provided method. method choices: - exons: Raw BED file of exon regions - transcripts: Full collapsed regions with the min and max of each transcript. - transcriptsXXXX: Collapsed regions around transcripts with a window size of XXXX. - A custom BED file of regions
[ "Retrieve", "a", "BED", "file", "of", "regions", "for", "SV", "and", "heterogeneity", "calling", "using", "the", "provided", "method", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L381-L406
223,555
bcbio/bcbio-nextgen
bcbio/structural/regions.py
_group_coords
def _group_coords(rs): """Organize coordinate regions into groups for each transcript. Avoids collapsing very large introns or repetitive genes spread across the chromosome by limiting the intron size to 100kb for creating a single transcript """ max_intron_size = 1e5 coords = [] for r in rs: coords.append(r.start) coords.append(r.end) coord_groups = [] cur_group = [] for coord in sorted(coords): if not cur_group or coord - cur_group[-1] < max_intron_size: cur_group.append(coord) else: coord_groups.append(cur_group) cur_group = [coord] if cur_group: coord_groups.append(cur_group) return coord_groups
python
def _group_coords(rs): """Organize coordinate regions into groups for each transcript. Avoids collapsing very large introns or repetitive genes spread across the chromosome by limiting the intron size to 100kb for creating a single transcript """ max_intron_size = 1e5 coords = [] for r in rs: coords.append(r.start) coords.append(r.end) coord_groups = [] cur_group = [] for coord in sorted(coords): if not cur_group or coord - cur_group[-1] < max_intron_size: cur_group.append(coord) else: coord_groups.append(cur_group) cur_group = [coord] if cur_group: coord_groups.append(cur_group) return coord_groups
[ "def", "_group_coords", "(", "rs", ")", ":", "max_intron_size", "=", "1e5", "coords", "=", "[", "]", "for", "r", "in", "rs", ":", "coords", ".", "append", "(", "r", ".", "start", ")", "coords", ".", "append", "(", "r", ".", "end", ")", "coord_group...
Organize coordinate regions into groups for each transcript. Avoids collapsing very large introns or repetitive genes spread across the chromosome by limiting the intron size to 100kb for creating a single transcript
[ "Organize", "coordinate", "regions", "into", "groups", "for", "each", "transcript", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L445-L466
223,556
bcbio/bcbio-nextgen
bcbio/structural/regions.py
MemoizedSizes._calc_sizes
def _calc_sizes(self, cnv_file, items): """Retrieve target and antitarget bin sizes based on depth. Similar to CNVkit's do_autobin but tries to have a standard set of ranges (50bp intervals for target and 10kb intervals for antitarget). """ bp_per_bin = 100000 # same target as CNVkit range_map = {"target": (100, 250), "antitarget": (10000, 1000000)} target_bps = [] anti_bps = [] checked_beds = set([]) for data in items: region_bed = tz.get_in(["depth", "variant_regions", "regions"], data) if region_bed and region_bed not in checked_beds: with utils.open_gzipsafe(region_bed) as in_handle: for r in pybedtools.BedTool(in_handle).intersect(cnv_file): if r.stop - r.start > range_map["target"][0]: target_bps.append(float(r.name)) with utils.open_gzipsafe(region_bed) as in_handle: for r in pybedtools.BedTool(in_handle).intersect(cnv_file, v=True): if r.stop - r.start > range_map["target"][1]: anti_bps.append(float(r.name)) checked_beds.add(region_bed) def scale_in_boundary(raw, round_interval, range_targets): min_val, max_val = range_targets out = int(math.ceil(raw / float(round_interval)) * round_interval) if out > max_val: return max_val elif out < min_val: return min_val else: return out if target_bps and np.median(target_bps) > 0: raw_target_bin = bp_per_bin / float(np.median(target_bps)) target_bin = scale_in_boundary(raw_target_bin, 50, range_map["target"]) else: target_bin = range_map["target"][1] if anti_bps and np.median(anti_bps) > 0: raw_anti_bin = bp_per_bin / float(np.median(anti_bps)) anti_bin = scale_in_boundary(raw_anti_bin, 10000, range_map["antitarget"]) else: anti_bin = range_map["antitarget"][1] return target_bin, anti_bin
python
def _calc_sizes(self, cnv_file, items): """Retrieve target and antitarget bin sizes based on depth. Similar to CNVkit's do_autobin but tries to have a standard set of ranges (50bp intervals for target and 10kb intervals for antitarget). """ bp_per_bin = 100000 # same target as CNVkit range_map = {"target": (100, 250), "antitarget": (10000, 1000000)} target_bps = [] anti_bps = [] checked_beds = set([]) for data in items: region_bed = tz.get_in(["depth", "variant_regions", "regions"], data) if region_bed and region_bed not in checked_beds: with utils.open_gzipsafe(region_bed) as in_handle: for r in pybedtools.BedTool(in_handle).intersect(cnv_file): if r.stop - r.start > range_map["target"][0]: target_bps.append(float(r.name)) with utils.open_gzipsafe(region_bed) as in_handle: for r in pybedtools.BedTool(in_handle).intersect(cnv_file, v=True): if r.stop - r.start > range_map["target"][1]: anti_bps.append(float(r.name)) checked_beds.add(region_bed) def scale_in_boundary(raw, round_interval, range_targets): min_val, max_val = range_targets out = int(math.ceil(raw / float(round_interval)) * round_interval) if out > max_val: return max_val elif out < min_val: return min_val else: return out if target_bps and np.median(target_bps) > 0: raw_target_bin = bp_per_bin / float(np.median(target_bps)) target_bin = scale_in_boundary(raw_target_bin, 50, range_map["target"]) else: target_bin = range_map["target"][1] if anti_bps and np.median(anti_bps) > 0: raw_anti_bin = bp_per_bin / float(np.median(anti_bps)) anti_bin = scale_in_boundary(raw_anti_bin, 10000, range_map["antitarget"]) else: anti_bin = range_map["antitarget"][1] return target_bin, anti_bin
[ "def", "_calc_sizes", "(", "self", ",", "cnv_file", ",", "items", ")", ":", "bp_per_bin", "=", "100000", "# same target as CNVkit", "range_map", "=", "{", "\"target\"", ":", "(", "100", ",", "250", ")", ",", "\"antitarget\"", ":", "(", "10000", ",", "10000...
Retrieve target and antitarget bin sizes based on depth. Similar to CNVkit's do_autobin but tries to have a standard set of ranges (50bp intervals for target and 10kb intervals for antitarget).
[ "Retrieve", "target", "and", "antitarget", "bin", "sizes", "based", "on", "depth", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/regions.py#L98-L141
223,557
bcbio/bcbio-nextgen
bcbio/hmmer/search.py
phmmer
def phmmer(**kwargs): """Search a protein sequence against a HMMER sequence database. Arguments: seq - The sequence to search -- a Fasta string. seqdb -- Sequence database to search against. range -- A string range of results to return (ie. 1,10 for the first ten) output -- The output format (defaults to JSON). """ logging.debug(kwargs) args = {'seq' : kwargs.get('seq'), 'seqdb' : kwargs.get('seqdb')} args2 = {'output' : kwargs.get('output', 'json'), 'range' : kwargs.get('range')} return _hmmer("http://hmmer.janelia.org/search/phmmer", args, args2)
python
def phmmer(**kwargs): """Search a protein sequence against a HMMER sequence database. Arguments: seq - The sequence to search -- a Fasta string. seqdb -- Sequence database to search against. range -- A string range of results to return (ie. 1,10 for the first ten) output -- The output format (defaults to JSON). """ logging.debug(kwargs) args = {'seq' : kwargs.get('seq'), 'seqdb' : kwargs.get('seqdb')} args2 = {'output' : kwargs.get('output', 'json'), 'range' : kwargs.get('range')} return _hmmer("http://hmmer.janelia.org/search/phmmer", args, args2)
[ "def", "phmmer", "(", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "kwargs", ")", "args", "=", "{", "'seq'", ":", "kwargs", ".", "get", "(", "'seq'", ")", ",", "'seqdb'", ":", "kwargs", ".", "get", "(", "'seqdb'", ")", "}", "args2"...
Search a protein sequence against a HMMER sequence database. Arguments: seq - The sequence to search -- a Fasta string. seqdb -- Sequence database to search against. range -- A string range of results to return (ie. 1,10 for the first ten) output -- The output format (defaults to JSON).
[ "Search", "a", "protein", "sequence", "against", "a", "HMMER", "sequence", "database", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/hmmer/search.py#L40-L54
223,558
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
scrnaseq_concatenate_metadata
def scrnaseq_concatenate_metadata(samples): """ Create file same dimension than mtx.colnames with metadata and sample name to help in the creation of the SC object. """ barcodes = {} counts = "" metadata = {} has_sample_barcodes = False for sample in dd.sample_data_iterator(samples): if dd.get_sample_barcodes(sample): has_sample_barcodes = True with open(dd.get_sample_barcodes(sample)) as inh: for line in inh: cols = line.strip().split(",") if len(cols) == 1: # Assign sample name in case of missing in barcodes cols.append("NaN") barcodes[(dd.get_sample_name(sample), cols[0])] = cols[1:] else: barcodes[(dd.get_sample_name(sample), "NaN")] = [dd.get_sample_name(sample), "NaN"] counts = dd.get_combined_counts(sample) meta = map(str, list(sample["metadata"].values())) meta_cols = list(sample["metadata"].keys()) meta = ["NaN" if not v else v for v in meta] metadata[dd.get_sample_name(sample)] = meta metadata_fn = counts + ".metadata" if file_exists(metadata_fn): return samples with file_transaction(metadata_fn) as tx_metadata_fn: with open(tx_metadata_fn, 'w') as outh: outh.write(",".join(["sample"] + meta_cols) + '\n') with open(counts + ".colnames") as inh: for line in inh: sample = line.split(":")[0] if has_sample_barcodes: barcode = sample.split("-")[1] else: barcode = "NaN" outh.write(",".join(barcodes[(sample, barcode)] + metadata[sample]) + '\n') return samples
python
def scrnaseq_concatenate_metadata(samples): """ Create file same dimension than mtx.colnames with metadata and sample name to help in the creation of the SC object. """ barcodes = {} counts = "" metadata = {} has_sample_barcodes = False for sample in dd.sample_data_iterator(samples): if dd.get_sample_barcodes(sample): has_sample_barcodes = True with open(dd.get_sample_barcodes(sample)) as inh: for line in inh: cols = line.strip().split(",") if len(cols) == 1: # Assign sample name in case of missing in barcodes cols.append("NaN") barcodes[(dd.get_sample_name(sample), cols[0])] = cols[1:] else: barcodes[(dd.get_sample_name(sample), "NaN")] = [dd.get_sample_name(sample), "NaN"] counts = dd.get_combined_counts(sample) meta = map(str, list(sample["metadata"].values())) meta_cols = list(sample["metadata"].keys()) meta = ["NaN" if not v else v for v in meta] metadata[dd.get_sample_name(sample)] = meta metadata_fn = counts + ".metadata" if file_exists(metadata_fn): return samples with file_transaction(metadata_fn) as tx_metadata_fn: with open(tx_metadata_fn, 'w') as outh: outh.write(",".join(["sample"] + meta_cols) + '\n') with open(counts + ".colnames") as inh: for line in inh: sample = line.split(":")[0] if has_sample_barcodes: barcode = sample.split("-")[1] else: barcode = "NaN" outh.write(",".join(barcodes[(sample, barcode)] + metadata[sample]) + '\n') return samples
[ "def", "scrnaseq_concatenate_metadata", "(", "samples", ")", ":", "barcodes", "=", "{", "}", "counts", "=", "\"\"", "metadata", "=", "{", "}", "has_sample_barcodes", "=", "False", "for", "sample", "in", "dd", ".", "sample_data_iterator", "(", "samples", ")", ...
Create file same dimension than mtx.colnames with metadata and sample name to help in the creation of the SC object.
[ "Create", "file", "same", "dimension", "than", "mtx", ".", "colnames", "with", "metadata", "and", "sample", "name", "to", "help", "in", "the", "creation", "of", "the", "SC", "object", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L47-L90
223,559
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
rnaseq_variant_calling
def rnaseq_variant_calling(samples, run_parallel): """ run RNA-seq variant calling using GATK """ samples = run_parallel("run_rnaseq_variant_calling", samples) variantcaller = dd.get_variantcaller(to_single_data(samples[0])) if variantcaller and ("gatk-haplotype" in variantcaller): out = [] for d in joint.square_off(samples, run_parallel): out.extend([[to_single_data(xs)] for xs in multi.split_variants_by_sample(to_single_data(d))]) samples = out if variantcaller: samples = run_parallel("run_rnaseq_ann_filter", samples) if variantcaller and ("gatk-haplotype" in variantcaller): out = [] for data in (to_single_data(xs) for xs in samples): if "variants" not in data: data["variants"] = [] data["variants"].append({"variantcaller": "gatk-haplotype", "vcf": data["vrn_file_orig"], "population": {"vcf": data["vrn_file"]}}) data["vrn_file"] = data.pop("vrn_file_orig") out.append([data]) samples = out return samples
python
def rnaseq_variant_calling(samples, run_parallel): """ run RNA-seq variant calling using GATK """ samples = run_parallel("run_rnaseq_variant_calling", samples) variantcaller = dd.get_variantcaller(to_single_data(samples[0])) if variantcaller and ("gatk-haplotype" in variantcaller): out = [] for d in joint.square_off(samples, run_parallel): out.extend([[to_single_data(xs)] for xs in multi.split_variants_by_sample(to_single_data(d))]) samples = out if variantcaller: samples = run_parallel("run_rnaseq_ann_filter", samples) if variantcaller and ("gatk-haplotype" in variantcaller): out = [] for data in (to_single_data(xs) for xs in samples): if "variants" not in data: data["variants"] = [] data["variants"].append({"variantcaller": "gatk-haplotype", "vcf": data["vrn_file_orig"], "population": {"vcf": data["vrn_file"]}}) data["vrn_file"] = data.pop("vrn_file_orig") out.append([data]) samples = out return samples
[ "def", "rnaseq_variant_calling", "(", "samples", ",", "run_parallel", ")", ":", "samples", "=", "run_parallel", "(", "\"run_rnaseq_variant_calling\"", ",", "samples", ")", "variantcaller", "=", "dd", ".", "get_variantcaller", "(", "to_single_data", "(", "samples", "...
run RNA-seq variant calling using GATK
[ "run", "RNA", "-", "seq", "variant", "calling", "using", "GATK" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L92-L115
223,560
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
run_rnaseq_variant_calling
def run_rnaseq_variant_calling(data): """ run RNA-seq variant calling, variation file is stored in `vrn_file` in the datadict """ variantcaller = dd.get_variantcaller(data) if isinstance(variantcaller, list) and len(variantcaller) > 1: logger.error("Only one variantcaller can be run for RNA-seq at " "this time. Post an issue here " "(https://github.com/bcbio/bcbio-nextgen/issues) " "if this is something you need to do.") sys.exit(1) if variantcaller: if "gatk-haplotype" in variantcaller: data = variation.rnaseq_gatk_variant_calling(data) if vardict.get_vardict_command(data): data = variation.rnaseq_vardict_variant_calling(data) vrn_file = dd.get_vrn_file(data) return [[data]]
python
def run_rnaseq_variant_calling(data): """ run RNA-seq variant calling, variation file is stored in `vrn_file` in the datadict """ variantcaller = dd.get_variantcaller(data) if isinstance(variantcaller, list) and len(variantcaller) > 1: logger.error("Only one variantcaller can be run for RNA-seq at " "this time. Post an issue here " "(https://github.com/bcbio/bcbio-nextgen/issues) " "if this is something you need to do.") sys.exit(1) if variantcaller: if "gatk-haplotype" in variantcaller: data = variation.rnaseq_gatk_variant_calling(data) if vardict.get_vardict_command(data): data = variation.rnaseq_vardict_variant_calling(data) vrn_file = dd.get_vrn_file(data) return [[data]]
[ "def", "run_rnaseq_variant_calling", "(", "data", ")", ":", "variantcaller", "=", "dd", ".", "get_variantcaller", "(", "data", ")", "if", "isinstance", "(", "variantcaller", ",", "list", ")", "and", "len", "(", "variantcaller", ")", ">", "1", ":", "logger", ...
run RNA-seq variant calling, variation file is stored in `vrn_file` in the datadict
[ "run", "RNA", "-", "seq", "variant", "calling", "variation", "file", "is", "stored", "in", "vrn_file", "in", "the", "datadict" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L117-L136
223,561
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
run_rnaseq_ann_filter
def run_rnaseq_ann_filter(data): """Run RNA-seq annotation and filtering. """ data = to_single_data(data) if dd.get_vrn_file(data): eff_file = effects.add_to_vcf(dd.get_vrn_file(data), data)[0] if eff_file: data = dd.set_vrn_file(data, eff_file) ann_file = population.run_vcfanno(dd.get_vrn_file(data), data) if ann_file: data = dd.set_vrn_file(data, ann_file) variantcaller = dd.get_variantcaller(data) if variantcaller and ("gatk-haplotype" in variantcaller): filter_file = variation.gatk_filter_rnaseq(dd.get_vrn_file(data), data) data = dd.set_vrn_file(data, filter_file) # remove variants close to splice junctions vrn_file = dd.get_vrn_file(data) vrn_file = variation.filter_junction_variants(vrn_file, data) data = dd.set_vrn_file(data, vrn_file) return [[data]]
python
def run_rnaseq_ann_filter(data): """Run RNA-seq annotation and filtering. """ data = to_single_data(data) if dd.get_vrn_file(data): eff_file = effects.add_to_vcf(dd.get_vrn_file(data), data)[0] if eff_file: data = dd.set_vrn_file(data, eff_file) ann_file = population.run_vcfanno(dd.get_vrn_file(data), data) if ann_file: data = dd.set_vrn_file(data, ann_file) variantcaller = dd.get_variantcaller(data) if variantcaller and ("gatk-haplotype" in variantcaller): filter_file = variation.gatk_filter_rnaseq(dd.get_vrn_file(data), data) data = dd.set_vrn_file(data, filter_file) # remove variants close to splice junctions vrn_file = dd.get_vrn_file(data) vrn_file = variation.filter_junction_variants(vrn_file, data) data = dd.set_vrn_file(data, vrn_file) return [[data]]
[ "def", "run_rnaseq_ann_filter", "(", "data", ")", ":", "data", "=", "to_single_data", "(", "data", ")", "if", "dd", ".", "get_vrn_file", "(", "data", ")", ":", "eff_file", "=", "effects", ".", "add_to_vcf", "(", "dd", ".", "get_vrn_file", "(", "data", ")...
Run RNA-seq annotation and filtering.
[ "Run", "RNA", "-", "seq", "annotation", "and", "filtering", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L138-L157
223,562
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
quantitate
def quantitate(data): """CWL target for quantitation. XXX Needs to be split and parallelized by expression caller, with merging of multiple calls. """ data = to_single_data(to_single_data(data)) data = generate_transcript_counts(data)[0][0] data["quant"] = {} if "sailfish" in dd.get_expression_caller(data): data = to_single_data(sailfish.run_sailfish(data)[0]) data["quant"]["tsv"] = data["sailfish"] data["quant"]["hdf5"] = os.path.join(os.path.dirname(data["sailfish"]), "abundance.h5") if ("kallisto" in dd.get_expression_caller(data) or "pizzly" in dd.get_fusion_caller(data, [])): data = to_single_data(kallisto.run_kallisto_rnaseq(data)[0]) data["quant"]["tsv"] = os.path.join(data["kallisto_quant"], "abundance.tsv") data["quant"]["hdf5"] = os.path.join(data["kallisto_quant"], "abundance.h5") if (os.path.exists(os.path.join(data["kallisto_quant"], "fusion.txt"))): data["quant"]["fusion"] = os.path.join(data["kallisto_quant"], "fusion.txt") else: data["quant"]["fusion"] = None if "salmon" in dd.get_expression_caller(data): data = to_single_data(salmon.run_salmon_reads(data)[0]) data["quant"]["tsv"] = data["salmon"] data["quant"]["hdf5"] = os.path.join(os.path.dirname(data["salmon"]), "abundance.h5") return [[data]]
python
def quantitate(data): """CWL target for quantitation. XXX Needs to be split and parallelized by expression caller, with merging of multiple calls. """ data = to_single_data(to_single_data(data)) data = generate_transcript_counts(data)[0][0] data["quant"] = {} if "sailfish" in dd.get_expression_caller(data): data = to_single_data(sailfish.run_sailfish(data)[0]) data["quant"]["tsv"] = data["sailfish"] data["quant"]["hdf5"] = os.path.join(os.path.dirname(data["sailfish"]), "abundance.h5") if ("kallisto" in dd.get_expression_caller(data) or "pizzly" in dd.get_fusion_caller(data, [])): data = to_single_data(kallisto.run_kallisto_rnaseq(data)[0]) data["quant"]["tsv"] = os.path.join(data["kallisto_quant"], "abundance.tsv") data["quant"]["hdf5"] = os.path.join(data["kallisto_quant"], "abundance.h5") if (os.path.exists(os.path.join(data["kallisto_quant"], "fusion.txt"))): data["quant"]["fusion"] = os.path.join(data["kallisto_quant"], "fusion.txt") else: data["quant"]["fusion"] = None if "salmon" in dd.get_expression_caller(data): data = to_single_data(salmon.run_salmon_reads(data)[0]) data["quant"]["tsv"] = data["salmon"] data["quant"]["hdf5"] = os.path.join(os.path.dirname(data["salmon"]), "abundance.h5") return [[data]]
[ "def", "quantitate", "(", "data", ")", ":", "data", "=", "to_single_data", "(", "to_single_data", "(", "data", ")", ")", "data", "=", "generate_transcript_counts", "(", "data", ")", "[", "0", "]", "[", "0", "]", "data", "[", "\"quant\"", "]", "=", "{",...
CWL target for quantitation. XXX Needs to be split and parallelized by expression caller, with merging of multiple calls.
[ "CWL", "target", "for", "quantitation", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L159-L184
223,563
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
quantitate_expression_parallel
def quantitate_expression_parallel(samples, run_parallel): """ quantitate expression, all programs run here should be multithreaded to take advantage of the threaded run_parallel environment """ data = samples[0][0] samples = run_parallel("generate_transcript_counts", samples) if "cufflinks" in dd.get_expression_caller(data): samples = run_parallel("run_cufflinks", samples) if "stringtie" in dd.get_expression_caller(data): samples = run_parallel("run_stringtie_expression", samples) if ("kallisto" in dd.get_expression_caller(data) or dd.get_fusion_mode(data) or "pizzly" in dd.get_fusion_caller(data, [])): samples = run_parallel("run_kallisto_index", [samples]) samples = run_parallel("run_kallisto_rnaseq", samples) if "sailfish" in dd.get_expression_caller(data): samples = run_parallel("run_sailfish_index", [samples]) samples = run_parallel("run_sailfish", samples) # always run salmon samples = run_parallel("run_salmon_index", [samples]) samples = run_parallel("run_salmon_reads", samples) samples = run_parallel("detect_fusions", samples) return samples
python
def quantitate_expression_parallel(samples, run_parallel): """ quantitate expression, all programs run here should be multithreaded to take advantage of the threaded run_parallel environment """ data = samples[0][0] samples = run_parallel("generate_transcript_counts", samples) if "cufflinks" in dd.get_expression_caller(data): samples = run_parallel("run_cufflinks", samples) if "stringtie" in dd.get_expression_caller(data): samples = run_parallel("run_stringtie_expression", samples) if ("kallisto" in dd.get_expression_caller(data) or dd.get_fusion_mode(data) or "pizzly" in dd.get_fusion_caller(data, [])): samples = run_parallel("run_kallisto_index", [samples]) samples = run_parallel("run_kallisto_rnaseq", samples) if "sailfish" in dd.get_expression_caller(data): samples = run_parallel("run_sailfish_index", [samples]) samples = run_parallel("run_sailfish", samples) # always run salmon samples = run_parallel("run_salmon_index", [samples]) samples = run_parallel("run_salmon_reads", samples) samples = run_parallel("detect_fusions", samples) return samples
[ "def", "quantitate_expression_parallel", "(", "samples", ",", "run_parallel", ")", ":", "data", "=", "samples", "[", "0", "]", "[", "0", "]", "samples", "=", "run_parallel", "(", "\"generate_transcript_counts\"", ",", "samples", ")", "if", "\"cufflinks\"", "in",...
quantitate expression, all programs run here should be multithreaded to take advantage of the threaded run_parallel environment
[ "quantitate", "expression", "all", "programs", "run", "here", "should", "be", "multithreaded", "to", "take", "advantage", "of", "the", "threaded", "run_parallel", "environment" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L186-L210
223,564
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
quantitate_expression_noparallel
def quantitate_expression_noparallel(samples, run_parallel): """ run transcript quantitation for algorithms that don't run in parallel """ data = samples[0][0] if "express" in dd.get_expression_caller(data): samples = run_parallel("run_express", samples) if "dexseq" in dd.get_expression_caller(data): samples = run_parallel("run_dexseq", samples) return samples
python
def quantitate_expression_noparallel(samples, run_parallel): """ run transcript quantitation for algorithms that don't run in parallel """ data = samples[0][0] if "express" in dd.get_expression_caller(data): samples = run_parallel("run_express", samples) if "dexseq" in dd.get_expression_caller(data): samples = run_parallel("run_dexseq", samples) return samples
[ "def", "quantitate_expression_noparallel", "(", "samples", ",", "run_parallel", ")", ":", "data", "=", "samples", "[", "0", "]", "[", "0", "]", "if", "\"express\"", "in", "dd", ".", "get_expression_caller", "(", "data", ")", ":", "samples", "=", "run_paralle...
run transcript quantitation for algorithms that don't run in parallel
[ "run", "transcript", "quantitation", "for", "algorithms", "that", "don", "t", "run", "in", "parallel" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L236-L245
223,565
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
generate_transcript_counts
def generate_transcript_counts(data): """Generate counts per transcript and per exon from an alignment""" data["count_file"] = featureCounts.count(data) if dd.get_fusion_mode(data, False) and not dd.get_fusion_caller(data): oncofuse_file = oncofuse.run(data) if oncofuse_file: data = dd.set_oncofuse_file(data, oncofuse_file) if dd.get_transcriptome_align(data): # to create a disambiguated transcriptome file realign with bowtie2 if dd.get_disambiguate(data): logger.info("Aligning to the transcriptome with bowtie2 using the " "disambiguated reads.") bam_path = data["work_bam"] fastq_paths = alignprep._bgzip_from_bam(bam_path, data["dirs"], data, is_retry=False, output_infix='-transcriptome') if len(fastq_paths) == 2: file1, file2 = fastq_paths else: file1, file2 = fastq_paths[0], None ref_file = dd.get_ref_file(data) data = bowtie2.align_transcriptome(file1, file2, ref_file, data) else: file1, file2 = dd.get_input_sequence_files(data) if not dd.get_transcriptome_bam(data): ref_file = dd.get_ref_file(data) logger.info("Transcriptome alignment was flagged to run, but the " "transcriptome BAM file was not found. Aligning to the " "transcriptome with bowtie2.") data = bowtie2.align_transcriptome(file1, file2, ref_file, data) data = spikein.counts_spikein(data) return [[data]]
python
def generate_transcript_counts(data): """Generate counts per transcript and per exon from an alignment""" data["count_file"] = featureCounts.count(data) if dd.get_fusion_mode(data, False) and not dd.get_fusion_caller(data): oncofuse_file = oncofuse.run(data) if oncofuse_file: data = dd.set_oncofuse_file(data, oncofuse_file) if dd.get_transcriptome_align(data): # to create a disambiguated transcriptome file realign with bowtie2 if dd.get_disambiguate(data): logger.info("Aligning to the transcriptome with bowtie2 using the " "disambiguated reads.") bam_path = data["work_bam"] fastq_paths = alignprep._bgzip_from_bam(bam_path, data["dirs"], data, is_retry=False, output_infix='-transcriptome') if len(fastq_paths) == 2: file1, file2 = fastq_paths else: file1, file2 = fastq_paths[0], None ref_file = dd.get_ref_file(data) data = bowtie2.align_transcriptome(file1, file2, ref_file, data) else: file1, file2 = dd.get_input_sequence_files(data) if not dd.get_transcriptome_bam(data): ref_file = dd.get_ref_file(data) logger.info("Transcriptome alignment was flagged to run, but the " "transcriptome BAM file was not found. Aligning to the " "transcriptome with bowtie2.") data = bowtie2.align_transcriptome(file1, file2, ref_file, data) data = spikein.counts_spikein(data) return [[data]]
[ "def", "generate_transcript_counts", "(", "data", ")", ":", "data", "[", "\"count_file\"", "]", "=", "featureCounts", ".", "count", "(", "data", ")", "if", "dd", ".", "get_fusion_mode", "(", "data", ",", "False", ")", "and", "not", "dd", ".", "get_fusion_c...
Generate counts per transcript and per exon from an alignment
[ "Generate", "counts", "per", "transcript", "and", "per", "exon", "from", "an", "alignment" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L247-L278
223,566
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
run_dexseq
def run_dexseq(data): """Quantitate exon-level counts with DEXSeq""" if dd.get_dexseq_gff(data, None): data = dexseq.bcbio_run(data) return [[data]]
python
def run_dexseq(data): """Quantitate exon-level counts with DEXSeq""" if dd.get_dexseq_gff(data, None): data = dexseq.bcbio_run(data) return [[data]]
[ "def", "run_dexseq", "(", "data", ")", ":", "if", "dd", ".", "get_dexseq_gff", "(", "data", ",", "None", ")", ":", "data", "=", "dexseq", ".", "bcbio_run", "(", "data", ")", "return", "[", "[", "data", "]", "]" ]
Quantitate exon-level counts with DEXSeq
[ "Quantitate", "exon", "-", "level", "counts", "with", "DEXSeq" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L285-L289
223,567
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
combine_express
def combine_express(samples, combined): """Combine tpm, effective counts and fpkm from express results""" if not combined: return None to_combine = [dd.get_express_counts(x) for x in dd.sample_data_iterator(samples) if dd.get_express_counts(x)] gtf_file = dd.get_gtf_file(samples[0][0]) isoform_to_gene_file = os.path.join(os.path.dirname(combined), "isoform_to_gene.txt") isoform_to_gene_file = express.isoform_to_gene_name( gtf_file, isoform_to_gene_file, next(dd.sample_data_iterator(samples))) if len(to_combine) > 0: eff_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_counts" eff_counts_combined = count.combine_count_files(to_combine, eff_counts_combined_file, ext=".counts") to_combine = [dd.get_express_tpm(x) for x in dd.sample_data_iterator(samples) if dd.get_express_tpm(x)] tpm_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_tpm" tpm_counts_combined = count.combine_count_files(to_combine, tpm_counts_combined_file) to_combine = [dd.get_express_fpkm(x) for x in dd.sample_data_iterator(samples) if dd.get_express_fpkm(x)] fpkm_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_fpkm" fpkm_counts_combined = count.combine_count_files(to_combine, fpkm_counts_combined_file, ext=".fpkm") return {'counts': eff_counts_combined, 'tpm': tpm_counts_combined, 'fpkm': fpkm_counts_combined, 'isoform_to_gene': isoform_to_gene_file} return {}
python
def combine_express(samples, combined): """Combine tpm, effective counts and fpkm from express results""" if not combined: return None to_combine = [dd.get_express_counts(x) for x in dd.sample_data_iterator(samples) if dd.get_express_counts(x)] gtf_file = dd.get_gtf_file(samples[0][0]) isoform_to_gene_file = os.path.join(os.path.dirname(combined), "isoform_to_gene.txt") isoform_to_gene_file = express.isoform_to_gene_name( gtf_file, isoform_to_gene_file, next(dd.sample_data_iterator(samples))) if len(to_combine) > 0: eff_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_counts" eff_counts_combined = count.combine_count_files(to_combine, eff_counts_combined_file, ext=".counts") to_combine = [dd.get_express_tpm(x) for x in dd.sample_data_iterator(samples) if dd.get_express_tpm(x)] tpm_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_tpm" tpm_counts_combined = count.combine_count_files(to_combine, tpm_counts_combined_file) to_combine = [dd.get_express_fpkm(x) for x in dd.sample_data_iterator(samples) if dd.get_express_fpkm(x)] fpkm_counts_combined_file = os.path.splitext(combined)[0] + ".isoform.express_fpkm" fpkm_counts_combined = count.combine_count_files(to_combine, fpkm_counts_combined_file, ext=".fpkm") return {'counts': eff_counts_combined, 'tpm': tpm_counts_combined, 'fpkm': fpkm_counts_combined, 'isoform_to_gene': isoform_to_gene_file} return {}
[ "def", "combine_express", "(", "samples", ",", "combined", ")", ":", "if", "not", "combined", ":", "return", "None", "to_combine", "=", "[", "dd", ".", "get_express_counts", "(", "x", ")", "for", "x", "in", "dd", ".", "sample_data_iterator", "(", "samples"...
Combine tpm, effective counts and fpkm from express results
[ "Combine", "tpm", "effective", "counts", "and", "fpkm", "from", "express", "results" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L296-L319
223,568
bcbio/bcbio-nextgen
bcbio/pipeline/rnaseq.py
run_cufflinks
def run_cufflinks(data): """Quantitate transcript expression with Cufflinks""" if "cufflinks" in dd.get_tools_off(data): return [[data]] work_bam = dd.get_work_bam(data) ref_file = dd.get_sam_ref(data) out_dir, fpkm_file, fpkm_isoform_file = cufflinks.run(work_bam, ref_file, data) data = dd.set_cufflinks_dir(data, out_dir) data = dd.set_fpkm(data, fpkm_file) data = dd.set_fpkm_isoform(data, fpkm_isoform_file) return [[data]]
python
def run_cufflinks(data): """Quantitate transcript expression with Cufflinks""" if "cufflinks" in dd.get_tools_off(data): return [[data]] work_bam = dd.get_work_bam(data) ref_file = dd.get_sam_ref(data) out_dir, fpkm_file, fpkm_isoform_file = cufflinks.run(work_bam, ref_file, data) data = dd.set_cufflinks_dir(data, out_dir) data = dd.set_fpkm(data, fpkm_file) data = dd.set_fpkm_isoform(data, fpkm_isoform_file) return [[data]]
[ "def", "run_cufflinks", "(", "data", ")", ":", "if", "\"cufflinks\"", "in", "dd", ".", "get_tools_off", "(", "data", ")", ":", "return", "[", "[", "data", "]", "]", "work_bam", "=", "dd", ".", "get_work_bam", "(", "data", ")", "ref_file", "=", "dd", ...
Quantitate transcript expression with Cufflinks
[ "Quantitate", "transcript", "expression", "with", "Cufflinks" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/rnaseq.py#L321-L331
223,569
bcbio/bcbio-nextgen
bcbio/rnaseq/express.py
run
def run(data): """Quantitaive isoforms expression by eXpress""" name = dd.get_sample_name(data) in_bam = dd.get_transcriptome_bam(data) config = data['config'] if not in_bam: logger.info("Transcriptome-mapped BAM file not found, skipping eXpress.") return data out_dir = os.path.join(dd.get_work_dir(data), "express", name) out_file = os.path.join(out_dir, name + ".xprs") express = config_utils.get_program("express", data['config']) strand = _set_stranded_flag(in_bam, data) if not file_exists(out_file): gtf_fasta = gtf.gtf_to_fasta(dd.get_gtf_file(data), dd.get_ref_file(data)) with tx_tmpdir(data) as tmp_dir: with file_transaction(data, out_dir) as tx_out_dir: bam_file = _prepare_bam_file(in_bam, tmp_dir, config) cmd = ("{express} --no-update-check -o {tx_out_dir} {strand} {gtf_fasta} {bam_file}") do.run(cmd.format(**locals()), "Run express on %s." % in_bam, {}) shutil.move(os.path.join(out_dir, "results.xprs"), out_file) eff_count_file = _get_column(out_file, out_file.replace(".xprs", "_eff.counts"), 7, data=data) tpm_file = _get_column(out_file, out_file.replace("xprs", "tpm"), 14, data=data) fpkm_file = _get_column(out_file, out_file.replace("xprs", "fpkm"), 10, data=data) data = dd.set_express_counts(data, eff_count_file) data = dd.set_express_tpm(data, tpm_file) data = dd.set_express_fpkm(data, fpkm_file) return data
python
def run(data): """Quantitaive isoforms expression by eXpress""" name = dd.get_sample_name(data) in_bam = dd.get_transcriptome_bam(data) config = data['config'] if not in_bam: logger.info("Transcriptome-mapped BAM file not found, skipping eXpress.") return data out_dir = os.path.join(dd.get_work_dir(data), "express", name) out_file = os.path.join(out_dir, name + ".xprs") express = config_utils.get_program("express", data['config']) strand = _set_stranded_flag(in_bam, data) if not file_exists(out_file): gtf_fasta = gtf.gtf_to_fasta(dd.get_gtf_file(data), dd.get_ref_file(data)) with tx_tmpdir(data) as tmp_dir: with file_transaction(data, out_dir) as tx_out_dir: bam_file = _prepare_bam_file(in_bam, tmp_dir, config) cmd = ("{express} --no-update-check -o {tx_out_dir} {strand} {gtf_fasta} {bam_file}") do.run(cmd.format(**locals()), "Run express on %s." % in_bam, {}) shutil.move(os.path.join(out_dir, "results.xprs"), out_file) eff_count_file = _get_column(out_file, out_file.replace(".xprs", "_eff.counts"), 7, data=data) tpm_file = _get_column(out_file, out_file.replace("xprs", "tpm"), 14, data=data) fpkm_file = _get_column(out_file, out_file.replace("xprs", "fpkm"), 10, data=data) data = dd.set_express_counts(data, eff_count_file) data = dd.set_express_tpm(data, tpm_file) data = dd.set_express_fpkm(data, fpkm_file) return data
[ "def", "run", "(", "data", ")", ":", "name", "=", "dd", ".", "get_sample_name", "(", "data", ")", "in_bam", "=", "dd", ".", "get_transcriptome_bam", "(", "data", ")", "config", "=", "data", "[", "'config'", "]", "if", "not", "in_bam", ":", "logger", ...
Quantitaive isoforms expression by eXpress
[ "Quantitaive", "isoforms", "expression", "by", "eXpress" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/express.py#L13-L39
223,570
bcbio/bcbio-nextgen
bcbio/rnaseq/express.py
_get_column
def _get_column(in_file, out_file, column, data=None): """Subset one column from a file """ with file_transaction(data, out_file) as tx_out_file: with open(in_file) as in_handle: with open(tx_out_file, 'w') as out_handle: for line in in_handle: cols = line.strip().split("\t") if line.find("eff_count") > 0: continue number = cols[column] if column == 7: number = int(round(float(number), 0)) out_handle.write("%s\t%s\n" % (cols[1], number)) return out_file
python
def _get_column(in_file, out_file, column, data=None): """Subset one column from a file """ with file_transaction(data, out_file) as tx_out_file: with open(in_file) as in_handle: with open(tx_out_file, 'w') as out_handle: for line in in_handle: cols = line.strip().split("\t") if line.find("eff_count") > 0: continue number = cols[column] if column == 7: number = int(round(float(number), 0)) out_handle.write("%s\t%s\n" % (cols[1], number)) return out_file
[ "def", "_get_column", "(", "in_file", ",", "out_file", ",", "column", ",", "data", "=", "None", ")", ":", "with", "file_transaction", "(", "data", ",", "out_file", ")", "as", "tx_out_file", ":", "with", "open", "(", "in_file", ")", "as", "in_handle", ":"...
Subset one column from a file
[ "Subset", "one", "column", "from", "a", "file" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/express.py#L41-L55
223,571
bcbio/bcbio-nextgen
bcbio/rnaseq/express.py
_prepare_bam_file
def _prepare_bam_file(bam_file, tmp_dir, config): """ Pipe sort by name cmd in case sort by coordinates """ sort_mode = _get_sort_order(bam_file, config) if sort_mode != "queryname": bam_file = sort(bam_file, config, "queryname") return bam_file
python
def _prepare_bam_file(bam_file, tmp_dir, config): """ Pipe sort by name cmd in case sort by coordinates """ sort_mode = _get_sort_order(bam_file, config) if sort_mode != "queryname": bam_file = sort(bam_file, config, "queryname") return bam_file
[ "def", "_prepare_bam_file", "(", "bam_file", ",", "tmp_dir", ",", "config", ")", ":", "sort_mode", "=", "_get_sort_order", "(", "bam_file", ",", "config", ")", "if", "sort_mode", "!=", "\"queryname\"", ":", "bam_file", "=", "sort", "(", "bam_file", ",", "con...
Pipe sort by name cmd in case sort by coordinates
[ "Pipe", "sort", "by", "name", "cmd", "in", "case", "sort", "by", "coordinates" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/express.py#L72-L79
223,572
bcbio/bcbio-nextgen
bcbio/rnaseq/express.py
isoform_to_gene_name
def isoform_to_gene_name(gtf_file, out_file, data): """ produce a table of isoform -> gene mappings for loading into EBSeq """ if not out_file: out_file = tempfile.NamedTemporaryFile(delete=False).name if file_exists(out_file): return out_file db = gtf.get_gtf_db(gtf_file) line_format = "{transcript}\t{gene}\n" with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: for feature in db.features_of_type('transcript'): transcript = feature['transcript_id'][0] gene = feature['gene_id'][0] out_handle.write(line_format.format(**locals())) return out_file
python
def isoform_to_gene_name(gtf_file, out_file, data): """ produce a table of isoform -> gene mappings for loading into EBSeq """ if not out_file: out_file = tempfile.NamedTemporaryFile(delete=False).name if file_exists(out_file): return out_file db = gtf.get_gtf_db(gtf_file) line_format = "{transcript}\t{gene}\n" with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: for feature in db.features_of_type('transcript'): transcript = feature['transcript_id'][0] gene = feature['gene_id'][0] out_handle.write(line_format.format(**locals())) return out_file
[ "def", "isoform_to_gene_name", "(", "gtf_file", ",", "out_file", ",", "data", ")", ":", "if", "not", "out_file", ":", "out_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", ".", "name", "if", "file_exists", "(", "out_file",...
produce a table of isoform -> gene mappings for loading into EBSeq
[ "produce", "a", "table", "of", "isoform", "-", ">", "gene", "mappings", "for", "loading", "into", "EBSeq" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/express.py#L81-L97
223,573
bcbio/bcbio-nextgen
bcbio/variation/samtools.py
shared_variantcall
def shared_variantcall(call_fn, name, align_bams, ref_file, items, assoc_files, region=None, out_file=None): """Provide base functionality for prepping and indexing for variant calling. """ config = items[0]["config"] if out_file is None: if vcfutils.is_paired_analysis(align_bams, items): out_file = "%s-paired-variants.vcf.gz" % config["metdata"]["batch"] else: out_file = "%s-variants.vcf.gz" % os.path.splitext(align_bams[0])[0] if not file_exists(out_file): logger.debug("Genotyping with {name}: {region} {fname}".format( name=name, region=region, fname=os.path.basename(align_bams[0]))) variant_regions = bedutils.population_variant_regions(items, merged=True) target_regions = subset_variant_regions(variant_regions, region, out_file, items=items) if (variant_regions is not None and isinstance(target_regions, six.string_types) and not os.path.isfile(target_regions)): vcfutils.write_empty_vcf(out_file, config) else: with file_transaction(config, out_file) as tx_out_file: call_fn(align_bams, ref_file, items, target_regions, tx_out_file) if out_file.endswith(".gz"): out_file = vcfutils.bgzip_and_index(out_file, config) return out_file
python
def shared_variantcall(call_fn, name, align_bams, ref_file, items, assoc_files, region=None, out_file=None): """Provide base functionality for prepping and indexing for variant calling. """ config = items[0]["config"] if out_file is None: if vcfutils.is_paired_analysis(align_bams, items): out_file = "%s-paired-variants.vcf.gz" % config["metdata"]["batch"] else: out_file = "%s-variants.vcf.gz" % os.path.splitext(align_bams[0])[0] if not file_exists(out_file): logger.debug("Genotyping with {name}: {region} {fname}".format( name=name, region=region, fname=os.path.basename(align_bams[0]))) variant_regions = bedutils.population_variant_regions(items, merged=True) target_regions = subset_variant_regions(variant_regions, region, out_file, items=items) if (variant_regions is not None and isinstance(target_regions, six.string_types) and not os.path.isfile(target_regions)): vcfutils.write_empty_vcf(out_file, config) else: with file_transaction(config, out_file) as tx_out_file: call_fn(align_bams, ref_file, items, target_regions, tx_out_file) if out_file.endswith(".gz"): out_file = vcfutils.bgzip_and_index(out_file, config) return out_file
[ "def", "shared_variantcall", "(", "call_fn", ",", "name", ",", "align_bams", ",", "ref_file", ",", "items", ",", "assoc_files", ",", "region", "=", "None", ",", "out_file", "=", "None", ")", ":", "config", "=", "items", "[", "0", "]", "[", "\"config\"", ...
Provide base functionality for prepping and indexing for variant calling.
[ "Provide", "base", "functionality", "for", "prepping", "and", "indexing", "for", "variant", "calling", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/samtools.py#L19-L43
223,574
bcbio/bcbio-nextgen
bcbio/variation/samtools.py
run_samtools
def run_samtools(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Detect SNPs and indels with samtools mpileup and bcftools. """ return shared_variantcall(_call_variants_samtools, "samtools", align_bams, ref_file, items, assoc_files, region, out_file)
python
def run_samtools(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Detect SNPs and indels with samtools mpileup and bcftools. """ return shared_variantcall(_call_variants_samtools, "samtools", align_bams, ref_file, items, assoc_files, region, out_file)
[ "def", "run_samtools", "(", "align_bams", ",", "items", ",", "ref_file", ",", "assoc_files", ",", "region", "=", "None", ",", "out_file", "=", "None", ")", ":", "return", "shared_variantcall", "(", "_call_variants_samtools", ",", "\"samtools\"", ",", "align_bams...
Detect SNPs and indels with samtools mpileup and bcftools.
[ "Detect", "SNPs", "and", "indels", "with", "samtools", "mpileup", "and", "bcftools", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/samtools.py#L45-L50
223,575
bcbio/bcbio-nextgen
bcbio/variation/samtools.py
_call_variants_samtools
def _call_variants_samtools(align_bams, ref_file, items, target_regions, tx_out_file): """Call variants with samtools in target_regions. Works around a GATK VCF 4.2 compatibility issue in samtools 1.0 by removing addition 4.2-only isms from VCF header lines. """ config = items[0]["config"] mpileup = prep_mpileup(align_bams, ref_file, config, target_regions=target_regions, want_bcf=True) bcftools = config_utils.get_program("bcftools", config) samtools_version = programs.get_version("samtools", config=config) if samtools_version and LooseVersion(samtools_version) <= LooseVersion("0.1.19"): raise ValueError("samtools calling not supported with pre-1.0 samtools") bcftools_opts = "call -v -m" compress_cmd = "| bgzip -c" if tx_out_file.endswith(".gz") else "" fix_ambig_ref = vcfutils.fix_ambiguous_cl() fix_ambig_alt = vcfutils.fix_ambiguous_cl(5) cmd = ("{mpileup} " "| {bcftools} {bcftools_opts} - " "| {fix_ambig_ref} | {fix_ambig_alt} " "| vt normalize -n -q -r {ref_file} - " "| sed 's/VCFv4.2/VCFv4.1/' " "| sed 's/,Version=3>/>/' " "| sed 's/,Version=\"3\">/>/' " "| sed 's/Number=R/Number=./' " "{compress_cmd} > {tx_out_file}") do.run(cmd.format(**locals()), "Variant calling with samtools", items[0])
python
def _call_variants_samtools(align_bams, ref_file, items, target_regions, tx_out_file): """Call variants with samtools in target_regions. Works around a GATK VCF 4.2 compatibility issue in samtools 1.0 by removing addition 4.2-only isms from VCF header lines. """ config = items[0]["config"] mpileup = prep_mpileup(align_bams, ref_file, config, target_regions=target_regions, want_bcf=True) bcftools = config_utils.get_program("bcftools", config) samtools_version = programs.get_version("samtools", config=config) if samtools_version and LooseVersion(samtools_version) <= LooseVersion("0.1.19"): raise ValueError("samtools calling not supported with pre-1.0 samtools") bcftools_opts = "call -v -m" compress_cmd = "| bgzip -c" if tx_out_file.endswith(".gz") else "" fix_ambig_ref = vcfutils.fix_ambiguous_cl() fix_ambig_alt = vcfutils.fix_ambiguous_cl(5) cmd = ("{mpileup} " "| {bcftools} {bcftools_opts} - " "| {fix_ambig_ref} | {fix_ambig_alt} " "| vt normalize -n -q -r {ref_file} - " "| sed 's/VCFv4.2/VCFv4.1/' " "| sed 's/,Version=3>/>/' " "| sed 's/,Version=\"3\">/>/' " "| sed 's/Number=R/Number=./' " "{compress_cmd} > {tx_out_file}") do.run(cmd.format(**locals()), "Variant calling with samtools", items[0])
[ "def", "_call_variants_samtools", "(", "align_bams", ",", "ref_file", ",", "items", ",", "target_regions", ",", "tx_out_file", ")", ":", "config", "=", "items", "[", "0", "]", "[", "\"config\"", "]", "mpileup", "=", "prep_mpileup", "(", "align_bams", ",", "r...
Call variants with samtools in target_regions. Works around a GATK VCF 4.2 compatibility issue in samtools 1.0 by removing addition 4.2-only isms from VCF header lines.
[ "Call", "variants", "with", "samtools", "in", "target_regions", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/samtools.py#L68-L94
223,576
bcbio/bcbio-nextgen
bcbio/pipeline/sra.py
_convert_fastq
def _convert_fastq(srafn, outdir, single=False): "convert sra to fastq" cmd = "fastq-dump --split-files --gzip {srafn}" cmd = "%s %s" % (utils.local_path_export(), cmd) sraid = os.path.basename(utils.splitext_plus(srafn)[0]) if not srafn: return None if not single: out_file = [os.path.join(outdir, "%s_1.fastq.gz" % sraid), os.path.join(outdir, "%s_2.fastq.gz" % sraid)] if not utils.file_exists(out_file[0]): with utils.chdir(outdir): do.run(cmd.format(**locals()), "Covert to fastq %s" % sraid) if not utils.file_exists(out_file[0]): raise IOError("SRA %s didn't convert, something happened." % srafn) return [out for out in out_file if utils.file_exists(out)] else: raise ValueError("Not supported single-end sra samples for now.")
python
def _convert_fastq(srafn, outdir, single=False): "convert sra to fastq" cmd = "fastq-dump --split-files --gzip {srafn}" cmd = "%s %s" % (utils.local_path_export(), cmd) sraid = os.path.basename(utils.splitext_plus(srafn)[0]) if not srafn: return None if not single: out_file = [os.path.join(outdir, "%s_1.fastq.gz" % sraid), os.path.join(outdir, "%s_2.fastq.gz" % sraid)] if not utils.file_exists(out_file[0]): with utils.chdir(outdir): do.run(cmd.format(**locals()), "Covert to fastq %s" % sraid) if not utils.file_exists(out_file[0]): raise IOError("SRA %s didn't convert, something happened." % srafn) return [out for out in out_file if utils.file_exists(out)] else: raise ValueError("Not supported single-end sra samples for now.")
[ "def", "_convert_fastq", "(", "srafn", ",", "outdir", ",", "single", "=", "False", ")", ":", "cmd", "=", "\"fastq-dump --split-files --gzip {srafn}\"", "cmd", "=", "\"%s %s\"", "%", "(", "utils", ".", "local_path_export", "(", ")", ",", "cmd", ")", "sraid", ...
convert sra to fastq
[ "convert", "sra", "to", "fastq" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/sra.py#L119-L136
223,577
bcbio/bcbio-nextgen
bcbio/illumina/machine.py
check_and_postprocess
def check_and_postprocess(args): """Check for newly dumped sequencer output, post-processing and transferring. """ with open(args.process_config) as in_handle: config = yaml.safe_load(in_handle) setup_local_logging(config) for dname in _find_unprocessed(config): lane_details = nglims.get_runinfo(config["galaxy_url"], config["galaxy_apikey"], dname, utils.get_in(config, ("process", "storedir"))) if isinstance(lane_details, dict) and "error" in lane_details: print("Flowcell not found in Galaxy: %s" % lane_details) else: lane_details = _tweak_lane(lane_details, dname) fcid_ss = samplesheet.from_flowcell(dname, lane_details) _update_reported(config["msg_db"], dname) fastq_dir = demultiplex.run_bcl2fastq(dname, fcid_ss, config) bcbio_config, ready_fastq_dir = nglims.prep_samples_and_config(dname, lane_details, fastq_dir, config) transfer.copy_flowcell(dname, ready_fastq_dir, bcbio_config, config) _start_processing(dname, bcbio_config, config)
python
def check_and_postprocess(args): """Check for newly dumped sequencer output, post-processing and transferring. """ with open(args.process_config) as in_handle: config = yaml.safe_load(in_handle) setup_local_logging(config) for dname in _find_unprocessed(config): lane_details = nglims.get_runinfo(config["galaxy_url"], config["galaxy_apikey"], dname, utils.get_in(config, ("process", "storedir"))) if isinstance(lane_details, dict) and "error" in lane_details: print("Flowcell not found in Galaxy: %s" % lane_details) else: lane_details = _tweak_lane(lane_details, dname) fcid_ss = samplesheet.from_flowcell(dname, lane_details) _update_reported(config["msg_db"], dname) fastq_dir = demultiplex.run_bcl2fastq(dname, fcid_ss, config) bcbio_config, ready_fastq_dir = nglims.prep_samples_and_config(dname, lane_details, fastq_dir, config) transfer.copy_flowcell(dname, ready_fastq_dir, bcbio_config, config) _start_processing(dname, bcbio_config, config)
[ "def", "check_and_postprocess", "(", "args", ")", ":", "with", "open", "(", "args", ".", "process_config", ")", "as", "in_handle", ":", "config", "=", "yaml", ".", "safe_load", "(", "in_handle", ")", "setup_local_logging", "(", "config", ")", "for", "dname",...
Check for newly dumped sequencer output, post-processing and transferring.
[ "Check", "for", "newly", "dumped", "sequencer", "output", "post", "-", "processing", "and", "transferring", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L22-L40
223,578
bcbio/bcbio-nextgen
bcbio/illumina/machine.py
_tweak_lane
def _tweak_lane(lane_details, dname): """Potentially tweak lane information to handle custom processing, reading a lane_config.yaml file. """ tweak_config_file = os.path.join(dname, "lane_config.yaml") if os.path.exists(tweak_config_file): with open(tweak_config_file) as in_handle: tweak_config = yaml.safe_load(in_handle) if tweak_config.get("uniquify_lanes"): out = [] for ld in lane_details: ld["name"] = "%s-%s" % (ld["name"], ld["lane"]) out.append(ld) return out return lane_details
python
def _tweak_lane(lane_details, dname): """Potentially tweak lane information to handle custom processing, reading a lane_config.yaml file. """ tweak_config_file = os.path.join(dname, "lane_config.yaml") if os.path.exists(tweak_config_file): with open(tweak_config_file) as in_handle: tweak_config = yaml.safe_load(in_handle) if tweak_config.get("uniquify_lanes"): out = [] for ld in lane_details: ld["name"] = "%s-%s" % (ld["name"], ld["lane"]) out.append(ld) return out return lane_details
[ "def", "_tweak_lane", "(", "lane_details", ",", "dname", ")", ":", "tweak_config_file", "=", "os", ".", "path", ".", "join", "(", "dname", ",", "\"lane_config.yaml\"", ")", "if", "os", ".", "path", ".", "exists", "(", "tweak_config_file", ")", ":", "with",...
Potentially tweak lane information to handle custom processing, reading a lane_config.yaml file.
[ "Potentially", "tweak", "lane", "information", "to", "handle", "custom", "processing", "reading", "a", "lane_config", ".", "yaml", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L42-L55
223,579
bcbio/bcbio-nextgen
bcbio/illumina/machine.py
_remap_dirname
def _remap_dirname(local, remote): """Remap directory names from local to remote. """ def do(x): return x.replace(local, remote, 1) return do
python
def _remap_dirname(local, remote): """Remap directory names from local to remote. """ def do(x): return x.replace(local, remote, 1) return do
[ "def", "_remap_dirname", "(", "local", ",", "remote", ")", ":", "def", "do", "(", "x", ")", ":", "return", "x", ".", "replace", "(", "local", ",", "remote", ",", "1", ")", "return", "do" ]
Remap directory names from local to remote.
[ "Remap", "directory", "names", "from", "local", "to", "remote", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L57-L62
223,580
bcbio/bcbio-nextgen
bcbio/illumina/machine.py
_find_unprocessed
def _find_unprocessed(config): """Find any finished directories that have not been processed. """ reported = _read_reported(config["msg_db"]) for dname in _get_directories(config): if os.path.isdir(dname) and dname not in reported: if _is_finished_dumping(dname): yield dname
python
def _find_unprocessed(config): """Find any finished directories that have not been processed. """ reported = _read_reported(config["msg_db"]) for dname in _get_directories(config): if os.path.isdir(dname) and dname not in reported: if _is_finished_dumping(dname): yield dname
[ "def", "_find_unprocessed", "(", "config", ")", ":", "reported", "=", "_read_reported", "(", "config", "[", "\"msg_db\"", "]", ")", "for", "dname", "in", "_get_directories", "(", "config", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "dname", ")...
Find any finished directories that have not been processed.
[ "Find", "any", "finished", "directories", "that", "have", "not", "been", "processed", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L98-L105
223,581
bcbio/bcbio-nextgen
bcbio/illumina/machine.py
_is_finished_dumping
def _is_finished_dumping(directory): """Determine if the sequencing directory has all files. The final checkpoint file will differ depending if we are a single or paired end run. """ #if _is_finished_dumping_checkpoint(directory): # return True # Check final output files; handles both HiSeq and GAII run_info = os.path.join(directory, "RunInfo.xml") hi_seq_checkpoint = "Basecalling_Netcopy_complete_Read%s.txt" % \ _expected_reads(run_info) to_check = ["Basecalling_Netcopy_complete_SINGLEREAD.txt", "Basecalling_Netcopy_complete_READ2.txt", hi_seq_checkpoint] return reduce(operator.or_, [os.path.exists(os.path.join(directory, f)) for f in to_check])
python
def _is_finished_dumping(directory): """Determine if the sequencing directory has all files. The final checkpoint file will differ depending if we are a single or paired end run. """ #if _is_finished_dumping_checkpoint(directory): # return True # Check final output files; handles both HiSeq and GAII run_info = os.path.join(directory, "RunInfo.xml") hi_seq_checkpoint = "Basecalling_Netcopy_complete_Read%s.txt" % \ _expected_reads(run_info) to_check = ["Basecalling_Netcopy_complete_SINGLEREAD.txt", "Basecalling_Netcopy_complete_READ2.txt", hi_seq_checkpoint] return reduce(operator.or_, [os.path.exists(os.path.join(directory, f)) for f in to_check])
[ "def", "_is_finished_dumping", "(", "directory", ")", ":", "#if _is_finished_dumping_checkpoint(directory):", "# return True", "# Check final output files; handles both HiSeq and GAII", "run_info", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "\"RunInfo.xml\""...
Determine if the sequencing directory has all files. The final checkpoint file will differ depending if we are a single or paired end run.
[ "Determine", "if", "the", "sequencing", "directory", "has", "all", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L113-L129
223,582
bcbio/bcbio-nextgen
bcbio/illumina/machine.py
_expected_reads
def _expected_reads(run_info_file): """Parse the number of expected reads from the RunInfo.xml file. """ reads = [] if os.path.exists(run_info_file): tree = ElementTree() tree.parse(run_info_file) read_elem = tree.find("Run/Reads") reads = read_elem.findall("Read") return len(reads)
python
def _expected_reads(run_info_file): """Parse the number of expected reads from the RunInfo.xml file. """ reads = [] if os.path.exists(run_info_file): tree = ElementTree() tree.parse(run_info_file) read_elem = tree.find("Run/Reads") reads = read_elem.findall("Read") return len(reads)
[ "def", "_expected_reads", "(", "run_info_file", ")", ":", "reads", "=", "[", "]", "if", "os", ".", "path", ".", "exists", "(", "run_info_file", ")", ":", "tree", "=", "ElementTree", "(", ")", "tree", ".", "parse", "(", "run_info_file", ")", "read_elem", ...
Parse the number of expected reads from the RunInfo.xml file.
[ "Parse", "the", "number", "of", "expected", "reads", "from", "the", "RunInfo", ".", "xml", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L149-L158
223,583
bcbio/bcbio-nextgen
bcbio/illumina/machine.py
_read_reported
def _read_reported(msg_db): """Retrieve a list of directories previous reported. """ reported = [] if os.path.exists(msg_db): with open(msg_db) as in_handle: for line in in_handle: reported.append(line.strip()) return reported
python
def _read_reported(msg_db): """Retrieve a list of directories previous reported. """ reported = [] if os.path.exists(msg_db): with open(msg_db) as in_handle: for line in in_handle: reported.append(line.strip()) return reported
[ "def", "_read_reported", "(", "msg_db", ")", ":", "reported", "=", "[", "]", "if", "os", ".", "path", ".", "exists", "(", "msg_db", ")", ":", "with", "open", "(", "msg_db", ")", "as", "in_handle", ":", "for", "line", "in", "in_handle", ":", "reported...
Retrieve a list of directories previous reported.
[ "Retrieve", "a", "list", "of", "directories", "previous", "reported", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/machine.py#L162-L170
223,584
bcbio/bcbio-nextgen
bcbio/qc/viral.py
get_files
def get_files(data): """Retrieve pre-installed viral reference files. """ all_files = glob.glob(os.path.normpath(os.path.join(os.path.dirname(dd.get_ref_file(data)), os.pardir, "viral", "*"))) return sorted(all_files)
python
def get_files(data): """Retrieve pre-installed viral reference files. """ all_files = glob.glob(os.path.normpath(os.path.join(os.path.dirname(dd.get_ref_file(data)), os.pardir, "viral", "*"))) return sorted(all_files)
[ "def", "get_files", "(", "data", ")", ":", "all_files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "dd", ".", "get_ref_file", "(", "data", "...
Retrieve pre-installed viral reference files.
[ "Retrieve", "pre", "-", "installed", "viral", "reference", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/viral.py#L59-L64
223,585
bcbio/bcbio-nextgen
bcbio/rnaseq/variation.py
gatk_splitreads
def gatk_splitreads(data): """ use GATK to split reads with Ns in the CIGAR string, hard clipping regions that end up in introns """ broad_runner = broad.runner_from_config(dd.get_config(data)) ref_file = dd.get_ref_file(data) deduped_bam = dd.get_deduped_bam(data) base, ext = os.path.splitext(deduped_bam) split_bam = base + ".splitN" + ext if file_exists(split_bam): data = dd.set_split_bam(data, split_bam) return data gatk_type = broad_runner.gatk_type() with file_transaction(data, split_bam) as tx_split_bam: params = ["-T", "SplitNCigarReads", "-R", ref_file, "-I", deduped_bam] if gatk_type == "gatk4": params += ["--output", tx_split_bam] else: params += ["-rf", "ReassignOneMappingQuality", "-RMQF", "255", "-RMQT", "60", "-rf", "UnmappedRead", "-U", "ALLOW_N_CIGAR_READS", "-o", tx_split_bam] if dd.get_quality_format(data) == "illumina": params += ["--fix_misencoded_quality_scores", "-fixMisencodedQuals"] broad_runner.run_gatk(params) bam.index(split_bam, dd.get_config(data)) data = dd.set_split_bam(data, split_bam) return data
python
def gatk_splitreads(data): """ use GATK to split reads with Ns in the CIGAR string, hard clipping regions that end up in introns """ broad_runner = broad.runner_from_config(dd.get_config(data)) ref_file = dd.get_ref_file(data) deduped_bam = dd.get_deduped_bam(data) base, ext = os.path.splitext(deduped_bam) split_bam = base + ".splitN" + ext if file_exists(split_bam): data = dd.set_split_bam(data, split_bam) return data gatk_type = broad_runner.gatk_type() with file_transaction(data, split_bam) as tx_split_bam: params = ["-T", "SplitNCigarReads", "-R", ref_file, "-I", deduped_bam] if gatk_type == "gatk4": params += ["--output", tx_split_bam] else: params += ["-rf", "ReassignOneMappingQuality", "-RMQF", "255", "-RMQT", "60", "-rf", "UnmappedRead", "-U", "ALLOW_N_CIGAR_READS", "-o", tx_split_bam] if dd.get_quality_format(data) == "illumina": params += ["--fix_misencoded_quality_scores", "-fixMisencodedQuals"] broad_runner.run_gatk(params) bam.index(split_bam, dd.get_config(data)) data = dd.set_split_bam(data, split_bam) return data
[ "def", "gatk_splitreads", "(", "data", ")", ":", "broad_runner", "=", "broad", ".", "runner_from_config", "(", "dd", ".", "get_config", "(", "data", ")", ")", "ref_file", "=", "dd", ".", "get_ref_file", "(", "data", ")", "deduped_bam", "=", "dd", ".", "g...
use GATK to split reads with Ns in the CIGAR string, hard clipping regions that end up in introns
[ "use", "GATK", "to", "split", "reads", "with", "Ns", "in", "the", "CIGAR", "string", "hard", "clipping", "regions", "that", "end", "up", "in", "introns" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/variation.py#L25-L57
223,586
bcbio/bcbio-nextgen
bcbio/rnaseq/variation.py
_setup_variant_regions
def _setup_variant_regions(data, out_dir): """Ensure we have variant regions for calling, using transcript if not present. Respects noalt_calling by removing additional contigs to improve speeds. """ vr_file = dd.get_variant_regions(data) if not vr_file: vr_file = regions.get_sv_bed(data, "transcripts", out_dir=out_dir) contigs = set([c.name for c in ref.file_contigs(dd.get_ref_file(data))]) out_file = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "bedprep")), "%s-rnaseq_clean.bed" % utils.splitext_plus(os.path.basename(vr_file))[0]) if not utils.file_uptodate(out_file, vr_file): with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: with shared.bedtools_tmpdir(data): for r in pybedtools.BedTool(vr_file): if r.chrom in contigs: if chromhacks.is_nonalt(r.chrom): out_handle.write(str(r)) data = dd.set_variant_regions(data, out_file) return data
python
def _setup_variant_regions(data, out_dir): """Ensure we have variant regions for calling, using transcript if not present. Respects noalt_calling by removing additional contigs to improve speeds. """ vr_file = dd.get_variant_regions(data) if not vr_file: vr_file = regions.get_sv_bed(data, "transcripts", out_dir=out_dir) contigs = set([c.name for c in ref.file_contigs(dd.get_ref_file(data))]) out_file = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "bedprep")), "%s-rnaseq_clean.bed" % utils.splitext_plus(os.path.basename(vr_file))[0]) if not utils.file_uptodate(out_file, vr_file): with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: with shared.bedtools_tmpdir(data): for r in pybedtools.BedTool(vr_file): if r.chrom in contigs: if chromhacks.is_nonalt(r.chrom): out_handle.write(str(r)) data = dd.set_variant_regions(data, out_file) return data
[ "def", "_setup_variant_regions", "(", "data", ",", "out_dir", ")", ":", "vr_file", "=", "dd", ".", "get_variant_regions", "(", "data", ")", "if", "not", "vr_file", ":", "vr_file", "=", "regions", ".", "get_sv_bed", "(", "data", ",", "\"transcripts\"", ",", ...
Ensure we have variant regions for calling, using transcript if not present. Respects noalt_calling by removing additional contigs to improve speeds.
[ "Ensure", "we", "have", "variant", "regions", "for", "calling", "using", "transcript", "if", "not", "present", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/variation.py#L59-L80
223,587
bcbio/bcbio-nextgen
bcbio/rnaseq/variation.py
gatk_rnaseq_calling
def gatk_rnaseq_calling(data): """Use GATK to perform gVCF variant calling on RNA-seq data """ from bcbio.bam import callable data = utils.deepish_copy(data) tools_on = dd.get_tools_on(data) if not tools_on: tools_on = [] tools_on.append("gvcf") data = dd.set_tools_on(data, tools_on) data = dd.set_jointcaller(data, ["%s-joint" % v for v in dd.get_variantcaller(data)]) out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "variation", "rnaseq", "gatk-haplotype")) data = _setup_variant_regions(data, out_dir) out_file = os.path.join(out_dir, "%s-gatk-haplotype.vcf.gz" % dd.get_sample_name(data)) if not utils.file_exists(out_file): region_files = [] regions = [] for cur_region in callable.get_split_regions(dd.get_variant_regions(data), data): str_region = "_".join([str(x) for x in cur_region]) region_file = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "variation", "rnaseq", "gatk-haplotype", "regions")), "%s-%s-gatk-haplotype.vcf.gz" % (dd.get_sample_name(data), str_region)) region_file = gatk.haplotype_caller([dd.get_split_bam(data)], [data], dd.get_ref_file(data), {}, region=cur_region, out_file=region_file) region_files.append(region_file) regions.append(cur_region) out_file = vcfutils.concat_variant_files(region_files, out_file, regions, dd.get_ref_file(data), data["config"]) return dd.set_vrn_file(data, out_file)
python
def gatk_rnaseq_calling(data): """Use GATK to perform gVCF variant calling on RNA-seq data """ from bcbio.bam import callable data = utils.deepish_copy(data) tools_on = dd.get_tools_on(data) if not tools_on: tools_on = [] tools_on.append("gvcf") data = dd.set_tools_on(data, tools_on) data = dd.set_jointcaller(data, ["%s-joint" % v for v in dd.get_variantcaller(data)]) out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "variation", "rnaseq", "gatk-haplotype")) data = _setup_variant_regions(data, out_dir) out_file = os.path.join(out_dir, "%s-gatk-haplotype.vcf.gz" % dd.get_sample_name(data)) if not utils.file_exists(out_file): region_files = [] regions = [] for cur_region in callable.get_split_regions(dd.get_variant_regions(data), data): str_region = "_".join([str(x) for x in cur_region]) region_file = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "variation", "rnaseq", "gatk-haplotype", "regions")), "%s-%s-gatk-haplotype.vcf.gz" % (dd.get_sample_name(data), str_region)) region_file = gatk.haplotype_caller([dd.get_split_bam(data)], [data], dd.get_ref_file(data), {}, region=cur_region, out_file=region_file) region_files.append(region_file) regions.append(cur_region) out_file = vcfutils.concat_variant_files(region_files, out_file, regions, dd.get_ref_file(data), data["config"]) return dd.set_vrn_file(data, out_file)
[ "def", "gatk_rnaseq_calling", "(", "data", ")", ":", "from", "bcbio", ".", "bam", "import", "callable", "data", "=", "utils", ".", "deepish_copy", "(", "data", ")", "tools_on", "=", "dd", ".", "get_tools_on", "(", "data", ")", "if", "not", "tools_on", ":...
Use GATK to perform gVCF variant calling on RNA-seq data
[ "Use", "GATK", "to", "perform", "gVCF", "variant", "calling", "on", "RNA", "-", "seq", "data" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/variation.py#L82-L112
223,588
bcbio/bcbio-nextgen
bcbio/rnaseq/variation.py
filter_junction_variants
def filter_junction_variants(vrn_file, data): """ filter out variants within 10 basepairs of a splice junction, these are very prone to being false positives with RNA-seq data """ SJ_BP_MASK = 10 vrn_dir = os.path.dirname(vrn_file) splicebed = dd.get_junction_bed(data) if not file_exists(splicebed): logger.info("Splice junction BED file not found, skipping filtering of " "variants closed to splice junctions.") return vrn_file spliceslop = get_padded_bed_file(vrn_dir, splicebed, SJ_BP_MASK, data) out_file = os.path.splitext(vrn_file)[0] + "-junctionfiltered.vcf.gz" if file_exists(out_file): return out_file with file_transaction(data, out_file) as tx_out_file: out_base = os.path.splitext(tx_out_file)[0] logger.info("Removing variants within %d bases of splice junctions listed in %s from %s. " % (SJ_BP_MASK, spliceslop, vrn_file)) pybedtools.BedTool(vrn_file).intersect(spliceslop, wa=True, header=True, v=True).saveas(out_base) tx_out_file = vcfutils.bgzip_and_index(out_base, dd.get_config(data)) return out_file
python
def filter_junction_variants(vrn_file, data): """ filter out variants within 10 basepairs of a splice junction, these are very prone to being false positives with RNA-seq data """ SJ_BP_MASK = 10 vrn_dir = os.path.dirname(vrn_file) splicebed = dd.get_junction_bed(data) if not file_exists(splicebed): logger.info("Splice junction BED file not found, skipping filtering of " "variants closed to splice junctions.") return vrn_file spliceslop = get_padded_bed_file(vrn_dir, splicebed, SJ_BP_MASK, data) out_file = os.path.splitext(vrn_file)[0] + "-junctionfiltered.vcf.gz" if file_exists(out_file): return out_file with file_transaction(data, out_file) as tx_out_file: out_base = os.path.splitext(tx_out_file)[0] logger.info("Removing variants within %d bases of splice junctions listed in %s from %s. " % (SJ_BP_MASK, spliceslop, vrn_file)) pybedtools.BedTool(vrn_file).intersect(spliceslop, wa=True, header=True, v=True).saveas(out_base) tx_out_file = vcfutils.bgzip_and_index(out_base, dd.get_config(data)) return out_file
[ "def", "filter_junction_variants", "(", "vrn_file", ",", "data", ")", ":", "SJ_BP_MASK", "=", "10", "vrn_dir", "=", "os", ".", "path", ".", "dirname", "(", "vrn_file", ")", "splicebed", "=", "dd", ".", "get_junction_bed", "(", "data", ")", "if", "not", "...
filter out variants within 10 basepairs of a splice junction, these are very prone to being false positives with RNA-seq data
[ "filter", "out", "variants", "within", "10", "basepairs", "of", "a", "splice", "junction", "these", "are", "very", "prone", "to", "being", "false", "positives", "with", "RNA", "-", "seq", "data" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/variation.py#L186-L207
223,589
bcbio/bcbio-nextgen
scripts/bcbio_nextgen_install.py
_clean_args
def _clean_args(sys_argv, args): """Remove data directory from arguments to pass to upgrade function. """ base = [x for x in sys_argv if x.startswith("-") or not args.datadir == os.path.abspath(os.path.expanduser(x))] # Remove installer only options we don't pass on base = [x for x in base if x not in set(["--minimize-disk"])] if "--nodata" in base: base.remove("--nodata") else: base.append("--data") return base
python
def _clean_args(sys_argv, args): """Remove data directory from arguments to pass to upgrade function. """ base = [x for x in sys_argv if x.startswith("-") or not args.datadir == os.path.abspath(os.path.expanduser(x))] # Remove installer only options we don't pass on base = [x for x in base if x not in set(["--minimize-disk"])] if "--nodata" in base: base.remove("--nodata") else: base.append("--data") return base
[ "def", "_clean_args", "(", "sys_argv", ",", "args", ")", ":", "base", "=", "[", "x", "for", "x", "in", "sys_argv", "if", "x", ".", "startswith", "(", "\"-\"", ")", "or", "not", "args", ".", "datadir", "==", "os", ".", "path", ".", "abspath", "(", ...
Remove data directory from arguments to pass to upgrade function.
[ "Remove", "data", "directory", "from", "arguments", "to", "pass", "to", "upgrade", "function", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/bcbio_nextgen_install.py#L53-L64
223,590
bcbio/bcbio-nextgen
scripts/bcbio_nextgen_install.py
setup_manifest
def setup_manifest(datadir): """Create barebones manifest to be filled in during update """ manifest_dir = os.path.join(datadir, "manifest") if not os.path.exists(manifest_dir): os.makedirs(manifest_dir)
python
def setup_manifest(datadir): """Create barebones manifest to be filled in during update """ manifest_dir = os.path.join(datadir, "manifest") if not os.path.exists(manifest_dir): os.makedirs(manifest_dir)
[ "def", "setup_manifest", "(", "datadir", ")", ":", "manifest_dir", "=", "os", ".", "path", ".", "join", "(", "datadir", ",", "\"manifest\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "manifest_dir", ")", ":", "os", ".", "makedirs", "(", ...
Create barebones manifest to be filled in during update
[ "Create", "barebones", "manifest", "to", "be", "filled", "in", "during", "update" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/bcbio_nextgen_install.py#L139-L144
223,591
bcbio/bcbio-nextgen
scripts/bcbio_nextgen_install.py
write_system_config
def write_system_config(base_url, datadir, tooldir): """Write a bcbio_system.yaml configuration file with tool information. """ out_file = os.path.join(datadir, "galaxy", os.path.basename(base_url)) if not os.path.exists(os.path.dirname(out_file)): os.makedirs(os.path.dirname(out_file)) if os.path.exists(out_file): # if no tool directory and exists, do not overwrite if tooldir is None: return out_file else: bak_file = out_file + ".bak%s" % (datetime.datetime.now().strftime("%Y%M%d_%H%M")) shutil.copy(out_file, bak_file) if tooldir: java_basedir = os.path.join(tooldir, "share", "java") rewrite_ignore = ("log",) with contextlib.closing(urllib_request.urlopen(base_url)) as in_handle: with open(out_file, "w") as out_handle: in_resources = False in_prog = None for line in (l.decode("utf-8") for l in in_handle): if line[0] != " ": in_resources = line.startswith("resources") in_prog = None elif (in_resources and line[:2] == " " and line[2] != " " and not line.strip().startswith(rewrite_ignore)): in_prog = line.split(":")[0].strip() # Update java directories to point to install directory, avoid special cases elif line.strip().startswith("dir:") and in_prog and in_prog not in ["log", "tmp"]: final_dir = os.path.basename(line.split()[-1]) if tooldir: line = "%s: %s\n" % (line.split(":")[0], os.path.join(java_basedir, final_dir)) in_prog = None elif line.startswith("galaxy"): line = "# %s" % line out_handle.write(line) return out_file
python
def write_system_config(base_url, datadir, tooldir): """Write a bcbio_system.yaml configuration file with tool information. """ out_file = os.path.join(datadir, "galaxy", os.path.basename(base_url)) if not os.path.exists(os.path.dirname(out_file)): os.makedirs(os.path.dirname(out_file)) if os.path.exists(out_file): # if no tool directory and exists, do not overwrite if tooldir is None: return out_file else: bak_file = out_file + ".bak%s" % (datetime.datetime.now().strftime("%Y%M%d_%H%M")) shutil.copy(out_file, bak_file) if tooldir: java_basedir = os.path.join(tooldir, "share", "java") rewrite_ignore = ("log",) with contextlib.closing(urllib_request.urlopen(base_url)) as in_handle: with open(out_file, "w") as out_handle: in_resources = False in_prog = None for line in (l.decode("utf-8") for l in in_handle): if line[0] != " ": in_resources = line.startswith("resources") in_prog = None elif (in_resources and line[:2] == " " and line[2] != " " and not line.strip().startswith(rewrite_ignore)): in_prog = line.split(":")[0].strip() # Update java directories to point to install directory, avoid special cases elif line.strip().startswith("dir:") and in_prog and in_prog not in ["log", "tmp"]: final_dir = os.path.basename(line.split()[-1]) if tooldir: line = "%s: %s\n" % (line.split(":")[0], os.path.join(java_basedir, final_dir)) in_prog = None elif line.startswith("galaxy"): line = "# %s" % line out_handle.write(line) return out_file
[ "def", "write_system_config", "(", "base_url", ",", "datadir", ",", "tooldir", ")", ":", "out_file", "=", "os", ".", "path", ".", "join", "(", "datadir", ",", "\"galaxy\"", ",", "os", ".", "path", ".", "basename", "(", "base_url", ")", ")", "if", "not"...
Write a bcbio_system.yaml configuration file with tool information.
[ "Write", "a", "bcbio_system", ".", "yaml", "configuration", "file", "with", "tool", "information", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/bcbio_nextgen_install.py#L146-L183
223,592
bcbio/bcbio-nextgen
scripts/bcbio_nextgen_install.py
check_dependencies
def check_dependencies(): """Ensure required tools for installation are present. """ print("Checking required dependencies") for dep, msg in [(["git", "--version"], "Git (http://git-scm.com/)"), (["wget", "--version"], "wget"), (["bzip2", "-h"], "bzip2")]: try: p = subprocess.Popen(dep, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) out, code = p.communicate() except OSError: out = "Executable not found" code = 127 if code == 127: raise OSError("bcbio-nextgen installer requires %s\n%s" % (msg, out))
python
def check_dependencies(): """Ensure required tools for installation are present. """ print("Checking required dependencies") for dep, msg in [(["git", "--version"], "Git (http://git-scm.com/)"), (["wget", "--version"], "wget"), (["bzip2", "-h"], "bzip2")]: try: p = subprocess.Popen(dep, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) out, code = p.communicate() except OSError: out = "Executable not found" code = 127 if code == 127: raise OSError("bcbio-nextgen installer requires %s\n%s" % (msg, out))
[ "def", "check_dependencies", "(", ")", ":", "print", "(", "\"Checking required dependencies\"", ")", "for", "dep", ",", "msg", "in", "[", "(", "[", "\"git\"", ",", "\"--version\"", "]", ",", "\"Git (http://git-scm.com/)\"", ")", ",", "(", "[", "\"wget\"", ",",...
Ensure required tools for installation are present.
[ "Ensure", "required", "tools", "for", "installation", "are", "present", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/bcbio_nextgen_install.py#L207-L221
223,593
bcbio/bcbio-nextgen
bcbio/distributed/runfn.py
process
def process(args): """Run the function in args.name given arguments in args.argfile. """ # Set environment to standard to use periods for decimals and avoid localization os.environ["LC_ALL"] = "C" os.environ["LC"] = "C" os.environ["LANG"] = "C" setpath.prepend_bcbiopath() try: fn = getattr(multitasks, args.name) except AttributeError: raise AttributeError("Did not find exposed function in bcbio.distributed.multitasks named '%s'" % args.name) if args.moreargs or args.raw: fnargs = [args.argfile] + args.moreargs work_dir = None argfile = None else: with open(args.argfile) as in_handle: fnargs = yaml.safe_load(in_handle) work_dir = os.path.dirname(args.argfile) fnargs = config_utils.merge_resources(fnargs) argfile = args.outfile if args.outfile else "%s-out%s" % os.path.splitext(args.argfile) if not work_dir: work_dir = os.getcwd() if len(fnargs) > 0 and fnargs[0] == "cwl": fnargs, parallel, out_keys, input_files = _world_from_cwl(args.name, fnargs[1:], work_dir) # Can remove this awkward Docker merge when we do not need custom GATK3 installs fnargs = config_utils.merge_resources(fnargs) argfile = os.path.join(work_dir, "cwl.output.json") else: parallel, out_keys, input_files = None, {}, [] with utils.chdir(work_dir): with contextlib.closing(log.setup_local_logging(parallel={"wrapper": "runfn"})): try: out = fn(*fnargs) except: logger.exception() raise finally: # Clean up any copied and unpacked workflow inputs, avoiding extra disk usage wf_input_dir = os.path.join(work_dir, "wf-inputs") if os.path.exists(wf_input_dir) and os.path.isdir(wf_input_dir): shutil.rmtree(wf_input_dir) if argfile: try: _write_out_argfile(argfile, out, fnargs, parallel, out_keys, input_files, work_dir) except: logger.exception() raise
python
def process(args): """Run the function in args.name given arguments in args.argfile. """ # Set environment to standard to use periods for decimals and avoid localization os.environ["LC_ALL"] = "C" os.environ["LC"] = "C" os.environ["LANG"] = "C" setpath.prepend_bcbiopath() try: fn = getattr(multitasks, args.name) except AttributeError: raise AttributeError("Did not find exposed function in bcbio.distributed.multitasks named '%s'" % args.name) if args.moreargs or args.raw: fnargs = [args.argfile] + args.moreargs work_dir = None argfile = None else: with open(args.argfile) as in_handle: fnargs = yaml.safe_load(in_handle) work_dir = os.path.dirname(args.argfile) fnargs = config_utils.merge_resources(fnargs) argfile = args.outfile if args.outfile else "%s-out%s" % os.path.splitext(args.argfile) if not work_dir: work_dir = os.getcwd() if len(fnargs) > 0 and fnargs[0] == "cwl": fnargs, parallel, out_keys, input_files = _world_from_cwl(args.name, fnargs[1:], work_dir) # Can remove this awkward Docker merge when we do not need custom GATK3 installs fnargs = config_utils.merge_resources(fnargs) argfile = os.path.join(work_dir, "cwl.output.json") else: parallel, out_keys, input_files = None, {}, [] with utils.chdir(work_dir): with contextlib.closing(log.setup_local_logging(parallel={"wrapper": "runfn"})): try: out = fn(*fnargs) except: logger.exception() raise finally: # Clean up any copied and unpacked workflow inputs, avoiding extra disk usage wf_input_dir = os.path.join(work_dir, "wf-inputs") if os.path.exists(wf_input_dir) and os.path.isdir(wf_input_dir): shutil.rmtree(wf_input_dir) if argfile: try: _write_out_argfile(argfile, out, fnargs, parallel, out_keys, input_files, work_dir) except: logger.exception() raise
[ "def", "process", "(", "args", ")", ":", "# Set environment to standard to use periods for decimals and avoid localization", "os", ".", "environ", "[", "\"LC_ALL\"", "]", "=", "\"C\"", "os", ".", "environ", "[", "\"LC\"", "]", "=", "\"C\"", "os", ".", "environ", "...
Run the function in args.name given arguments in args.argfile.
[ "Run", "the", "function", "in", "args", ".", "name", "given", "arguments", "in", "args", ".", "argfile", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L23-L71
223,594
bcbio/bcbio-nextgen
bcbio/distributed/runfn.py
_cwlvar_to_wdl
def _cwlvar_to_wdl(var): """Convert a CWL output object into a WDL output. This flattens files and other special CWL outputs that are plain strings in WDL. """ if isinstance(var, (list, tuple)): return [_cwlvar_to_wdl(x) for x in var] elif isinstance(var, dict): assert var.get("class") == "File", var # XXX handle secondary files return var.get("path") or var["value"] else: return var
python
def _cwlvar_to_wdl(var): """Convert a CWL output object into a WDL output. This flattens files and other special CWL outputs that are plain strings in WDL. """ if isinstance(var, (list, tuple)): return [_cwlvar_to_wdl(x) for x in var] elif isinstance(var, dict): assert var.get("class") == "File", var # XXX handle secondary files return var.get("path") or var["value"] else: return var
[ "def", "_cwlvar_to_wdl", "(", "var", ")", ":", "if", "isinstance", "(", "var", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "_cwlvar_to_wdl", "(", "x", ")", "for", "x", "in", "var", "]", "elif", "isinstance", "(", "var", ",", "dict...
Convert a CWL output object into a WDL output. This flattens files and other special CWL outputs that are plain strings in WDL.
[ "Convert", "a", "CWL", "output", "object", "into", "a", "WDL", "output", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L73-L86
223,595
bcbio/bcbio-nextgen
bcbio/distributed/runfn.py
_write_out_argfile
def _write_out_argfile(argfile, out, fnargs, parallel, out_keys, input_files, work_dir): """Write output argfile, preparing a CWL ready JSON or YAML representation of the world. """ with open(argfile, "w") as out_handle: if argfile.endswith(".json"): record_name, record_attrs = _get_record_attrs(out_keys) if record_name: if parallel in ["multi-batch"]: recs = _nested_cwl_record(out, record_attrs, input_files) elif parallel in ["single-split", "multi-combined", "multi-parallel", "batch-single", "single-single"]: recs = [_collapse_to_cwl_record_single(utils.to_single_data(xs), record_attrs, input_files) for xs in out] else: samples = [utils.to_single_data(xs) for xs in out] recs = [_collapse_to_cwl_record(samples, record_attrs, input_files)] json.dump(_combine_cwl_records(recs, record_name, parallel), out_handle, sort_keys=True, indent=4, separators=(', ', ': ')) elif parallel in ["single-split", "multi-combined", "batch-split"]: json.dump(_convert_to_cwl_json([utils.to_single_data(xs) for xs in out], fnargs, input_files), out_handle, sort_keys=True, indent=4, separators=(', ', ': ')) else: json.dump(_convert_to_cwl_json(utils.to_single_data(utils.to_single_data(out)), fnargs, input_files), out_handle, sort_keys=True, indent=4, separators=(', ', ': ')) else: yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
python
def _write_out_argfile(argfile, out, fnargs, parallel, out_keys, input_files, work_dir): """Write output argfile, preparing a CWL ready JSON or YAML representation of the world. """ with open(argfile, "w") as out_handle: if argfile.endswith(".json"): record_name, record_attrs = _get_record_attrs(out_keys) if record_name: if parallel in ["multi-batch"]: recs = _nested_cwl_record(out, record_attrs, input_files) elif parallel in ["single-split", "multi-combined", "multi-parallel", "batch-single", "single-single"]: recs = [_collapse_to_cwl_record_single(utils.to_single_data(xs), record_attrs, input_files) for xs in out] else: samples = [utils.to_single_data(xs) for xs in out] recs = [_collapse_to_cwl_record(samples, record_attrs, input_files)] json.dump(_combine_cwl_records(recs, record_name, parallel), out_handle, sort_keys=True, indent=4, separators=(', ', ': ')) elif parallel in ["single-split", "multi-combined", "batch-split"]: json.dump(_convert_to_cwl_json([utils.to_single_data(xs) for xs in out], fnargs, input_files), out_handle, sort_keys=True, indent=4, separators=(', ', ': ')) else: json.dump(_convert_to_cwl_json(utils.to_single_data(utils.to_single_data(out)), fnargs, input_files), out_handle, sort_keys=True, indent=4, separators=(', ', ': ')) else: yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
[ "def", "_write_out_argfile", "(", "argfile", ",", "out", ",", "fnargs", ",", "parallel", ",", "out_keys", ",", "input_files", ",", "work_dir", ")", ":", "with", "open", "(", "argfile", ",", "\"w\"", ")", "as", "out_handle", ":", "if", "argfile", ".", "en...
Write output argfile, preparing a CWL ready JSON or YAML representation of the world.
[ "Write", "output", "argfile", "preparing", "a", "CWL", "ready", "JSON", "or", "YAML", "representation", "of", "the", "world", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L88-L113
223,596
bcbio/bcbio-nextgen
bcbio/distributed/runfn.py
_get_record_attrs
def _get_record_attrs(out_keys): """Check for records, a single key plus output attributes. """ if len(out_keys) == 1: attr = list(out_keys.keys())[0] if out_keys[attr]: return attr, out_keys[attr] return None, None
python
def _get_record_attrs(out_keys): """Check for records, a single key plus output attributes. """ if len(out_keys) == 1: attr = list(out_keys.keys())[0] if out_keys[attr]: return attr, out_keys[attr] return None, None
[ "def", "_get_record_attrs", "(", "out_keys", ")", ":", "if", "len", "(", "out_keys", ")", "==", "1", ":", "attr", "=", "list", "(", "out_keys", ".", "keys", "(", ")", ")", "[", "0", "]", "if", "out_keys", "[", "attr", "]", ":", "return", "attr", ...
Check for records, a single key plus output attributes.
[ "Check", "for", "records", "a", "single", "key", "plus", "output", "attributes", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L115-L122
223,597
bcbio/bcbio-nextgen
bcbio/distributed/runfn.py
_add_resources
def _add_resources(data, runtime): """Merge input resources with current CWL runtime parameters. """ if "config" not in data: data["config"] = {} # Convert input resources, which may be a JSON string resources = data.get("resources", {}) or {} if isinstance(resources, six.string_types) and resources.startswith(("{", "[")): resources = json.loads(resources) data["resources"] = resources assert isinstance(resources, dict), (resources, data) data["config"]["resources"] = resources # Add in memory and core usage from CWL memory = int(float(runtime["ram"]) / float(runtime["cores"])) data["config"]["resources"].update({"default": {"cores": int(runtime["cores"]), "memory": "%sM" % memory, "jvm_opts": ["-Xms%sm" % min(1000, memory // 2), "-Xmx%sm" % memory]}}) data["config"]["algorithm"]["num_cores"] = int(runtime["cores"]) return data
python
def _add_resources(data, runtime): """Merge input resources with current CWL runtime parameters. """ if "config" not in data: data["config"] = {} # Convert input resources, which may be a JSON string resources = data.get("resources", {}) or {} if isinstance(resources, six.string_types) and resources.startswith(("{", "[")): resources = json.loads(resources) data["resources"] = resources assert isinstance(resources, dict), (resources, data) data["config"]["resources"] = resources # Add in memory and core usage from CWL memory = int(float(runtime["ram"]) / float(runtime["cores"])) data["config"]["resources"].update({"default": {"cores": int(runtime["cores"]), "memory": "%sM" % memory, "jvm_opts": ["-Xms%sm" % min(1000, memory // 2), "-Xmx%sm" % memory]}}) data["config"]["algorithm"]["num_cores"] = int(runtime["cores"]) return data
[ "def", "_add_resources", "(", "data", ",", "runtime", ")", ":", "if", "\"config\"", "not", "in", "data", ":", "data", "[", "\"config\"", "]", "=", "{", "}", "# Convert input resources, which may be a JSON string", "resources", "=", "data", ".", "get", "(", "\"...
Merge input resources with current CWL runtime parameters.
[ "Merge", "input", "resources", "with", "current", "CWL", "runtime", "parameters", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L124-L143
223,598
bcbio/bcbio-nextgen
bcbio/distributed/runfn.py
_world_from_cwl
def _world_from_cwl(fn_name, fnargs, work_dir): """Reconstitute a bcbio world data object from flattened CWL-compatible inputs. Converts the flat CWL representation into a nested bcbio world dictionary. Handles single sample inputs (returning a single world object) and multi-sample runs (returning a list of individual samples to get processed together). """ parallel = None output_cwl_keys = None runtime = {} out = [] data = {} passed_keys = [] for fnarg in fnargs: key, val = fnarg.split("=") # extra values pulling in nested indexes if key == "ignore": continue if key == "sentinel_parallel": parallel = val continue if key == "sentinel_runtime": runtime = dict(tz.partition(2, val.split(","))) continue if key == "sentinel_outputs": output_cwl_keys = _parse_output_keys(val) continue if key == "sentinel_inputs": input_order = collections.OrderedDict([x.split(":") for x in val.split(",")]) continue else: assert key not in passed_keys, "Multiple keys should be handled via JSON records" passed_keys.append(key) key = key.split("__") data = _update_nested(key, _convert_value(val), data) if data: out.append(_finalize_cwl_in(data, work_dir, passed_keys, output_cwl_keys, runtime)) # Read inputs from standard files instead of command line assert os.path.exists(os.path.join(work_dir, "cwl.inputs.json")) out, input_files = _read_from_cwlinput(os.path.join(work_dir, "cwl.inputs.json"), work_dir, runtime, parallel, input_order, output_cwl_keys) if parallel in ["single-parallel", "single-merge", "multi-parallel", "multi-combined", "multi-batch", "batch-split", "batch-parallel", "batch-merge", "batch-single"]: out = [out] else: assert len(out) == 1, "%s\n%s" % (pprint.pformat(out), pprint.pformat(fnargs)) return out, parallel, output_cwl_keys, input_files
python
def _world_from_cwl(fn_name, fnargs, work_dir): """Reconstitute a bcbio world data object from flattened CWL-compatible inputs. Converts the flat CWL representation into a nested bcbio world dictionary. Handles single sample inputs (returning a single world object) and multi-sample runs (returning a list of individual samples to get processed together). """ parallel = None output_cwl_keys = None runtime = {} out = [] data = {} passed_keys = [] for fnarg in fnargs: key, val = fnarg.split("=") # extra values pulling in nested indexes if key == "ignore": continue if key == "sentinel_parallel": parallel = val continue if key == "sentinel_runtime": runtime = dict(tz.partition(2, val.split(","))) continue if key == "sentinel_outputs": output_cwl_keys = _parse_output_keys(val) continue if key == "sentinel_inputs": input_order = collections.OrderedDict([x.split(":") for x in val.split(",")]) continue else: assert key not in passed_keys, "Multiple keys should be handled via JSON records" passed_keys.append(key) key = key.split("__") data = _update_nested(key, _convert_value(val), data) if data: out.append(_finalize_cwl_in(data, work_dir, passed_keys, output_cwl_keys, runtime)) # Read inputs from standard files instead of command line assert os.path.exists(os.path.join(work_dir, "cwl.inputs.json")) out, input_files = _read_from_cwlinput(os.path.join(work_dir, "cwl.inputs.json"), work_dir, runtime, parallel, input_order, output_cwl_keys) if parallel in ["single-parallel", "single-merge", "multi-parallel", "multi-combined", "multi-batch", "batch-split", "batch-parallel", "batch-merge", "batch-single"]: out = [out] else: assert len(out) == 1, "%s\n%s" % (pprint.pformat(out), pprint.pformat(fnargs)) return out, parallel, output_cwl_keys, input_files
[ "def", "_world_from_cwl", "(", "fn_name", ",", "fnargs", ",", "work_dir", ")", ":", "parallel", "=", "None", "output_cwl_keys", "=", "None", "runtime", "=", "{", "}", "out", "=", "[", "]", "data", "=", "{", "}", "passed_keys", "=", "[", "]", "for", "...
Reconstitute a bcbio world data object from flattened CWL-compatible inputs. Converts the flat CWL representation into a nested bcbio world dictionary. Handles single sample inputs (returning a single world object) and multi-sample runs (returning a list of individual samples to get processed together).
[ "Reconstitute", "a", "bcbio", "world", "data", "object", "from", "flattened", "CWL", "-", "compatible", "inputs", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L145-L194
223,599
bcbio/bcbio-nextgen
bcbio/distributed/runfn.py
_parse_output_keys
def _parse_output_keys(val): """Parse expected output keys from string, handling records. """ out = {} for k in val.split(","): # record output if ":" in k: name, attrs = k.split(":") out[name] = attrs.split(";") else: out[k] = None return out
python
def _parse_output_keys(val): """Parse expected output keys from string, handling records. """ out = {} for k in val.split(","): # record output if ":" in k: name, attrs = k.split(":") out[name] = attrs.split(";") else: out[k] = None return out
[ "def", "_parse_output_keys", "(", "val", ")", ":", "out", "=", "{", "}", "for", "k", "in", "val", ".", "split", "(", "\",\"", ")", ":", "# record output", "if", "\":\"", "in", "k", ":", "name", ",", "attrs", "=", "k", ".", "split", "(", "\":\"", ...
Parse expected output keys from string, handling records.
[ "Parse", "expected", "output", "keys", "from", "string", "handling", "records", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L196-L207