code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not chunks: raise ValueError( "No command parts: {} ({})".format(chunks, type(chunks))) if isinstance(chunks, str): return chunks parsed_pieces = [] for cmd_part in chunks: if cmd_part is None: continue try: # Trim just spac...
def build_command(chunks)
Create a command from various parts. The parts provided may include a base, flags, option-bound arguments, and positional arguments. Each element must be either a string or a two-tuple. Raw strings are interpreted as either the command base, a pre-joined pair (or multiple pairs) of option and argument,...
4.786461
4.237336
1.129592
for path_name, path in sample.paths.items(): print("{}: '{}'".format(path_name, path)) base, ext = os.path.splitext(path) if ext: print("Skipping file-like: '[}'".format(path)) elif not os.path.isdir(base): os.makedirs(base)
def build_sample_paths(sample)
Ensure existence of folders for a Sample. :param looper.models.Sample sample: Sample (or instance supporting get() that stores folders paths in a 'paths' key, in which the value is a mapping from path name to actual folder path)
5.201777
4.902782
1.060985
# Allow Stage as type for checkpoint parameter's argument without # needing to import here the Stage type from stage.py module. try: base = checkpoint.checkpoint_name except AttributeError: base = translate_stage_name(checkpoint) if pipeline_name: base = "{}{}{}".format(...
def checkpoint_filename(checkpoint, pipeline_name=None)
Translate a checkpoint to a filename. This not only adds the checkpoint file extension but also standardizes the way in which checkpoint names are mapped to filenames. :param str | pypiper.Stage checkpoint: name of a pipeline phase/stage :param str pipeline_name: name of pipeline to prepend to the che...
8.84571
8.361936
1.057854
# Handle case in which checkpoint is given not just as a string, but # as a checkpoint-like filename. Don't worry about absolute path status # of a potential filename input, or whether it's in the pipeline's # output folder. That's handled upstream. While this isn't a protected # function, the...
def checkpoint_filepath(checkpoint, pm)
Create filepath for indicated checkpoint. :param str | pypiper.Stage checkpoint: Pipeline phase/stage or one's name :param pypiper.PipelineManager | pypiper.Pipeline pm: manager of a pipeline instance, relevant for output folder path. :return str: standardized checkpoint name for file, plus extensi...
7.26551
6.805312
1.067623
if isinstance(shell, bool): return shell return "|" in cmd or ">" in cmd or r"*" in cmd
def check_shell(cmd, shell=None)
Determine whether a command appears to involve shell process(es). The shell argument can be used to override the result of the check. :param str cmd: Command to investigate. :param bool shell: override the result of the check with this value. :return bool: Whether the command appears to involve shell p...
9.312864
10.950527
0.850449
curly_brackets = True while curly_brackets: SRE_match_obj = re.search(r'\{(.*?)}',cmd) if SRE_match_obj is not None: cmd = cmd[:SRE_match_obj.start()] + cmd[(SRE_match_obj.end()+1):] if re.search(r'\{(.*?)}',cmd) is None: curly_brackets = False ...
def check_shell_redirection(cmd)
Determine whether a command appears to contain shell redirection symbol outside of curly brackets :param str cmd: Command to investigate. :return bool: Whether the command appears to contain shell redirection.
2.721396
2.663526
1.021727
if isinstance(cmd, Iterable) and not isinstance(cmd, str): cmd = " ".join(cmd) return cmd.split()[0].replace('(', '').replace(')', '')
def get_proc_name(cmd)
Get the representative process name from complex command :param str | list[str] cmd: a command to be processed :return str: the basename representative command
3.564635
4.509593
0.790456
# Search for the requested parameter. for pool in param_pools: if param in pool: return pool[param] # Raise error if unfound and no strategy or value is provided or handling # unmapped parameter requests. if error and on_missing is None: raise KeyError("Unmapped pa...
def get_first_value(param, param_pools, on_missing=None, error=True)
Get the value for a particular parameter from the first pool in the provided priority list of parameter pools. :param str param: Name of parameter for which to determine/fetch value. :param Sequence[Mapping[str, object]] param_pools: Ordered (priority) collection of mapping from parameter name to v...
5.711907
4.169869
1.369805
file_folder, _ = os.path.split(fpath) other_folder = os.path.join(folder, "") return other_folder.startswith(file_folder)
def is_in_file_tree(fpath, folder)
Determine whether a file is in a folder. :param str fpath: filepath to investigate :param folder: path to folder to query :return bool: whether the path indicated is in the folder indicated
3.697238
4.786077
0.772499
_, ext = os.path.splitext(file_name) return file_name.endswith(".fastq.gz") or file_name.endswith(".fq.gz")
def is_gzipped_fastq(file_name)
Determine whether indicated file appears to be a gzipped FASTQ. :param str file_name: Name/path of file to check as gzipped FASTQ. :return bool: Whether indicated file appears to be in gzipped FASTQ format.
2.544674
3.06534
0.830144
def make_name(p): return p.replace(path_base_folder, "").replace(os.sep, "__") if isinstance(original_path, str): return make_name(original_path) elif isinstance(original_path, Sequence): return [make_name(p) for p in original_path] raise TypeError("Neither string nor other ...
def make_lock_name(original_path, path_base_folder)
Create name for lock file from an absolute path. The original path must be absolute, and it should point to a location within the location indicated by the base folder path provided. This is particularly useful for deleting a sample's output folder path from within the path of a target file to generate...
2.87041
3.24217
0.885336
if target is None or isinstance(target, str): return False elif isinstance(target, Sequence): return len(target) > 1 else: raise TypeError("Could not interpret argument as a target: {} ({})". format(target, type(target)))
def is_multi_target(target)
Determine if pipeline manager's run target is multiple. :param None or str or Sequence of str target: 0, 1, or multiple targets :return bool: Whether there are multiple targets :raise TypeError: if the argument is neither None nor string nor Sequence
3.185887
3.096428
1.028891
cores = cores or getattr(pm, "cores", default) return int(cores)
def parse_cores(cores, pm, default)
Framework to finalize number of cores for an operation. Some calls to a function may directly provide a desired number of cores, others may not. Similarly, some pipeline managers may define a cores count while others will not. This utility provides a single via which the count of cores to use for an op...
6.516126
13.892586
0.469036
if isinstance(stage, str): return stage try: return stage.name except AttributeError: try: return stage.__name__ except AttributeError: raise TypeError("Unsupported stage type: {}".format(type(stage)))
def parse_stage_name(stage)
Determine the name of a stage. The stage may be provided already as a name, as a Stage object, or as a callable with __name__ (e.g., function). :param str | pypiper.Stage | function stage: Object representing a stage, from which to obtain name. :return str: Name of putative pipeline Stage.
2.670384
3.016978
0.885119
if filename is None and suffix is None: raise TypeError("Provide filename and/or suffix to create " "path to a pipeline file.") filename = (filename or pm.name) + (suffix or "") # Note that Pipeline and PipelineManager define the same outfolder. # In fact, a Pipel...
def pipeline_filepath(pm, filename=None, suffix=None)
Derive path to file for managed pipeline. :param pypiper.PipelineManager | pypiper.Pipeline pm: Manager of a particular pipeline instance. :param str filename: Name of file for which to create full path based on pipeline's output folder. :param str suffix: Suffix for the file; this can be a...
7.431487
6.655632
1.116571
# First ensure that we have text. name = parse_stage_name(stage) # Cast to string to ensure that indexed stages (ints are handled). return str(name).lower().replace(" ", STAGE_NAME_SPACE_REPLACEMENT)
def translate_stage_name(stage)
Account for potential variability in stage/phase name definition. Since a pipeline author is free to name his/her processing phases/stages as desired, but these choices influence file names, enforce some standardization. Specifically, prohibit potentially problematic spaces. :param str | pypiper.Stage...
17.260447
17.286997
0.998464
if sys.version_info < (3, 3): from collections import Iterable else: from collections.abc import Iterable # Define the argument groups. args_by_group = { "pypiper": ["recover", "new-start", "dirty", "force-follow"], "config": ["config"], "checkpoint": ["sto...
def _determine_args(argument_groups, arguments, use_all_args=False)
Determine the arguments to add to a parser (for a pipeline). :param Iterable[str] | str argument_groups: Collection of names of groups of arguments to add to an argument parser. :param Iterable[str] | str arguments: Collection of specific arguments to add to the parser. :param bool use_all_...
3.750574
3.605298
1.040295
import copy required = required or [] # Determine the default pipeline config file. pipeline_script = os.path.basename(sys.argv[0]) default_config, _ = os.path.splitext(pipeline_script) default_config += ".yaml" # Define the arguments. argument_data = { "recover": ...
def _add_args(parser, args, required)
Add new arguments to an ArgumentParser. :param argparse.ArgumentParser parser: instance to update with new arguments :param Iterable[str] args: Collection of names of arguments to add. :param Iterable[str] required: Collection of arguments to designate as required :return argparse.ArgumentParser: Updat...
3.242457
3.233149
1.002879
for p in paths: # Only provide assurance for absolute paths. if not p or not os.path.isabs(p): continue # See if what we're assuring is file- or folder-like. fpath, fname = os.path.split(p) base, ext = os.path.splitext(fname) ...
def _ensure_folders(self, *paths)
Ensure that paths to folder(s) exist. Some command-line tools will not attempt to create folder(s) needed for output path to exist. They instead assume that they already are present and will fail if that assumption does not hold. :param Iterable[str] paths: Collection of path for which
6.268327
7.095163
0.883465
# Use `command` to see if command is callable, store exit code code = os.system("command -v {0} >/dev/null 2>&1 || {{ exit 1; }}".format(command)) # If exit code is not 0, report which command failed and return False, else return True if code != 0: print("Command i...
def check_command(self, command)
Check if command can be called.
4.437078
4.154944
1.067903
# use (1024 ** 3) for gigabytes # equivalent to: stat -Lc '%s' filename # If given a list, recurse through it. if type(filenames) is list: return sum([self.get_file_size(filename) for filename in filenames]) return round(sum([float(os.stat(f).st_size) for f...
def get_file_size(self, filenames)
Get size of all files in string (space-separated) in megabytes (Mb). :param str filenames: a space-separated string of filenames
5.868743
5.614342
1.045313
self._ensure_folders(output_fastq, output_fastq2, unpaired_fastq) cmd = self.tools.java + " -Xmx" + self.pm.javamem cmd += " -jar " + self.tools.picard + " SamToFastq" cmd += " INPUT={0}".format(input_bam) cmd += " FASTQ={0}".format(output_fastq) if output_fastq2...
def bam2fastq(self, input_bam, output_fastq, output_fastq2=None, unpaired_fastq=None)
Create command to convert BAM(s) to FASTQ(s). :param str input_bam: Path to sequencing reads file to convert :param output_fastq: Path to FASTQ to write :param output_fastq2: Path to (R2) FASTQ to write :param unpaired_fastq: Path to unpaired FASTQ to write :return str: Command ...
2.409022
2.432745
0.990249
self.make_sure_path_exists(os.path.dirname(out_fastq_pre)) cmd = self.tools.java + " -Xmx" + self.pm.javamem cmd += " -jar " + self.tools.picard + " SamToFastq" cmd += " I=" + bam_file cmd += " F=" + out_fastq_pre + "_R1.fastq" if paired_end: cmd += "...
def bam_to_fastq(self, bam_file, out_fastq_pre, paired_end)
Build command to convert BAM file to FASTQ file(s) (R1/R2). :param str bam_file: path to BAM file with sequencing reads :param str out_fastq_pre: path prefix for output FASTQ file(s) :param bool paired_end: whether the given file contains paired-end or single-end sequencing reads ...
2.347243
2.475731
0.948101
self.make_sure_path_exists(os.path.dirname(out_fastq_pre)) fq1 = out_fastq_pre + "_R1.fastq" if paired_end: fq2 = out_fastq_pre + "_R2.fastq" cmd = self.tools.samtools + " view " + bam_file + " | awk '" cmd += r'{ if (NR%2==1) print "@"$1"/1\n"$10"\n+...
def bam_to_fastq_awk(self, bam_file, out_fastq_pre, paired_end)
This converts bam file to fastq files, but using awk. As of 2016, this is much faster than the standard way of doing this using Picard, and also much faster than the bedtools implementation as well; however, it does no sanity checks and assumes the reads (for paired data) are all paired (no si...
2.40183
2.365858
1.015205
self.make_sure_path_exists(os.path.dirname(out_fastq_pre)) fq1 = out_fastq_pre + "_R1.fastq" fq2 = None cmd = self.tools.bedtools + " bamtofastq -i " + bam_file + " -fq " + fq1 + ".fastq" if paired_end: fq2 = out_fastq_pre + "_R2.fastq" cmd += " -...
def bam_to_fastq_bedtools(self, bam_file, out_fastq_pre, paired_end)
Converts bam to fastq; A version using bedtools
2.215394
2.182336
1.015148
if input_file.endswith(".bam"): input_ext = ".bam" elif input_file.endswith(".fastq.gz") or input_file.endswith(".fq.gz"): input_ext = ".fastq.gz" elif input_file.endswith(".fastq") or input_file.endswith(".fq"): input_ext = ".fastq" else: ...
def get_input_ext(self, input_file)
Get the extension of the input_file. Assumes you're using either .bam or .fastq/.fq or .fastq.gz/.fq.gz.
2.298618
2.196408
1.046535
fastq_prefix = os.path.join(fastq_folder, sample_name) self.make_sure_path_exists(fastq_folder) # this expects a list; if it gets a string, convert it to a list. if type(input_file) != list: input_file = [input_file] if len(input_file) > 1: cmd...
def input_to_fastq( self, input_file, sample_name, paired_end, fastq_folder, output_file=None, multiclass=False)
Builds a command to convert input file to fastq, for various inputs. Takes either .bam, .fastq.gz, or .fastq input and returns commands that will create the .fastq file, regardless of input type. This is useful to made your pipeline easily accept any of these input types seamlessly, sta...
3.034855
3.00509
1.009905
# Define a temporary function which we will return, to be called by the # pipeline. # Must define default parameters here based on the parameters passed in. This locks # these values in place, so that the variables will be defined when this function # is called without ...
def check_fastq(self, input_files, output_files, paired_end)
Returns a follow sanity-check function to be run after a fastq conversion. Run following a command that will produce the fastq files. This function will make sure any input files have the same number of reads as the output files.
4.628858
4.435498
1.043594
def temp_func(): print("Evaluating read trimming") if paired_end and not trimmed_fastq_R2: print("WARNING: specified paired-end but no R2 file") n_trim = float(self.count_reads(trimmed_fastq, paired_end)) self.pm.report_result("Trimmed...
def check_trim(self, trimmed_fastq, paired_end, trimmed_fastq_R2=None, fastqc_folder=None)
Build function to evaluate read trimming, and optionally run fastqc. This is useful to construct an argument for the 'follow' parameter of a PipelineManager's 'run' method. :param str trimmed_fastq: Path to trimmed reads file. :param bool paired_end: Whether the processing is being don...
2.803056
2.712471
1.033396
cmd = self.tools.java + " -Xmx" + self.pm.javamem cmd += " -jar " + self.tools.picard + " ValidateSamFile" cmd += " INPUT=" + input_bam return cmd
def validate_bam(self, input_bam)
Wrapper for Picard's ValidateSamFile. :param str input_bam: Path to file to validate. :return str: Command to run for the validation.
4.446613
3.861595
1.151496
if not len(input_bams) > 1: print("No merge required") return 0 outdir, _ = os.path.split(merged_bam) if outdir and not os.path.exists(outdir): print("Creating path to merge file's folder: '{}'".format(outdir)) os.makedirs(outdir) ...
def merge_bams(self, input_bams, merged_bam, in_sorted="TRUE", tmp_dir=None)
Combine multiple files into one. The tmp_dir parameter is important because on poorly configured systems, the default can sometimes fill up. :param Iterable[str] input_bams: Paths to files to combine :param str merged_bam: Path to which to write combined result. :param bool | s...
3.053795
3.138738
0.972937
if remove_inputs and not run: raise ValueError("Can't delete files if command isn't run") cmd = "cat {} > {}".format(" ".join(inputs), output) if run: subprocess.check_call(cmd.split(), shell=True) if remove_inputs: cmd = "rm {}".forma...
def merge_fastq(self, inputs, output, run=False, remove_inputs=False)
Merge FASTQ files (zipped or not) into one. :param Iterable[str] inputs: Collection of paths to files to merge. :param str output: Path to single output file. :param bool run: Whether to run the command. :param bool remove_inputs: Whether to keep the original files. :ret...
2.802959
2.300355
1.21849
x = subprocess.check_output("wc -l " + file_name + " | sed -E 's/^[[:space:]]+//' | cut -f1 -d' '", shell=True) return x.strip()
def count_lines(self, file_name)
Uses the command-line utility wc to count the number of lines in a file. For MacOS, must strip leading whitespace from wc. :param str file_name: name of file whose lines are to be counted
3.580799
3.727656
0.960604
x = subprocess.check_output(self.tools.samtools + " view -H " + file_name + " | grep '^@SQ' | cut -f2| sed s'/SN://'", shell=True) # Chromosomes will be separated by newlines; split into list to return return x.split()
def get_chrs_from_bam(self, file_name)
Uses samtools to grab the chromosomes from the header that are contained in this bam file.
6.397407
5.697834
1.122779
if file_name.endswith("sam"): param = "-S" if file_name.endswith("bam"): param = "" if paired_end: r1 = self.samtools_view(file_name, param=param + " -f64", postpend=" | cut -f1 | sort -k1,1 -u | wc -l | sed -E 's/^[[:space:]]+//'") r2 = s...
def count_unique_reads(self, file_name, paired_end)
Sometimes alignment software puts multiple locations for a single read; if you just count those reads, you will get an inaccurate count. This is _not_ the same as multimapping reads, which may or may not be actually duplicated in the bam file (depending on the alignment software). This f...
2.168379
2.148317
1.009339
_, ext = os.path.splitext(file_name) ext = ext.lower() if ext == ".sam": param = "-S -F4" elif ext == "bam": param = "-F4" else: raise ValueError("Not a SAM or BAM: '{}'".format(file_name)) if paired_end: r1 = s...
def count_unique_mapped_reads(self, file_name, paired_end)
For a bam or sam file with paired or or single-end reads, returns the number of mapped reads, counting each read only once, even if it appears mapped at multiple locations. :param str file_name: name of reads file :param bool paired_end: True/False paired end data :return int: N...
2.35479
2.351081
1.001578
param = " -c -f" + str(flag) if file_name.endswith("sam"): param += " -S" return self.samtools_view(file_name, param=param)
def count_flag_reads(self, file_name, flag, paired_end)
Counts the number of reads with the specified flag. :param str file_name: name of reads file :param str flag: sam flag value to be read :param bool paired_end: This parameter is ignored; samtools automatically correctly responds depending on the data in the bamfile. We leave the opt...
6.278889
7.352077
0.854029
param = " -c -F256" if file_name.endswith("sam"): param += " -S" return self.samtools_view(file_name, param=param)
def count_uniquelymapping_reads(self, file_name, paired_end)
Counts the number of reads that mapped to a unique position. :param str file_name: name of reads file :param bool paired_end: This parameter is ignored.
7.908658
10.02166
0.789157
cmd = "{} view {} {} {}".format( self.tools.samtools, param, file_name, postpend) return subprocess.check_output(cmd, shell=True)
def samtools_view(self, file_name, param, postpend="")
Run samtools view, with flexible parameters and post-processing. This is used internally to implement the various count_reads functions. :param str file_name: file_name :param str param: String of parameters to pass to samtools view :param str postpend: String to append to the samtools...
3.508955
4.611655
0.760888
_, ext = os.path.splitext(file_name) if not (is_sam_or_bam(file_name) or is_fastq(file_name)): # TODO: make this an exception and force caller to handle that # rather than relying on knowledge of possibility of negative value. return -1 if is_sam_or...
def count_reads(self, file_name, paired_end)
Count reads in a file. Paired-end reads count as 2 in this function. For paired-end reads, this function assumes that the reads are split into 2 files, so it divides line count by 2 instead of 4. This will thus give an incorrect result if your paired-end fastq files are in only ...
4.779892
4.598215
1.039511
cmd = self.tools.samtools + " view " + aligned_bam + " | " cmd += "grep 'YT:Z:CP'" + " | uniq -u | wc -l | sed -E 's/^[[:space:]]+//'" return subprocess.check_output(cmd, shell=True)
def count_concordant(self, aligned_bam)
Count only reads that "aligned concordantly exactly 1 time." :param str aligned_bam: File for which to count mapped reads.
5.358687
5.80928
0.922436
if file_name.endswith("bam"): return self.samtools_view(file_name, param="-c -F4") if file_name.endswith("sam"): return self.samtools_view(file_name, param="-c -F4 -S") return -1
def count_mapped_reads(self, file_name, paired_end)
Mapped_reads are not in fastq format, so this one doesn't need to accommodate fastq, and therefore, doesn't require a paired-end parameter because it only uses samtools view. Therefore, it's ok that it has a default parameter, since this is discarded. :param str file_name: File for which to cou...
3.467831
3.046321
1.138367
cmd = self.tools.samtools + " view -bS " + sam_file + " > " + sam_file.replace(".sam", ".bam") + "\n" cmd += self.tools.samtools + " sort " + sam_file.replace(".sam", ".bam") + " -o " + sam_file.replace(".sam", "_sorted.bam") + "\n" cmd += self.tools.samtools + " index " + sam_file.repl...
def sam_conversions(self, sam_file, depth=True)
Convert sam files to bam files, then sort and index them for later use. :param bool depth: also calculate coverage over each position
1.565705
1.648473
0.949791
cmd = self.tools.samtools + " view -h " + bam_file + " > " + bam_file.replace(".bam", ".sam") + "\n" cmd += self.tools.samtools + " sort " + bam_file + " -o " + bam_file.replace(".bam", "_sorted.bam") + "\n" cmd += self.tools.samtools + " index " + bam_file.replace(".bam", "_sorted.bam"...
def bam_conversions(self, bam_file, depth=True)
Sort and index bam files for later use. :param bool depth: also calculate coverage over each position
1.556161
1.668861
0.932469
# You can find the fastqc help with fastqc --help try: pm = self.pm except AttributeError: # Do nothing, this is just for path construction. pass else: if not os.path.isabs(output_dir) and pm is not None: output_dir...
def fastqc(self, file, output_dir)
Create command to run fastqc on a FASTQ file :param str file: Path to file with sequencing reads :param str output_dir: Path to folder in which to place output :return str: Command with which to run fastqc
4.903086
5.044398
0.971986
cmds = list() initial = os.path.splitext(os.path.basename(input_bam))[0] cmd1 = self.fastqc(input_bam, output_dir) cmds.append(cmd1) cmd2 = "if [[ ! -s {1}_fastqc.html ]]; then mv {0}_fastqc.html {1}_fastqc.html; mv {0}_fastqc.zip {1}_fastqc.zip; fi".format( ...
def fastqc_rename(self, input_bam, output_dir, sample_name)
Create pair of commands to run fastqc and organize files. The first command returned is the one that actually runs fastqc when it's executed; the second moves the output files to the output folder for the sample indicated. :param str input_bam: Path to file for which to run fastqc. ...
2.351378
2.63263
0.893167
cmd = self.tools.samtools + " index {0}".format(bam_file) return cmd
def samtools_index(self, bam_file)
Index a bam file.
5.034904
5.391093
0.93393
pe = input_fastq2 is not None mode = "pe" if pe else "any" cmds = list() cmd1 = self.tools.skewer + " --quiet" cmd1 += " -f sanger" cmd1 += " -t {0}".format(cpus) cmd1 += " -m {0}".format(mode) cmd1 += " -x {0}".format(adapters) cmd1 += "...
def skewer( self, input_fastq1, output_prefix, output_fastq1, log, cpus, adapters, input_fastq2=None, output_fastq2=None)
Create commands with which to run skewer. :param str input_fastq1: Path to input (read 1) FASTQ file :param str output_prefix: Prefix for output FASTQ file names :param str output_fastq1: Path to (read 1) output FASTQ file :param str log: Path to file to which to write logging informati...
1.878934
1.916521
0.980388
nodups = re.sub("\.bam$", "", output_bam) + ".nodups.nofilter.bam" cmd1 = self.tools.sambamba + " markdup -t {0} -r --compression-level=0 {1} {2} 2> {3}".format(cpus, input_bam, nodups, metrics_file) cmd2 = self.tools.sambamba + ' view -t {0} -f bam --valid'.format(cpus) if pair...
def filter_reads(self, input_bam, output_bam, metrics_file, paired=False, cpus=16, Q=30)
Remove duplicates, filter for >Q, remove multiple mapping reads. For paired-end reads, keep only proper pairs.
2.812086
2.772643
1.014226
base = "{} {} -rf -savp".format(self.tools.Rscript, self.tools.spp) cmd = base + " -savp={} -s=0:5:500 -c={} -out={} -p={}".format( plot, input_bam, output, cpus) return cmd
def run_spp(self, input_bam, output, plot, cpus)
Run the SPP read peak analysis tool. :param str input_bam: Path to reads file :param str output: Path to output file :param str plot: Path to plot file :param int cpus: Number of processors to use :return str: Command with which to run SPP
9.162084
9.353112
0.979576
# TODO: # addjust fragment length dependent on read size and real fragment size # (right now it asssumes 50bp reads with 180bp fragments) cmds = list() transient_file = os.path.abspath(re.sub("\.bigWig", "", output_bigwig)) cmd1 = self.tools.bedtools + " bamtobed...
def bam_to_bigwig( self, input_bam, output_bigwig, genome_sizes, genome, tagmented=False, normalize=False, norm_factor=1000)
Convert a BAM file to a bigWig file. :param str input_bam: path to BAM file to convert :param str output_bigwig: path to which to write file in bigwig format :param str genome_sizes: path to file with chromosome size information :param str genome: name of genomic assembly :param...
3.80689
3.855108
0.987492
cmd = self.simple_frip(input_bam, input_bed, threads) return subprocess.check_output(cmd.split(" "), shell=True)
def calc_frip(self, input_bam, input_bed, threads=4)
Calculate fraction of reads in peaks. A file of with a pool of sequencing reads and a file with peak call regions define the operation that will be performed. Thread count for samtools can be specified as well. :param str input_bam: sequencing reads file :param str input_bed: f...
4.119648
6.155104
0.669306
sizes = {"hg38": 2.7e9, "hg19": 2.7e9, "mm10": 1.87e9, "dr7": 1.412e9, "mm9": 1.87e9} # Whether to specify to MACS2 a value for statistical significance # can be either directly indicated, but if not, it's determined by # whether the mark is associated with broad peaks. By defa...
def macs2_call_peaks( self, treatment_bams, output_dir, sample_name, genome, control_bams=None, broad=False, paired=False, pvalue=None, qvalue=None, include_significance=None)
Use MACS2 to call peaks. :param str | Iterable[str] treatment_bams: Paths to files with data to regard as treatment. :param str output_dir: Path to output folder. :param str sample_name: Name for the sample involved. :param str genome: Name of the genome assembly to use. ...
4.176424
4.03387
1.035339
broad = "TRUE" if broad else "FALSE" cmd = self.tools.Rscript + " `which spp_peak_calling.R` {0} {1} {2} {3} {4} {5} {6}".format( treatment_bam, control_bam, treatment_name, control_name, broad, cpus, output_dir ) if qvalue is not None: cmd += " {}".forma...
def spp_call_peaks( self, treatment_bam, control_bam, treatment_name, control_name, output_dir, broad, cpus, qvalue=None)
Build command for R script to call peaks with SPP. :param str treatment_bam: Path to file with data for treatment sample. :param str control_bam: Path to file with data for control sample. :param str treatment_name: Name for the treatment sample. :param str control_name: Name for the co...
2.786527
3.049743
0.913693
from collections import Counter try: p = subprocess.Popen([self.tools.samtools, 'view', bam_file], stdout=subprocess.PIPE) # Count paired alignments paired = 0 read_length = Counter() while n > 0: ...
def get_read_type(self, bam_file, n=10)
Gets the read type (single, paired) and length of bam file. :param str bam_file: Bam file to determine read attributes. :param int n: Number of lines to read from bam file. :return str, int: tuple of read type and read length
4.187023
4.340145
0.96472
import pandas as pd stats = pd.Series(index=["readCount", "unpaired", "unaligned", "unique", "multiple", "alignmentRate"]) try: with open(stats_file) as handle: content = handle.readlines() # list of strings per line except: return stats ...
def parse_bowtie_stats(self, stats_file)
Parses Bowtie2 stats file, returns series with values. :param str stats_file: Bowtie2 output file with alignment statistics.
2.080291
2.044215
1.017648
import pandas as pd series = pd.Series() try: with open(stats_file) as handle: content = handle.readlines() # list of strings per line except: return series try: line = [i for i in range(len(content)) if "single ends (...
def parse_duplicate_stats(self, stats_file)
Parses sambamba markdup output, returns series with values. :param str stats_file: sambamba output file with duplicate statistics.
3.520846
3.353135
1.050016
import pandas as pd series = pd.Series() try: with open(qc_file) as handle: line = handle.readlines()[0].strip().split("\t") # list of strings per line series["NSC"] = line[-3] series["RSC"] = line[-2] series["qualityTag"]...
def parse_qc(self, qc_file)
Parse phantompeakqualtools (spp) QC table and return quality metrics. :param str qc_file: Path to phantompeakqualtools output file, which contains sample quality measurements.
4.689587
4.857494
0.965433
proc = subprocess.Popen(["wc", "-l", sample.peaks], stdout=subprocess.PIPE) out, err = proc.communicate() sample["peakNumber"] = re.sub("\D.*", "", out) return sample
def get_peak_number(self, sample)
Counts number of peaks from a sample's peak file. :param pipelines.Sample sample: Sample object with "peaks" attribute.
5.126551
4.462358
1.148843
import pandas as pd with open(sample.frip, "r") as handle: content = handle.readlines() reads_in_peaks = int(re.sub("\D", "", content[0])) mapped_reads = sample["readCount"] - sample["unaligned"] return pd.Series(reads_in_peaks / mapped_reads, index="FRiP")
def get_frip(self, sample)
Calculates the fraction of reads in peaks for a given sample. :param pipelines.Sample sample: Sample object with "peaks" attribute.
6.547635
5.07948
1.289036
signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGTERM, signal.SIG_IGN)
def _ignore_interrupts(self)
Ignore interrupt and termination signals. Used as a pre-execution function (preexec_fn) for subprocess.Popen calls that pypiper will control over (i.e., manually clean up).
2.179137
2.108312
1.033593
# Remove previous status flag file. flag_file_path = self._flag_file_path() try: os.remove(flag_file_path) except: # Print message only if the failure to remove the status flag # is unexpected; there's no flag for initialization, so we ...
def _set_status_flag(self, status)
Configure state and files on disk to match current processing status. :param str status: Name of new status designation for pipeline.
4.435678
4.490539
0.987783
flag_file_name = "{}_{}".format( self.name, flag_name(status or self.status)) return pipeline_filepath(self, filename=flag_file_name)
def _flag_file_path(self, status=None)
Create path to flag file based on indicated or current status. Internal variables used are the pipeline name and the designated pipeline output folder path. :param str status: flag file type to create, default to current status :return str: path to flag file of indicated or current sta...
7.048026
7.739297
0.91068
self._report_command(cmd) likely_shell = check_shell(cmd, shell) if shell is None: shell = likely_shell if not shell: if likely_shell: print("Should this command run in a shell instead of directly in a subprocess?") cmd = s...
def checkprint(self, cmd, shell=None, nofail=False)
Just like callprint, but checks output -- so you can get a variable in python corresponding to the return value of the command you call. This is equivalent to running subprocess.check_output() instead of subprocess.call(). :param str | Iterable[str] cmd: Bash command(s) to be run. ...
4.941651
4.450994
1.110235
# print("attend:{}".format(proc.pid)) try: proc.wait(timeout=sleeptime) except psutil.TimeoutExpired: return True return False
def _attend_process(self, proc, sleeptime)
Waits on a process for a given time to see if it finishes, returns True if it's still running after the given time or False as soon as it returns. :param psutil.Popen proc: Process object opened by psutil.Popen() :param float sleeptime: Time to wait :return bool: True if proces...
3.498044
3.209205
1.090003
local_maxmem = -1 sleeptime = .5 while p.poll() is None: if not shell: local_maxmem = max(local_maxmem, self._memory_usage(p.pid) / 1e6) # print("int.maxmem (pid:" + str(p.pid) + ") " + str(local_maxmem)) time.sleep(sleeptime) ...
def _wait_for_process(self, p, shell=False)
Debug function used in unit tests. :param p: A subprocess.Popen process. :param bool shell: If command requires should be run in its own shell. Optional. Default: False.
3.47918
3.710436
0.937674
sleeptime = .5 first_message_flag = False dot_count = 0 recover_file = self._recoverfile_from_lockfile(lock_file) while os.path.isfile(lock_file): if first_message_flag is False: self.timestamp("Waiting for file lock: " + lock_file) ...
def _wait_for_lock(self, lock_file)
Just sleep until the lock_file does not exist or a lock_file-related dynamic recovery flag is spotted :param str lock_file: Lock file to wait upon.
5.311377
5.201064
1.02121
# Halt if the manager's state has been set such that this call # should halt the pipeline. if self.halt_on_next: self.halt(checkpoint, finished, raise_error=raise_error) # Determine action to take with respect to halting if needed. if checkpoint: ...
def timestamp(self, message="", checkpoint=None, finished=False, raise_error=True)
Print message, time, and time elapsed, perhaps creating checkpoint. This prints your given message, along with the current time, and time elapsed since the previous timestamp() call. If you specify a HEADING by beginning the message with "###", it surrounds the message with newlines fo...
4.060853
3.693301
1.099519
message_raw = str(command) + "\t " + \ str(lock_name) + "\t" + \ str(datetime.timedelta(seconds = round(elapsed_time, 2))) + "\t " + \ str(memory) with open(self.pipeline_profile_file, "a") as myfile: myfile.write(message_raw + "\n")
def _report_profile(self, command, lock_name, elapsed_time, memory)
Writes a string to self.pipeline_profile_file.
3.227805
2.577691
1.252208
# Default annotation is current pipeline name. annotation = str(annotation or self.name) # In case the value is passed with trailing whitespace. value = str(value).strip() # keep the value in memory: self.stats_dict[key] = value message_raw = "{key}\t{v...
def report_result(self, key, value, annotation=None)
Writes a string to self.pipeline_stats_file. :param str key: name (key) of the stat :param str annotation: By default, the stats will be annotated with the pipeline name, so you can tell which pipeline records which stats. If you want, you can change this; use annotation...
5.551328
5.172476
1.073244
# Default annotation is current pipeline name. annotation = str(annotation or self.name) # In case the value is passed with trailing whitespace. filename = str(filename).strip() if anchor_text: anchor_text = str(anchor_text).strip() else: ...
def report_object(self, key, filename, anchor_text=None, anchor_image=None, annotation=None)
Writes a string to self.pipeline_objects_file. Used to report figures and others. :param str key: name (key) of the object :param str filename: relative path to the file (relative to parent output dir) :param str anchor_text: text used as the link anchor test or caption to refer to ...
2.746182
2.586498
1.061738
target = file lock_name = make_lock_name(target, self.outfolder) lock_file = self._make_lock_path(lock_name) while True: if os.path.isfile(lock_file): self._wait_for_lock(lock_file) else: try: self.lock...
def _safe_write_to_file(self, file, message)
Writes a string to a file safely (with file locks).
4.267626
4.102028
1.04037
if isinstance(procs, list): procs = ",".join(map(str,procs)) if procs: line = "\n> `{cmd}` ({procs})\n".format(cmd=str(cmd), procs=procs) else: line = "\n> `{cmd}`\n".format(cmd=str(cmd)) print(line) with open(self.pipeline_commands_f...
def _report_command(self, cmd, procs=None)
Writes a command to both stdout and to the commands log file (self.pipeline_commands_file). :param str cmd: command to report :param str | list[str] procs: process numbers for processes in the command
2.953345
2.582592
1.143558
write_lock_flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY os.open(file, write_lock_flags)
def _create_file_racefree(self, file)
Creates a file, but fails if the file already exists. This function will thus only succeed if this process actually creates the file; if the file already exists, it will cause an OSError, solving race conditions. :param str file: File to create.
3.475914
4.327162
0.803278
# For lock prefix validation, separate file name from other path # components, as we care about the name prefix not path prefix. base, name = os.path.split(lock_name_base) lock_name = self._ensure_lock_prefix(name) if base: lock_name = os.path.join(base, lo...
def _make_lock_path(self, lock_name_base)
Create path to lock file with given name as base. :param str lock_name_base: Lock file name, designed to not be prefixed with the lock file designation, but that's permitted. :return str: Path to the lock file.
7.732098
8.101525
0.9544
# Require that the lock file path be absolute, or at least relative # and starting with the pipeline output folder. if not (os.path.isabs(lockfile) or lockfile.startswith(self.outfolder)): lockfile = self._make_lock_path(lockfile) return lockfile.replace(LOCK_PREFIX,...
def _recoverfile_from_lockfile(self, lockfile)
Create path to recovery file with given name as base. :param str lockfile: Name of file on which to base this path, perhaps already prefixed with the designation of a lock file. :return str: Path to recovery file.
7.659129
7.856059
0.974933
try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise
def make_sure_path_exists(self, path)
Creates all directories in a path if it does not exist. :param str path: Path to create. :raises Exception: if the path creation attempt hits an error with a code indicating a cause other than pre-existence.
1.868528
2.422615
0.771286
# regex identifies all possible stats files. #regex = self.outfolder + "*_stats.tsv" #stats_files = glob.glob(regex) #stats_files.insert(self.pipeline_stats_file) # last one is the current pipeline #for stats_file in stats_files: stats_file = self.pipel...
def _refresh_stats(self)
Loads up the stats sheet created for this pipeline run and reads those stats into memory
5.996138
5.610402
1.068754
try: return self.stats_dict[key] except KeyError: self._refresh_stats() try: return self.stats_dict[key] except KeyError: print("Missing stat '{}'".format(key)) return None
def get_stat(self, key)
Returns a stat that was previously reported. This is necessary for reporting new stats that are derived from two stats, one of which may have been reported by an earlier run. For example, if you first use report_result to report (number of trimmed reads), and then in a later stage want to repor...
3.045545
3.060305
0.995177
# For null stage, short-circuit and indicate no file write. # This handles case in which we're timestamping prospectively and # previously weren't in a stage. if stage is None: return False try: is_checkpoint = stage.checkpoint except At...
def _checkpoint(self, stage)
Decide whether to stop processing of a pipeline. This is the hook A pipeline can report various "checkpoints" as sort of status markers that designate the logical processing phase that's just been completed. The initiation of a pipeline can preordain one of those as a "stopping point" t...
8.768884
8.453394
1.037321
if os.path.isabs(check_file): folder, _ = os.path.split(check_file) # For raw string comparison, ensure that each path # bears the final path separator. other_folder = os.path.join(folder, "") this_folder = os.path.join(self.outfolder, "") ...
def _touch_checkpoint(self, check_file)
Alternative way for a pipeline to designate a checkpoint. :param str check_file: Name or path of file to use as checkpoint. :return bool: Whether a file was written (equivalent to whether the checkpoint file already existed). :raise ValueError: Raise a ValueError if the argument pro...
5.062363
4.47381
1.131555
# Take care of any active running subprocess sys.stdout.flush() self._terminate_running_subprocesses() if dynamic_recover: # job was terminated, not failed due to a bad process. # flag this run as recoverable. if len(self.locks) < 1: ...
def fail_pipeline(self, e, dynamic_recover=False)
If the pipeline does not complete, this function will stop the pipeline gracefully. It sets the status flag to failed and skips the normal success completion procedure. :param Exception e: Exception to raise. :param bool dynamic_recover: Whether to recover e.g. for job termination.
7.288017
7.516611
0.969588
self.stop_pipeline(PAUSE_FLAG) self._active = False if raise_error: raise PipelineHalt(checkpoint, finished)
def halt(self, checkpoint=None, finished=False, raise_error=True)
Stop the pipeline before completion point. :param str checkpoint: Name of stage just reached or just completed. :param bool finished: Whether the indicated stage was just finished (True), or just reached (False) :param bool raise_error: Whether to raise an exception to truly ...
9.382702
9.786435
0.958746
self._set_status_flag(status) self._cleanup() self.report_result("Time", str(datetime.timedelta(seconds=self.time_elapsed(self.starttime)))) self.report_result("Success", time.strftime("%m-%d-%H:%M:%S")) print("\n##### [Epilogue:]") print("* " + "Total elapsed ti...
def stop_pipeline(self, status=COMPLETE_FLAG)
Terminate the pipeline. This is the "healthy" pipeline completion function. The normal pipeline completion function, to be run by the pipeline at the end of the script. It sets status flag to completed and records some time and memory statistics to the log file.
5.275828
5.261236
1.002773
print("</pre>") message = "Got " + signal_type + ". Failing gracefully..." self.timestamp(message) self.fail_pipeline(KeyboardInterrupt(signal_type), dynamic_recover=True) sys.exit(1)
def _generic_signal_handler(self, signal_type)
Function for handling both SIGTERM and SIGINT
13.731616
12.973715
1.058418
# TODO: consider handling sys.stderr/sys.stdout exceptions related to # TODO (cont.): order of interpreter vs. subprocess shutdown signal receipt. # TODO (cont.): see https://bugs.python.org/issue11380 # Make the cleanup file executable if it exists if os.path.isfile(...
def _exit_handler(self)
This function I register with atexit to run whenever the script is completing. A catch-all for uncaught exceptions, setting status flag file to failed.
7.326778
6.939795
1.055763
# When we kill process, it turns into a zombie, and we have to reap it. # So we can't just kill it and then let it go; we call wait def pskill(proc_pid, sig=signal.SIGINT): parent_process = psutil.Process(proc_pid) for child_proc in parent_process.children(recu...
def _kill_child_process(self, child_pid, proc_name=None)
Pypiper spawns subprocesses. We need to kill them to exit gracefully, in the event of a pipeline termination or interrupt signal. By default, child processes are not automatically killed when python terminates, so Pypiper must clean these up manually. Given a process ID, this function ju...
3.315553
3.388906
0.978355
if self.dirty: # Override the user-provided option and force manual cleanup. manual = True if not self.clean_initialized: # Make cleanup files relative to the cleanup script in case the result folder moves. with open(self.cleanup_file, "a") as my...
def clean_add(self, regex, conditional=False, manual=False)
Add files (or regexs) to a cleanup list, to delete when this pipeline completes successfully. When making a call with run that produces intermediate files that should be deleted after the pipeline completes, you flag these files for deletion with this command. Files added with clean_add will onl...
3.88518
3.831219
1.014084
if dry_run: # Move all unconditional cleans into the conditional list if len(self.cleanup_list) > 0: combined_list = self.cleanup_list_conditional + self.cleanup_list self.cleanup_list_conditional = combined_list self.cleanup_list...
def _cleanup(self, dry_run=False)
Cleans up (removes) intermediate files. You can register intermediate files, which will be deleted automatically when the pipeline completes. This function deletes them, either absolutely or conditionally. It is run automatically when the pipeline succeeds, so you shouldn't need to call...
2.465043
2.443497
1.008817
if container: # TODO: Put some debug output here with switch to Logger # since this is relatively untested. cmd = "docker stats " + container + " --format '{{.MemUsage}}' --no-stream" mem_use_str = subprocess.check_output(cmd, shell=True) mem_...
def _memory_usage(self, pid='self', category="hwm", container=None)
Memory usage of the process in kilobytes. :param str pid: Process ID of process to check :param str category: Memory type to check. 'hwm' for high water mark.
3.53908
3.667323
0.965031
if not nofail: self.fail_pipeline(e) elif self._failed: print("This is a nofail process, but the pipeline was terminated for other reasons, so we fail.") raise e else: print(e) print("ERROR: Subprocess returned nonzero result, ...
def _triage_error(self, e, nofail)
Print a message and decide what to do about an error.
9.085966
8.935834
1.016801
path_reqs_file = os.path.join( "requirements", "reqs-{}.txt".format(reqs_name)) with open(path_reqs_file, 'r') as reqs_file: return [pkg.rstrip() for pkg in reqs_file.readlines() if not pkg.startswith("#")]
def read_reqs_file(reqs_name)
Read requirements file for given requirements group.
2.74222
2.714023
1.01039
if not isinstance(collection, Iterable): raise TypeError("Non-iterable alleged collection: {}". format(type(collection))) return isinstance(collection, set) or \ (isinstance(collection, dict) and not isinstance(collection, OrderedDict))
def _is_unordered(collection)
Determine whether a collection appears to be unordered. This is a conservative implementation, allowing for the possibility that someone's implemented Mapping or Set, for example, and provided an __iter__ implementation that defines a consistent ordering of the collection's elements. :param object...
5.105458
5.25159
0.972174
# The logic used here, a message to a user about how to specify Stage. req_msg = "Stage specification must be either a {0} itself, a " \ "(<name>, {0}) pair, or a callable with a __name__ attribute " \ "(e.g., a non-anonymous function)".format(Stage.__name__) # Simplest ca...
def _parse_stage_spec(stage_spec)
Handle alternate Stage specifications, returning name and Stage. Isolate this parsing logic from any iteration. TypeError as single exception type funnel also provides a more uniform way for callers to handle specification errors (e.g., skip a stage, warn, re-raise, etc.) :param (str, pypiper.Stage) |...
6.250203
5.55068
1.126025
# Canonical usage model for Pipeline checkpointing through # implementations of this class is by automatically creating a # checkpoint when a conceptual unit or group of operations of a # pipeline completes, so fix the 'finished' parameter to the manager's # timestamp me...
def checkpoint(self, stage, msg="")
Touch checkpoint file for given stage and provide timestamp message. :param pypiper.Stage stage: Stage for which to mark checkpoint :param str msg: Message to embed in timestamp. :return bool: Whether a checkpoint file was written.
32.68409
26.351629
1.240306
check_path = checkpoint_filepath(stage, self.manager) return os.path.exists(check_path)
def completed_stage(self, stage)
Determine whether the pipeline's completed the stage indicated. :param pypiper.Stage stage: Stage to check for completion status. :return bool: Whether this pipeline's completed the indicated stage. :raises UnknownStageException: If the stage name given is undefined for the pipeline...
10.501155
15.165275
0.692447
paths = glob.glob(os.path.join(self.outfolder, flag_name("*"))) if only_name: return [os.path.split(p)[1] for p in paths] else: return paths
def list_flags(self, only_name=False)
Determine the flag files associated with this pipeline. :param bool only_name: Whether to return only flag file name(s) (True), or full flag file paths (False); default False (paths) :return list[str]: flag files associated with this pipeline.
3.542232
3.95347
0.89598
# Start the run with a clean slate of Stage status/label tracking. self._reset() # TODO: validate starting point against checkpoint flags for # TODO (cont.): earlier stages if the pipeline defines its stages as a # TODO (cont.): sequence (i.e., probably prohibit start ...
def run(self, start_point=None, stop_before=None, stop_after=None)
Run the pipeline, optionally specifying start and/or stop points. :param str start_point: Name of stage at which to begin execution. :param str stop_before: Name of stage at which to cease execution; exclusive, i.e. this stage is not run :param str stop_after: Name of stage at which...
6.905105
6.691127
1.031979
if start is None: return 0 start_stage = translate_stage_name(start) internal_names = [translate_stage_name(s.name) for s in self._stages] try: return internal_names.index(start_stage) except ValueError: raise UnknownPipelineStageError...
def _start_index(self, start=None)
Seek to the first stage to run.
4.045114
3.41111
1.185865
if not stop_point: # Null case, no stopping point return len(self._stages) stop_name = parse_stage_name(stop_point) try: stop_index = self.stage_names.index(stop_name) except ValueError: raise UnknownPipelineStageError(stop_name, s...
def _stop_index(self, stop_point, inclusive)
Determine index of stage of stopping point for run(). :param str | pypiper.Stage | function stop_point: Stopping point itself or name of it. :param bool inclusive: Whether the stopping point is to be regarded as inclusive (i.e., whether it's the final stage to run, or the one ...
3.923707
3.537383
1.109212