INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
match_key: key of the match over_key: key of the over Return: json data:
def get_ball_by_ball(self, match_key, over_key=None): """ match_key: key of the match over_key : key of the over Return: json data: """ if over_key: ball_by_ball_url = "{base_path}match/{match_key}/balls/{over_key}/".format(base_path=self....
Calling specific season recent matches.
def get_recent_season_matches(self, season_key): """ Calling specific season recent matches. Arg: season_key: key of the season. Return: json date """ season_recent_matches_url = self.api_path + "season/" + season_key + "/recent_matches/" r...
Calling the Recent Season API.
def get_recent_seasons(self): """ Calling the Recent Season API. Return: json data """ recent_seasons_url = self.api_path + "recent_seasons/" response = self.get_response(recent_seasons_url) return response
Calling the Schedule API.
def get_schedule(self, date=None): """ Calling the Schedule API. Return: json data """ schedule_url = self.api_path + "schedule/" params = {} if date: params['date'] = date response = self.get_response(schedule_url, params) ...
Calling specific season schedule
def get_season_schedule(self, season_key): """ Calling specific season schedule Arg: season_key: key of the season Return: json data """ schedule_url = self.api_path + "season/" + season_key + "/schedule/" response = self.get_response(sched...
Calling Season API.
def get_season(self, season_key, card_type="micro_card"): """ Calling Season API. Arg: season_key: key of the season card_type: optional, default to micro_card. Accepted values are micro_card & summary_card Return: json data """ ...
Calling Season Stats API.
def get_season_stats(self, season_key): """ Calling Season Stats API. Arg: season_key: key of the season Return: json data """ season_stats_url = self.api_path + "season/" + season_key + "/stats/" response = self.get_response(season_stats_u...
Calling Season teams API
def get_season_team(self, season_key, season_team_key,stats_type=None): """ Calling Season teams API Arg: season_key: key of the season Return: json data """ params = {"stats_type": stats_type} season_team_url = self.api_path + 'season/' +...
Calling Season Points API.
def get_season_points(self, season_key): """ Calling Season Points API. Arg: season_key: key of the season Return: json data """ season_points_url = self.api_path + "season/" + season_key + "/points/" response = self.get_response(season_poi...
Calling Season Player Stats API.
def get_season_player_stats(self, season_key, player_key): """ Calling Season Player Stats API. Arg: season_key: key of the season player_key: key of the player Return: json data """ season_player_stats_url = self.api_path + "season/" + ...
Calling Overs Summary API
def get_overs_summary(self, match_key): """ Calling Overs Summary API Arg: match_key: key of the match Return: json data """ overs_summary_url = self.api_path + "match/" + match_key + "/overs_summary/" response = self.get_response(overs_summ...
Calling News Aggregation API
def get_news_aggregation(self): """ Calling News Aggregation API Return: json data """ news_aggregation_url = self.api_path + "news_aggregation" + "/" response = self.get_response(news_aggregation_url) return response
Calling Fantasy Credit API
def get_fantasy_credits(self, match_key): """ Calling Fantasy Credit API Arg: match_key: key of the match Return: json data """ fantasy_credit_url = self.api_path_v3 + "fantasy-match-credits/" + match_key + "/" response = self.get_respons...
Calling Fantasy Points API
def get_fantasy_points(self, match_key): """ Calling Fantasy Points API Arg: match_key: key of the match Return: json data """ fantasy_points_url = self.api_path_v3 + "fantasy-match-points/" + match_key + "/" response = self.get_response(...
Generates an output string by replacing the keywords in the format string with the corresponding values from a submission dictionary.
def main(self): """ Generates an output string by replacing the keywords in the format string with the corresponding values from a submission dictionary. """ self.manage_submissions() out_string = self.options['format'] # Pop until we get something which len(titl...
Logs into Reddit in order to display a personalised front page.
def login(self): """ Logs into Reddit in order to display a personalised front page. """ data = {'user': self.options['username'], 'passwd': self.options['password'], 'api_type': 'json'} response = self.client.post('http://www.reddit.com/api/login', data=data) ...
If there are no or only one submissions left get new submissions. This function manages URL creation and the specifics for front page or subreddit mode.
def manage_submissions(self): """ If there are no or only one submissions left, get new submissions. This function manages URL creation and the specifics for front page or subreddit mode. """ if not hasattr(self, 'submissions') or len(self.submissions) == 1: s...
Connects to Reddit and gets a JSON representation of submissions. This JSON data is then processed and returned.
def get_submissions(self, url): """ Connects to Reddit and gets a JSON representation of submissions. This JSON data is then processed and returned. url: A url that requests for submissions should be sent to. """ response = self.client.get(url, params={'limit': self.opti...
A compulsary function that gets the output of the cmus - remote - Q command and converts it to unicode in order for it to be processed and finally output.
def main(self): """ A compulsary function that gets the output of the cmus-remote -Q command and converts it to unicode in order for it to be processed and finally output. """ try: # Setting stderr to subprocess.STDOUT seems to stop the error # mes...
Change the newline separated string of output data into a dictionary which can then be used to replace the strings in the config format.
def convert_cmus_output(self, cmus_output): """ Change the newline separated string of output data into a dictionary which can then be used to replace the strings in the config format. cmus_output: A string with information about cmus that is newline seperated. Running c...
A helper function to convert seconds into hh: mm: ss for better readability.
def convert_time(self, time): """ A helper function to convert seconds into hh:mm:ss for better readability. time: A string representing time in seconds. """ time_string = str(datetime.timedelta(seconds=int(time))) if time_string.split(':')[0] == '0': ...
Output all of the options and data for a segment.
def output(self, full_text, short_text): """ Output all of the options and data for a segment. full_text: A string representing the data that should be output to i3bar. short_text: A more concise version of full_text, in case there is minimal room on the i3bar. """ ...
A function that should be overwritten by a plugin that wishes to react to events if it wants to perform any action other than running the supplied command related to a button.
def on_click(self, event): """ A function that should be overwritten by a plugin that wishes to react to events, if it wants to perform any action other than running the supplied command related to a button. event: A dictionary passed from i3bar (after being decoded from JSON) ...
Reverse the requested URL ( passed via GET/ POST as url_name parameter )
def url_reverse(request): """ Reverse the requested URL (passed via GET / POST as `url_name` parameter) :param request: Request object :return: The reversed path """ if request.method in ('GET', 'POST'): data = getattr(request, request.method) url_name = data.get('url_name') ...
Converts a filer image ID in a complete path
def url_image(request, image_id, thumb_options=None, width=None, height=None): """ Converts a filer image ID in a complete path :param request: Request object :param image_id: Filer image ID :param thumb_options: ThumbnailOption ID :param width: user-provided width :param height: user-provi...
Returns the requested ThumbnailOption as JSON
def thumbnail_options(request): """ Returns the requested ThumbnailOption as JSON :param request: Request object :return: JSON serialized ThumbnailOption """ response_data = [{'id': opt.pk, 'name': opt.name} for opt in ThumbnailOption.objects.all()] return http.HttpResponse(json.dumps(respo...
returns the content of an image sized according to the parameters
def serve_image(request, image_id, thumb_options=None, width=None, height=None): """ returns the content of an image sized according to the parameters :param request: Request object :param image_id: Filer image ID :param thumb_options: ThumbnailOption ID :param width: user-provided width :p...
A helper function to create a directory if it doesn t exist.
def _touch_dir(self, path): """ A helper function to create a directory if it doesn't exist. path: A string containing a full path to the directory to be created. """ try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: ...
Reload the configuration from the file. This is in its own function so that it can be called at any time by another class.
def reload(self): """ Reload the configuration from the file. This is in its own function so that it can be called at any time by another class. """ self._conf = configparser.ConfigParser() # Preserve the case of sections and keys. self._conf.optionxform = str ...
Replaces strings with appropriate data types ( int boolean ). Also replaces the human readable logging levels with the integer form.
def _replace_data_types(dictionary): """ Replaces strings with appropriate data types (int, boolean). Also replaces the human readable logging levels with the integer form. dictionary: A dictionary returned from the config file. """ logging_levels = {'NONE': 0, 'NULL': 0...
Command line interface for the rotate - backups program.
def main(): """Command line interface for the ``rotate-backups`` program.""" coloredlogs.install(syslog=True) # Command line option defaults. rotation_scheme = {} kw = dict(include_list=[], exclude_list=[]) parallel = False use_sudo = False # Internal state. selected_locations = [] ...
Return the first line from the file located at battery_path/ prop as a string.
def get_battery_state(self, prop): """ Return the first line from the file located at battery_path/prop as a string. """ with open(os.path.join(self.options['battery_path'], prop), 'r') as f: return f.readline().strip()
Coerce a string to a: class: Location object.
def coerce_location(value, **options): """ Coerce a string to a :class:`Location` object. :param value: The value to coerce (a string or :class:`Location` object). :param options: Any keyword arguments are passed on to :func:`~executor.contexts.create_context()`. :returns: A :cl...
Coerce a retention period to a Python value.
def coerce_retention_period(value): """ Coerce a retention period to a Python value. :param value: A string containing the text 'always', a number or an expression that can be evaluated to a number. :returns: A number or the string 'always'. :raises: :exc:`~exceptions.ValueError` ...
Load a configuration file with backup directories and rotation schemes.
def load_config_file(configuration_file=None, expand=True): """ Load a configuration file with backup directories and rotation schemes. :param configuration_file: Override the pathname of the configuration file to load (a string or :data:`None`). :param expand: :data:`Tru...
Rotate the backups in a directory according to a flexible rotation scheme.
def rotate_backups(directory, rotation_scheme, **options): """ Rotate the backups in a directory according to a flexible rotation scheme. .. note:: This function exists to preserve backwards compatibility with older versions of the `rotate-backups` package where all of the logic...
Rotate the backups in the given locations concurrently.
def rotate_concurrent(self, *locations, **kw): """ Rotate the backups in the given locations concurrently. :param locations: One or more values accepted by :func:`coerce_location()`. :param kw: Any keyword arguments are passed on to :func:`rotate_backups()`. This function uses ...
Rotate the backups in a directory according to a flexible rotation scheme.
def rotate_backups(self, location, load_config=True, prepare=False): """ Rotate the backups in a directory according to a flexible rotation scheme. :param location: Any value accepted by :func:`coerce_location()`. :param load_config: If :data:`True` (so by default) the rotation scheme ...
Load a rotation scheme and other options from a configuration file.
def load_config_file(self, location): """ Load a rotation scheme and other options from a configuration file. :param location: Any value accepted by :func:`coerce_location()`. :returns: The configured or given :class:`Location` object. """ location = coerce_location(loca...
Collect the backups at the given location.
def collect_backups(self, location): """ Collect the backups at the given location. :param location: Any value accepted by :func:`coerce_location()`. :returns: A sorted :class:`list` of :class:`Backup` objects (the backups are sorted by their date). :raises: :e...
Group backups collected by: func: collect_backups () by rotation frequencies.
def group_backups(self, backups): """ Group backups collected by :func:`collect_backups()` by rotation frequencies. :param backups: A :class:`set` of :class:`Backup` objects. :returns: A :class:`dict` whose keys are the names of rotation frequencies ('hourly', 'daily',...
Apply the user defined rotation scheme to the result of: func: group_backups ().
def apply_rotation_scheme(self, backups_by_frequency, most_recent_backup): """ Apply the user defined rotation scheme to the result of :func:`group_backups()`. :param backups_by_frequency: A :class:`dict` in the format generated by :func:`group_backups()`. ...
Collect the criteria used to decide which backups to preserve.
def find_preservation_criteria(self, backups_by_frequency): """ Collect the criteria used to decide which backups to preserve. :param backups_by_frequency: A :class:`dict` in the format generated by :func:`group_backups()` which has been ...
The pathname of the mount point of: attr: directory ( a string or: data: None ).
def mount_point(self): """ The pathname of the mount point of :attr:`directory` (a string or :data:`None`). If the ``stat --format=%m ...`` command that is used to determine the mount point fails, the value of this property defaults to :data:`None`. This enables graceful degrada...
Make sure the location exists.
def ensure_exists(self): """Make sure the location exists.""" if not self.context.is_directory(self.directory): # This can also happen when we don't have permission to one of the # parent directories so we'll point that out in the error message # when it seems applica...
Make sure the location exists and is readable.
def ensure_readable(self): """Make sure the location exists and is readable.""" self.ensure_exists() if not self.context.is_readable(self.directory): if self.context.have_superuser_privileges: msg = "The directory %s isn't readable!" raise ValueError(m...
Make sure the directory exists and is writable.
def ensure_writable(self): """Make sure the directory exists and is writable.""" self.ensure_exists() if not self.context.is_writable(self.directory): if self.context.have_superuser_privileges: msg = "The directory %s isn't writable!" raise ValueError(...
Check if the given location matches.
def match(self, location): """ Check if the given location "matches". :param location: The :class:`Location` object to try to match. :returns: :data:`True` if the two locations are on the same system and the :attr:`directory` can be matched as a filename pattern or ...
A helper function for creating a file logger. Accepts arguments as it is used in Status and LoggingWriter.
def setup_file_logger(filename, formatting, log_level): """ A helper function for creating a file logger. Accepts arguments, as it is used in Status and LoggingWriter. """ logger = logging.getLogger() # If a stream handler has been attached, remove it. if logger.handlers: logger.remo...
Outputs data to stdout without buffering.
def output_to_bar(self, message, comma=True): """ Outputs data to stdout, without buffering. message: A string containing the data to be output. comma: Whether or not a comma should be placed at the end of the output. """ if comma: message += ',' sys....
Reload the installed plugins and the configuration file. This is called when either the plugins or config get updated.
def reload(self): """ Reload the installed plugins and the configuration file. This is called when either the plugins or config get updated. """ logging.debug('Reloading config file as files have been modified.') self.config.plugin, self.config.general = self.config.reloa...
Creates a thread for each plugin and lets the thread_manager handle it.
def run_plugins(self): """ Creates a thread for each plugin and lets the thread_manager handle it. """ for obj in self.loader.objects: # Reserve a slot in the output_dict in order to ensure that the # items are in the correct order. self.output_dict[ob...
Monitors if the config file or plugins are updated. Also outputs the JSON data generated by the plugins without needing to poll the threads.
def run(self): """ Monitors if the config file or plugins are updated. Also outputs the JSON data generated by the plugins, without needing to poll the threads. """ self.run_plugins() while True: # Reload plugins and config if either the config file or plugin ...
If plugins haven t been initialised and therefore not sending output or their output is None there is no reason to take up extra room on the bar.
def _remove_empty_output(self): """ If plugins haven't been initialised and therefore not sending output or their output is None, there is no reason to take up extra room on the bar. """ output = [] for key in self.output_dict: if self.output_dict[key]...
An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in another thread so as to not stall the main thread.
def handle_events(self): """ An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in another thread, so as to not stall the main thread. """ for event in sys.stdin: if event.startswith...
Helper function that returns a dictionary of all fields in the given model. If self. field_filter is set it only includes the fields that match the filter.
def field_dict(self, model): """ Helper function that returns a dictionary of all fields in the given model. If self.field_filter is set, it only includes the fields that match the filter. """ if self.field_filter: return dict( [(f.name, f) for...
Calls the main function of a plugin and mutates the output dict with its return value. Provides an easy way to change the output whilst not needing to constantly poll a queue in another thread and allowing plugin s to manage their own intervals.
def run(self): """ Calls the main function of a plugin and mutates the output dict with its return value. Provides an easy way to change the output whilst not needing to constantly poll a queue in another thread and allowing plugin's to manage their own intervals. """ ...
Creates a thread starts it and then adds it to the thread pool.
def add_thread(self, func, interval): """ Creates a thread, starts it and then adds it to the thread pool. Func: Same as in the Thread class. Interval: Same as in the Thread class. """ t = Thread(func, interval, self.output_dict) t.start() self._thread_po...
Compiles python plugin files in order to be processed by the loader. It compiles the plugins if they have been updated or haven t yet been compiled.
def _compile_files(self): """ Compiles python plugin files in order to be processed by the loader. It compiles the plugins if they have been updated or haven't yet been compiled. """ for f in glob.glob(os.path.join(self.dir_path, '*.py')): # Check for compiled...
Accepts a path to a compiled plugin and returns a module object.
def _load_compiled(self, file_path): """ Accepts a path to a compiled plugin and returns a module object. file_path: A string that represents a complete file path to a compiled plugin. """ name = os.path.splitext(os.path.split(file_path)[-1])[0] plugin_directory ...
Matches the plugins that have been specified in the config file with the available plugins. Returns instantiated objects based upon the classes defined in the plugins.
def load_objects(self): """ Matches the plugins that have been specified in the config file with the available plugins. Returns instantiated objects based upon the classes defined in the plugins. """ objects = [] for settings in self._config: if settin...
Discovers the available plugins and turns each into a module object. This is a seperate function to allow plugins to be updated dynamically by other parts of the application.
def refresh_files(self): """ Discovers the available plugins and turns each into a module object. This is a seperate function to allow plugins to be updated dynamically by other parts of the application. """ plugins = {} _plugin_files = glob.glob(os.path.join(self...
Handles main URL routing for the databrowse app.
def root(self, request, url): """ Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. 'objects/3'. """ # Delegate to the appropriate method, based on the URL. if url is None: return self.main_view(request) try: ...
Registers the given model ( s ) with the given databrowse site.
def register(self, *model_list, **options): """ Registers the given model(s) with the given databrowse site. The model(s) should be Model classes, not instances. If a databrowse class isn't given, it will use DefaultModelDatabrowse (the default databrowse options). If ...
Unregisters the given model ( s ).
def unregister(self, *model_list): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ for model in model_list: if model not in self.registry: raise NotRegistered('The model %s is not registered'...
Handles main URL routing for the databrowse app.
def root(self, request, url): """ Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. 'comments/comment/'. """ self.root_url = request.path[:len(request.path) - len(url)] url = url.rstrip('/') # Trim trailing slash, if it exists. ...
Handles the model - specific functionality of the databrowse site delegating<to the appropriate ModelDatabrowse class.
def model_page(self, request, app_label, model_name, rest_of_url=None): """ Handles the model-specific functionality of the databrowse site, delegating<to the appropriate ModelDatabrowse class. """ try: model = get_model(app_label, model_name) except LookupErr...
Returns a list of values for this field for this instance. It s a list so we can accomodate many - to - many fields.
def values(self): """ Returns a list of values for this field for this instance. It's a list so we can accomodate many-to-many fields. """ # This import is deliberately inside the function because it causes # some settings to be imported, and we don't want to do that at t...
Returns a list of ( value URL ) tuples.
def urls(self): "Returns a list of (value, URL) tuples." # First, check the urls() method for each plugin. plugin_urls = [] for plugin_name, plugin in \ self.model.model_databrowse().plugins.items(): urls = plugin.urls(plugin_name, self) ...
Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self. field_names is set it takes that into account when building the dictionary.
def field_dict(self, model): """ Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it takes that into account when building the dictionary. """ if self.field_names is None: return dict...
Optionally launches a Spark cluster and then runs ADAM to count k - mers on an input file.
def kmer_dag(job, input_file, output_path, kmer_length, spark_conf, workers, cores, memory, sudo): ''' Optionally launches a Spark cluster and then runs ADAM to count k-mers on an input file. :param ...
Runs k - mer counting.
def download_count_upload(job, master_ip, input_file, output_file, kmer_length, spark_conf, memory, sudo): ''' Runs k-mer counting...
Sets up command line parser for Toil/ ADAM based k - mer counter and launches k - mer counter with optional Spark cluster.
def main(): ''' Sets up command line parser for Toil/ADAM based k-mer counter, and launches k-mer counter with optional Spark cluster. ''' parser = argparse.ArgumentParser() # add parser arguments parser.add_argument('--input_path', help='The full path to the input ...
Downloads shared files and calls the GATK best practices germline pipeline for a cohort of samples
def run_gatk_germline_pipeline(job, samples, config): """ Downloads shared files and calls the GATK best practices germline pipeline for a cohort of samples :param JobFunctionWrappingJob job: passed automatically by Toil :param list[GermlineSample] samples: List of GermlineSample namedtuples :param...
Runs the GATK best practices pipeline for germline SNP and INDEL discovery.
def gatk_germline_pipeline(job, samples, config): """ Runs the GATK best practices pipeline for germline SNP and INDEL discovery. Steps in Pipeline 0: Generate and preprocess BAM - Uploads processed BAM to output directory 1: Call Variants using HaplotypeCaller - Uploads GVCF 2:...
Checks for enough disk space for joint genotyping then calls the genotype and filter pipeline function.
def joint_genotype_and_filter(job, gvcfs, config): """ Checks for enough disk space for joint genotyping, then calls the genotype and filter pipeline function. :param JobFunctionWrappingJob job: passed automatically by Toil :param dict gvcfs: Dictionary of GVCFs {Sample ID: FileStoreID} :param Name...
Genotypes one or more GVCF files and runs either the VQSR or hard filtering pipeline. Uploads the genotyped VCF file to the config output directory.
def genotype_and_filter(job, gvcfs, config): """ Genotypes one or more GVCF files and runs either the VQSR or hard filtering pipeline. Uploads the genotyped VCF file to the config output directory. :param JobFunctionWrappingJob job: passed automatically by Toil :param dict gvcfs: Dictionary of GVCF...
Runs Oncotator for a group of VCF files. Each sample is annotated individually.
def annotate_vcfs(job, vcfs, config): """ Runs Oncotator for a group of VCF files. Each sample is annotated individually. :param JobFunctionWrappingJob job: passed automatically by Toil :param dict vcfs: Dictionary of VCF FileStoreIDs {Sample identifier: FileStoreID} :param Namespace config: Input ...
Parses manifest file for Toil Germline Pipeline
def parse_manifest(path_to_manifest): """ Parses manifest file for Toil Germline Pipeline :param str path_to_manifest: Path to sample manifest file :return: List of GermlineSample namedtuples :rtype: list[GermlineSample] """ bam_re = r"^(?P<uuid>\S+)\s(?P<url>\S+[bsc][r]?am)" fq_re = r"...
Downloads shared reference files for Toil Germline pipeline
def download_shared_files(job, config): """ Downloads shared reference files for Toil Germline pipeline :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Pipeline configuration options :return: Updated config with shared fileStoreIDS :rtype: Namespace ...
Creates a genome fasta index and sequence dictionary file if not already present in the pipeline config.
def reference_preprocessing(job, config): """ Creates a genome fasta index and sequence dictionary file if not already present in the pipeline config. :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Pipeline configuration options and shared files. ...
Prepares BAM file for Toil germline pipeline.
def prepare_bam(job, uuid, url, config, paired_url=None, rg_line=None): """ Prepares BAM file for Toil germline pipeline. Steps in pipeline 0: Download and align BAM or FASTQ sample 1: Sort BAM 2: Index BAM 3: Run GATK preprocessing pipeline (Optional) - Uploads preprocessed BAM to ...
Downloads and runs bwakit for BAM or FASTQ files
def setup_and_run_bwakit(job, uuid, url, rg_line, config, paired_url=None): """ Downloads and runs bwakit for BAM or FASTQ files :param JobFunctionWrappingJob job: passed automatically by Toil :param str uuid: Unique sample identifier :param str url: FASTQ or BAM file URL. BAM alignment URL must ha...
Uses GATK HaplotypeCaller to identify SNPs and INDELs. Outputs variants in a Genomic VCF file.
def gatk_haplotype_caller(job, bam, bai, ref, fai, ref_dict, annotations=None, emit_threshold=10.0, call_threshold=30.0, unsafe_mode=False, hc_output=None): """...
GATK germline pipeline with variant filtering and annotation.
def main(): """ GATK germline pipeline with variant filtering and annotation. """ # Define Parser object and add to jobTree parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter) # Generate subparsers subparsers = parser.add_subparsers(dest='com...
Loops over the sample_ids ( uuids ) in the manifest creating child jobs to process each
def sample_loop(job, uuid_list, inputs): """ Loops over the sample_ids (uuids) in the manifest, creating child jobs to process each """ for uuid_rg in uuid_list: uuid_items = uuid_rg.split(',') uuid = uuid_items[0] rg_line = None if len(uuid_items) > 1: rg_line = uuid_items[1] job...
Prefer this here as it allows us to pull the job functions from other jobs without rewrapping the job functions back together.
def static_dag(job, uuid, rg_line, inputs): """ Prefer this here as it allows us to pull the job functions from other jobs without rewrapping the job functions back together. bwa_inputs: Input arguments to be passed to BWA. adam_inputs: Input arguments to be passed to ADAM. gatk_preprocess_inpu...
This is a Toil pipeline used to perform alignment of fastqs.
def main(): """ This is a Toil pipeline used to perform alignment of fastqs. """ # Define Parser object and add to Toil if mock_mode(): usage_msg = 'You have the TOIL_SCRIPTS_MOCK_MODE environment variable set, so this pipeline ' \ 'will run in mock mode. To disable mock ...
Input1: Path to the BD2K Master Key ( for S3 Encryption ) Input2: S3 URL ( e. g. https:// s3 - us - west - 2. amazonaws. com/ cgl - driver - projects - encrypted/ wcdt/ exome_bams/ DTB - 111 - N. bam )
def generate_unique_key(master_key_path, url): """ Input1: Path to the BD2K Master Key (for S3 Encryption) Input2: S3 URL (e.g. https://s3-us-west-2.amazonaws.com/cgl-driver-projects-encrypted/wcdt/exome_bams/DTB-111-N.bam) Returns: 32-byte unique key generated for that URL """ with open(master...
Downloads encrypted file from S3
def download_encrypted_file(work_dir, url, key_path, name): """ Downloads encrypted file from S3 Input1: Working directory Input2: S3 URL to be downloaded Input3: Path to key necessary for decryption Input4: name of file to be downloaded """ file_path = os.path.join(work_dir, name) ...
Returns the paths of files from the FileStore
def return_input_paths(job, work_dir, ids, *args): """ Returns the paths of files from the FileStore Input1: Toil job instance Input2: Working directory Input3: jobstore id dictionary Input4: names of files to be returned from the jobstore Returns: path(s) to the file(s) requested -- unpac...
Moves files from work_dir to output_dir
def move_to_output_dir(work_dir, output_dir, uuid=None, files=list()): """ Moves files from work_dir to output_dir Input1: Working directory Input2: Output directory Input3: UUID to be preprended onto file name Input4: list of file names to be moved from working dir to output dir """ fo...
Downloads shared files that are used by all samples for alignment and places them in the jobstore.
def batch_start(job, input_args): """ Downloads shared files that are used by all samples for alignment and places them in the jobstore. """ shared_files = ['ref.fa', 'ref.fa.amb', 'ref.fa.ann', 'ref.fa.bwt', 'ref.fa.pac', 'ref.fa.sa', 'ref.fa.fai'] shared_ids = {} for fname in shared_files: ...
Spawns an alignment job for every sample in the input configuration file
def spawn_batch_jobs(job, shared_ids, input_args): """ Spawns an alignment job for every sample in the input configuration file """ samples = [] config = input_args['config'] with open(config, 'r') as f_in: for line in f_in: line = line.strip().split(',') uuid = l...
Runs BWA and then Bamsort on the supplied fastqs for this sample
def alignment(job, ids, input_args, sample): """ Runs BWA and then Bamsort on the supplied fastqs for this sample Input1: Toil Job instance Input2: jobstore id dictionary Input3: Input arguments dictionary Input4: Sample tuple -- contains uuid and urls for the sample """ uuid, urls = sa...
Uploads output BAM from sample to S3
def upload_bam_to_s3(job, ids, input_args, sample): """ Uploads output BAM from sample to S3 Input1: Toil Job instance Input2: jobstore id dictionary Input3: Input arguments dictionary Input4: Sample tuple -- contains uuid and urls for the sample """ uuid, urls = sample key_path = i...
Runs GATK Variant Quality Score Recalibration.
def vqsr_pipeline(job, uuid, vcf_id, config): """ Runs GATK Variant Quality Score Recalibration. 0: Start 0 --> 1 --> 3 --> 4 --> 5 1: Recalibrate SNPs | | 2: Recalibrate INDELS +-> 2 -+ 3: Apply SNP Recalibration 4: Apply INDEL ...
Converts full GATK annotation name to the shortened version: param annotations:: return:
def get_short_annotations(annotations): """ Converts full GATK annotation name to the shortened version :param annotations: :return: """ # Annotations need to match VCF header short_name = {'QualByDepth': 'QD', 'FisherStrand': 'FS', 'StrandOddsRatio': 'SOR...
Parses genetorrent config file. Returns list of samples: [ [ id1 id1 ] [ id2 id2 ]... ] Returns duplicate of ids to follow UUID/ URL standard.
def parse_sra(path_to_config): """ Parses genetorrent config file. Returns list of samples: [ [id1, id1 ], [id2, id2], ... ] Returns duplicate of ids to follow UUID/URL standard. """ samples = [] with open(path_to_config, 'r') as f: for line in f.readlines(): if not line.iss...
Tars a group of files together into a tarball
def tarball_files(work_dir, tar_name, uuid=None, files=None): """ Tars a group of files together into a tarball work_dir: str Current Working Directory tar_name: str Name of tarball uuid: str UUID to stamp files with files: str(s) List of filenames to place in the ta...