gt_call = {}<EOL>ind_id = ind['<STR_LIT>']<EOL>gt_call['<STR_LIT>'] = ind_id<EOL>gt_call['<STR_LIT>'] = ind['<STR_LIT>']<EOL>genotype = variant.genotypes[pos]<EOL>ref_call = genotype[<NUM_LIT:0>]<EOL>alt_call = genotype[<NUM_LIT:1>]<EOL>gt_call['<STR_LIT>'] = '<STR_LIT:/>'.join([GENOTYPE_MAP[ref_call],<EOL>GENOTYPE_MAP[alt_call]])<EOL>paired_end_alt = None<EOL>paired_end_ref = None<EOL>split_read_alt = None<EOL>split_read_ref = None<EOL>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>try:<EOL><INDENT>value = int(variant.format('<STR_LIT>')[pos])<EOL>if not value < <NUM_LIT:0>:<EOL><INDENT>paired_end_alt = value<EOL><DEDENT><DEDENT>except ValueError as e:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>values = variant.format('<STR_LIT>')[pos]<EOL>try:<EOL><INDENT>alt_value = int(values[<NUM_LIT:1>])<EOL>ref_value = int(values[<NUM_LIT:0>])<EOL>if not alt_value < <NUM_LIT:0>:<EOL><INDENT>paired_end_alt = alt_value<EOL><DEDENT>if not ref_value < <NUM_LIT:0>:<EOL><INDENT>paired_end_ref = ref_value<EOL><DEDENT><DEDENT>except ValueError as r:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>values = variant.format('<STR_LIT>')[pos]<EOL>alt_value = <NUM_LIT:0><EOL>ref_value = <NUM_LIT:0><EOL>if len(values) == <NUM_LIT:1>:<EOL><INDENT>alt_value = int(values[<NUM_LIT:0>])<EOL><DEDENT>elif len(values) == <NUM_LIT:2>:<EOL><INDENT>alt_value = int(values[<NUM_LIT:1>])<EOL>ref_value = int(values[<NUM_LIT:0>])<EOL><DEDENT>if not alt_value < <NUM_LIT:0>:<EOL><INDENT>split_read_alt = alt_value<EOL><DEDENT>if not ref_value < <NUM_LIT:0>:<EOL><INDENT>split_read_ref = ref_value<EOL><DEDENT><DEDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>values = variant.format('<STR_LIT>')[pos]<EOL>alt_value = int(values[<NUM_LIT:0>])<EOL>if not alt_value < <NUM_LIT:0>:<EOL><INDENT>paired_end_alt = alt_value<EOL><DEDENT><DEDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>values = variant.format('<STR_LIT>')[pos]<EOL>ref_value = int(values[<NUM_LIT:0>])<EOL>if not alt_value < <NUM_LIT:0>:<EOL><INDENT>paired_end_ref = ref_value<EOL><DEDENT><DEDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>values = variant.format('<STR_LIT>')[pos]<EOL>alt_value = int(values[<NUM_LIT:0>])<EOL>if not alt_value < <NUM_LIT:0>:<EOL><INDENT>split_read_alt = alt_value<EOL><DEDENT><DEDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>values = variant.format('<STR_LIT>')[pos]<EOL>ref_value = int(values[<NUM_LIT:0>])<EOL>if not ref_value < <NUM_LIT:0>:<EOL><INDENT>split_read_ref = ref_value<EOL><DEDENT><DEDENT>alt_depth = int(variant.gt_alt_depths[pos])<EOL>if alt_depth == -<NUM_LIT:1>:<EOL><INDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>alt_depth = int(variant.format('<STR_LIT>')[pos][<NUM_LIT:0>])<EOL><DEDENT>if (paired_end_alt != None or split_read_alt != None):<EOL><INDENT>alt_depth = <NUM_LIT:0><EOL>if paired_end_alt:<EOL><INDENT>alt_depth += paired_end_alt<EOL><DEDENT>if split_read_alt:<EOL><INDENT>alt_depth += split_read_alt<EOL><DEDENT><DEDENT><DEDENT>gt_call['<STR_LIT>'] = alt_depth<EOL>ref_depth = int(variant.gt_ref_depths[pos])<EOL>if ref_depth == -<NUM_LIT:1>:<EOL><INDENT>if (paired_end_ref != None or split_read_ref != None):<EOL><INDENT>ref_depth = <NUM_LIT:0><EOL>if paired_end_ref:<EOL><INDENT>ref_depth += paired_end_ref<EOL><DEDENT>if split_read_ref:<EOL><INDENT>ref_depth += split_read_ref<EOL><DEDENT><DEDENT><DEDENT>gt_call['<STR_LIT>'] = ref_depth<EOL>alt_frequency = float(variant.gt_alt_freqs[pos])<EOL>if alt_frequency == -<NUM_LIT:1>:<EOL><INDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>alt_frequency = float(variant.format('<STR_LIT>')[pos][<NUM_LIT:0>])<EOL><DEDENT><DEDENT>read_depth = int(variant.gt_depths[pos])<EOL>if read_depth == -<NUM_LIT:1>:<EOL><INDENT>if '<STR_LIT>' in variant.FORMAT:<EOL><INDENT>read_depth = int(variant.format('<STR_LIT>')[pos][<NUM_LIT:0>])<EOL><DEDENT>elif (alt_depth != -<NUM_LIT:1> or ref_depth != -<NUM_LIT:1>):<EOL><INDENT>read_depth = <NUM_LIT:0><EOL>if alt_depth != -<NUM_LIT:1>:<EOL><INDENT>read_depth += alt_depth<EOL><DEDENT>if ref_depth != -<NUM_LIT:1>:<EOL><INDENT>read_depth += alt_depth<EOL><DEDENT><DEDENT><DEDENT>gt_call['<STR_LIT>'] = read_depth<EOL>gt_call['<STR_LIT>'] = alt_frequency<EOL>gt_call['<STR_LIT>'] = int(variant.gt_quals[pos])<EOL>return gt_call<EOL>

Get the genotype information in the proper format

    Sv specific format fields:

    ##FORMAT=<ID=DV,Number=1,Type=Integer,
    Description="Number of paired-ends that support the event">

    ##FORMAT=<ID=PE,Number=1,Type=Integer,
    Description="Number of paired-ends that support the event">

    ##FORMAT=<ID=PR,Number=.,Type=Integer,
    Description="Spanning paired-read support for the ref and alt alleles
                in the order listed">

    ##FORMAT=<ID=RC,Number=1,Type=Integer,
    Description="Raw high-quality read counts for the SV">

    ##FORMAT=<ID=RCL,Number=1,Type=Integer,
    Description="Raw high-quality read counts for the left control region">

    ##FORMAT=<ID=RCR,Number=1,Type=Integer,
    Description="Raw high-quality read counts for the right control region">

    ##FORMAT=<ID=RR,Number=1,Type=Integer,
    Description="# high-quality reference junction reads">

    ##FORMAT=<ID=RV,Number=1,Type=Integer,
    Description="# high-quality variant junction reads">

    ##FORMAT=<ID=SR,Number=1,Type=Integer,
    Description="Number of split reads that support the event">

    Args:
        variant(cyvcf2.Variant)
        ind_id(dict): A dictionary with individual information
        pos(int): What position the ind has in vcf

    Returns:
        gt_call(dict)


cadd = <NUM_LIT:0><EOL>cadd_keys = ['<STR_LIT>', '<STR_LIT>']<EOL>for key in cadd_keys:<EOL><INDENT>cadd = variant.INFO.get(key, <NUM_LIT:0>)<EOL>if cadd:<EOL><INDENT>return float(cadd)<EOL><DEDENT><DEDENT>for transcript in transcripts:<EOL><INDENT>cadd_entry = transcript.get('<STR_LIT>')<EOL>if (cadd_entry and cadd_entry > cadd):<EOL><INDENT>cadd = cadd_entry<EOL><DEDENT><DEDENT>return cadd<EOL>

Check if the cadd phred score is annotated


conservations = {}<EOL>conservations['<STR_LIT>'] = parse_conservation(<EOL>variant,<EOL>'<STR_LIT>'<EOL>)<EOL>conservations['<STR_LIT>'] = parse_conservation(<EOL>variant,<EOL>'<STR_LIT>'<EOL>)<EOL>conservations['<STR_LIT>'] = parse_conservation(<EOL>variant,<EOL>'<STR_LIT>'<EOL>)<EOL>return conservations<EOL>

Parse the conservation predictors

        Args:
            variant(dict): A variant dictionary

        Returns:
            conservations(dict): A dictionary with the conservations


raw_score = variant.INFO.get(info_key)<EOL>conservations = []<EOL>if raw_score:<EOL><INDENT>if isinstance(raw_score, numbers.Number):<EOL><INDENT>raw_score = (raw_score,)<EOL><DEDENT>for score in raw_score:<EOL><INDENT>if score >= CONSERVATION[info_key]['<STR_LIT>']:<EOL><INDENT>conservations.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>conservations.append('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>return conservations<EOL>

Get the conservation prediction

        Args:
            variant(dict): A variant dictionary
            info_key(str)

        Returns:
            conservations(list): List of censervation terms


frequencies = {}<EOL>thousand_genomes_keys = ['<STR_LIT>']<EOL>thousand_genomes_max_keys = ['<STR_LIT>']<EOL>exac_keys = ['<STR_LIT>']<EOL>exac_max_keys = ['<STR_LIT>', '<STR_LIT>']<EOL>gnomad_keys = ['<STR_LIT>', '<STR_LIT>']<EOL>gnomad_max_keys = ['<STR_LIT>', '<STR_LIT>']<EOL>for test_key in thousand_genomes_keys:<EOL><INDENT>thousand_g = parse_frequency(variant, test_key)<EOL>if thousand_g:<EOL><INDENT>frequencies['<STR_LIT>'] = thousand_g<EOL>break<EOL><DEDENT><DEDENT>for test_key in thousand_genomes_max_keys:<EOL><INDENT>thousand_g_max = parse_frequency(variant, test_key)<EOL>if thousand_g_max:<EOL><INDENT>frequencies['<STR_LIT>'] = thousand_g_max<EOL>break<EOL><DEDENT><DEDENT>for test_key in exac_keys:<EOL><INDENT>exac = parse_frequency(variant, test_key)<EOL>if exac:<EOL><INDENT>frequencies['<STR_LIT>'] = exac<EOL>break<EOL><DEDENT><DEDENT>for test_key in exac_max_keys:<EOL><INDENT>exac_max = parse_frequency(variant, test_key)<EOL>if exac_max:<EOL><INDENT>frequencies['<STR_LIT>'] = exac_max<EOL>break<EOL><DEDENT><DEDENT>for test_key in gnomad_keys:<EOL><INDENT>gnomad = parse_frequency(variant, test_key)<EOL>if gnomad:<EOL><INDENT>frequencies['<STR_LIT>'] = gnomad<EOL>break<EOL><DEDENT><DEDENT>for test_key in gnomad_max_keys:<EOL><INDENT>gnomad_max = parse_frequency(variant, test_key)<EOL>if gnomad_max:<EOL><INDENT>frequencies['<STR_LIT>'] = gnomad_max<EOL>break<EOL><DEDENT><DEDENT>if not frequencies:<EOL><INDENT>for transcript in transcripts:<EOL><INDENT>exac = transcript.get('<STR_LIT>')<EOL>exac_max = transcript.get('<STR_LIT>')<EOL>thousand_g = transcript.get('<STR_LIT>')<EOL>thousandg_max = transcript.get('<STR_LIT>')<EOL>gnomad = transcript.get('<STR_LIT>')<EOL>gnomad_max = transcript.get('<STR_LIT>')<EOL>if exac:<EOL><INDENT>frequencies['<STR_LIT>'] = exac<EOL><DEDENT>if exac_max:<EOL><INDENT>frequencies['<STR_LIT>'] = exac_max<EOL><DEDENT>if thousand_g:<EOL><INDENT>frequencies['<STR_LIT>'] = thousand_g<EOL><DEDENT>if thousandg_max:<EOL><INDENT>frequencies['<STR_LIT>'] = thousandg_max<EOL><DEDENT>if gnomad:<EOL><INDENT>frequencies['<STR_LIT>'] = gnomad<EOL><DEDENT>if gnomad_max:<EOL><INDENT>frequencies['<STR_LIT>'] = gnomad_max<EOL><DEDENT><DEDENT><DEDENT>thousand_g_left = parse_frequency(variant, '<STR_LIT>')<EOL>if thousand_g_left:<EOL><INDENT>frequencies['<STR_LIT>'] = thousand_g_left<EOL><DEDENT>thousand_g_right = parse_frequency(variant, '<STR_LIT>')<EOL>if thousand_g_right:<EOL><INDENT>frequencies['<STR_LIT>'] = thousand_g_right<EOL><DEDENT>return frequencies<EOL>

Add the frequencies to a variant

    Frequencies are parsed either directly from keys in info fieds or from the
    transcripts is they are annotated there.

    Args:
        variant(cyvcf2.Variant): A parsed vcf variant
        transcripts(iterable(dict)): Parsed transcripts

    Returns:
        frequencies(dict): A dictionary with the relevant frequencies


raw_annotation = variant.INFO.get(info_key)<EOL>raw_annotation = None if raw_annotation == '<STR_LIT:.>' else raw_annotation<EOL>frequency = float(raw_annotation) if raw_annotation else None<EOL>return frequency<EOL>

Parse any frequency from the info dict

    Args:
        variant(cyvcf2.Variant)
        info_key(str)

    Returns:
        frequency(float): or None if frequency does not exist


frequency_keys = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>]<EOL>sv_frequencies = {}<EOL>for key in frequency_keys:<EOL><INDENT>value = variant.INFO.get(key, <NUM_LIT:0>)<EOL>if '<STR_LIT>' in key:<EOL><INDENT>value = float(value)<EOL><DEDENT>else:<EOL><INDENT>value = int(value)<EOL><DEDENT>if value > <NUM_LIT:0>:<EOL><INDENT>sv_frequencies[key] = value<EOL><DEDENT><DEDENT>return sv_frequencies<EOL>

Parsing of some custom sv frequencies

    These are very specific at the moment, this will hopefully get better over time when the
    field of structural variants is more developed.

    Args:
        variant(cyvcf2.Variant)

    Returns:
        sv_frequencies(dict)


def parse_compounds(compound_info, case_id, variant_type):

<EOL>compounds = []<EOL>if compound_info:<EOL><INDENT>for family_info in compound_info.split('<STR_LIT:U+002C>'):<EOL><INDENT>splitted_entry = family_info.split('<STR_LIT::>')<EOL>if splitted_entry[<NUM_LIT:0>] == case_id:<EOL><INDENT>for compound in splitted_entry[<NUM_LIT:1>].split('<STR_LIT:|>'):<EOL><INDENT>splitted_compound = compound.split('<STR_LIT:>>')<EOL>compound_obj = {}<EOL>compound_name = splitted_compound[<NUM_LIT:0>]<EOL>compound_obj['<STR_LIT>'] = generate_md5_key(compound_name.split('<STR_LIT:_>') +<EOL>[variant_type, case_id])<EOL>try:<EOL><INDENT>compound_score = float(splitted_compound[<NUM_LIT:1>])<EOL><DEDENT>except (TypeError, IndexError):<EOL><INDENT>compound_score = <NUM_LIT:0.0><EOL><DEDENT>compound_obj['<STR_LIT>'] = compound_score<EOL>compound_obj['<STR_LIT>'] = compound_name<EOL>compounds.append(compound_obj)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return compounds<EOL>

Get a list with compounds objects for this variant.

        Arguments:
            compound_info(str): A Variant dictionary
            case_id (str): unique family id
            variant_type(str): 'research' or 'clinical'

        Returns:
            compounds(list(dict)): A list of compounds


genetic_models = []<EOL>if models_info:<EOL><INDENT>for family_info in models_info.split('<STR_LIT:U+002C>'):<EOL><INDENT>splitted_info = family_info.split('<STR_LIT::>')<EOL>if splitted_info[<NUM_LIT:0>] == case_id:<EOL><INDENT>genetic_models = splitted_info[<NUM_LIT:1>].split('<STR_LIT:|>')<EOL><DEDENT><DEDENT><DEDENT>return genetic_models<EOL>

Parse the genetic models entry of a vcf

    Args:
        models_info(str): The raw vcf information
        case_id(str)

    Returns:
        genetic_models(list)


rank_score = None<EOL>if rank_score_entry:<EOL><INDENT>for family_info in rank_score_entry.split('<STR_LIT:U+002C>'):<EOL><INDENT>splitted_info = family_info.split('<STR_LIT::>')<EOL>if case_id == splitted_info[<NUM_LIT:0>]:<EOL><INDENT>rank_score = float(splitted_info[<NUM_LIT:1>])<EOL><DEDENT><DEDENT><DEDENT>return rank_score<EOL>

Parse the rank score

        Args:
            rank_score_entry(str): The raw rank score entry
            case_id(str)

        Returns:
            rank_score(float)


<EOL>genes_to_transcripts = {}<EOL>genes = []<EOL>hgvs_identifier = None<EOL>canonical_transcript = None<EOL>exon = None<EOL>for transcript in transcripts:<EOL><INDENT>hgnc_id = transcript['<STR_LIT>']<EOL>hgnc_symbol = transcript['<STR_LIT>']<EOL>if (transcript['<STR_LIT>'] and transcript.get('<STR_LIT>')):<EOL><INDENT>hgvs_identifier = transcript.get('<STR_LIT>')<EOL>canonical_transcript = transcript['<STR_LIT>']<EOL>exon = transcript['<STR_LIT>']<EOL><DEDENT>if hgnc_id:<EOL><INDENT>if hgnc_id in genes_to_transcripts:<EOL><INDENT>genes_to_transcripts[hgnc_id].append(transcript)<EOL><DEDENT>else:<EOL><INDENT>genes_to_transcripts[hgnc_id] = [transcript]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if hgnc_symbol:<EOL><INDENT>if hgnc_symbol in genes_to_transcripts:<EOL><INDENT>genes_to_transcripts[hgnc_symbol].append(transcript)<EOL><DEDENT>else:<EOL><INDENT>genes_to_transcripts[hgnc_symbol] = [transcript]<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for gene_id in genes_to_transcripts:<EOL><INDENT>gene_transcripts = genes_to_transcripts[gene_id]<EOL>most_severe_consequence = None<EOL>most_severe_rank = float('<STR_LIT>')<EOL>most_severe_transcript = None<EOL>most_severe_region = None<EOL>most_severe_sift = None<EOL>most_severe_polyphen = None<EOL>for transcript in gene_transcripts:<EOL><INDENT>hgnc_id = transcript['<STR_LIT>']<EOL>hgnc_symbol = transcript['<STR_LIT>']<EOL>for consequence in transcript['<STR_LIT>']:<EOL><INDENT>new_rank = SO_TERMS[consequence]['<STR_LIT>']<EOL>if new_rank < most_severe_rank:<EOL><INDENT>most_severe_rank = new_rank<EOL>most_severe_consequence = consequence<EOL>most_severe_transcript = transcript<EOL>most_severe_sift = transcript['<STR_LIT>']<EOL>most_severe_polyphen = transcript['<STR_LIT>']<EOL>most_severe_region = SO_TERMS[consequence]['<STR_LIT>']<EOL><DEDENT><DEDENT><DEDENT>gene = {<EOL>'<STR_LIT>': gene_transcripts,<EOL>'<STR_LIT>': most_severe_transcript,<EOL>'<STR_LIT>': most_severe_consequence,<EOL>'<STR_LIT>': most_severe_sift,<EOL>'<STR_LIT>': most_severe_polyphen,<EOL>'<STR_LIT>': hgnc_id,<EOL>'<STR_LIT>': hgnc_symbol,<EOL>'<STR_LIT>': most_severe_region,<EOL>'<STR_LIT>': transcript['<STR_LIT>'],<EOL>'<STR_LIT>': transcript['<STR_LIT>'],<EOL>'<STR_LIT>': transcript['<STR_LIT>'],<EOL>}<EOL>genes.append(gene)    <EOL><DEDENT>return genes<EOL>

Parse transcript information and get the gene information from there.

    Use hgnc_id as identifier for genes and ensembl transcript id to identify transcripts

    Args:
        transcripts(iterable(dict))

    Returns:
      genes (list(dict)): A list with dictionaries that represents genes


for entry in raw_transcripts:<EOL><INDENT>transcript = {}<EOL>functional_annotations = entry.get('<STR_LIT>', '<STR_LIT>').split('<STR_LIT:&>')<EOL>transcript['<STR_LIT>'] = functional_annotations<EOL>transcript_id = entry.get('<STR_LIT>', '<STR_LIT>').split('<STR_LIT::>')[<NUM_LIT:0>]<EOL>transcript['<STR_LIT>'] = transcript_id<EOL>hgnc_id = entry.get('<STR_LIT>')<EOL>if hgnc_id:<EOL><INDENT>hgnc_id = hgnc_id.split('<STR_LIT::>')[-<NUM_LIT:1>]<EOL>transcript['<STR_LIT>'] = int(hgnc_id)<EOL><DEDENT>else:<EOL><INDENT>transcript['<STR_LIT>'] = None<EOL><DEDENT>hgnc_symbol = entry.get('<STR_LIT>')<EOL>if hgnc_symbol:<EOL><INDENT>transcript['<STR_LIT>'] = hgnc_symbol<EOL><DEDENT>else:<EOL><INDENT>transcript['<STR_LIT>'] = None<EOL><DEDENT>transcript['<STR_LIT>'] = entry.get('<STR_LIT>')<EOL>polyphen_prediction = entry.get('<STR_LIT>')<EOL>prediction_term = '<STR_LIT>'<EOL>if polyphen_prediction:<EOL><INDENT>prediction_term = polyphen_prediction.split('<STR_LIT:(>')[<NUM_LIT:0>]<EOL><DEDENT>transcript['<STR_LIT>'] = prediction_term<EOL>sift_prediction = entry.get('<STR_LIT>')<EOL>prediction_term = '<STR_LIT>'<EOL>if not sift_prediction:<EOL><INDENT>sift_prediction = entry.get('<STR_LIT>')<EOL><DEDENT>if sift_prediction:<EOL><INDENT>prediction_term = sift_prediction.split('<STR_LIT:(>')[<NUM_LIT:0>]<EOL><DEDENT>transcript['<STR_LIT>'] = prediction_term<EOL>transcript['<STR_LIT>'] = entry.get('<STR_LIT>') or '<STR_LIT>'<EOL>if entry.get('<STR_LIT>', None):<EOL><INDENT>pfam_domains = entry['<STR_LIT>'].split('<STR_LIT:&>')<EOL>for annotation in pfam_domains:<EOL><INDENT>annotation = annotation.split('<STR_LIT::>')<EOL>domain_name = annotation[<NUM_LIT:0>]<EOL>domain_id = annotation[<NUM_LIT:1>]<EOL>if domain_name == '<STR_LIT>':<EOL><INDENT>transcript['<STR_LIT>'] = domain_id<EOL><DEDENT>elif domain_name == '<STR_LIT>':<EOL><INDENT>transcript['<STR_LIT>'] = domain_id<EOL><DEDENT>elif domain_name == '<STR_LIT>':<EOL><INDENT>transcript['<STR_LIT>'] = domain_id<EOL><DEDENT><DEDENT><DEDENT>coding_sequence_entry = entry.get('<STR_LIT>', '<STR_LIT>').split('<STR_LIT::>')<EOL>protein_sequence_entry = entry.get('<STR_LIT>', '<STR_LIT>').split('<STR_LIT::>')<EOL>coding_sequence_name = None<EOL>if len(coding_sequence_entry) > <NUM_LIT:1>:<EOL><INDENT>coding_sequence_name = coding_sequence_entry[-<NUM_LIT:1>]<EOL><DEDENT>transcript['<STR_LIT>'] = coding_sequence_name<EOL>protein_sequence_name = None<EOL>if len(protein_sequence_entry) > <NUM_LIT:1>:<EOL><INDENT>protein_sequence_name = protein_sequence_entry[-<NUM_LIT:1>]<EOL><DEDENT>transcript['<STR_LIT>'] = protein_sequence_name<EOL>transcript['<STR_LIT>'] = entry.get('<STR_LIT>')<EOL>transcript['<STR_LIT>'] = entry.get('<STR_LIT>')<EOL>transcript['<STR_LIT>'] = entry.get('<STR_LIT>')<EOL>if entry.get('<STR_LIT>'):<EOL><INDENT>if entry['<STR_LIT>'] == '<STR_LIT:1>':<EOL><INDENT>transcript['<STR_LIT>'] = '<STR_LIT:+>'<EOL><DEDENT>elif entry['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>transcript['<STR_LIT>'] = '<STR_LIT:->'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>transcript['<STR_LIT>'] = None<EOL><DEDENT>functional = []<EOL>regional = []<EOL>for annotation in functional_annotations:<EOL><INDENT>functional.append(annotation)<EOL>regional.append(SO_TERMS[annotation]['<STR_LIT>'])<EOL><DEDENT>transcript['<STR_LIT>'] = functional<EOL>transcript['<STR_LIT>'] = regional<EOL>transcript['<STR_LIT>'] = (entry.get('<STR_LIT>') == '<STR_LIT>')<EOL>cadd_phred = entry.get('<STR_LIT>')<EOL>if cadd_phred:<EOL><INDENT>transcript['<STR_LIT>'] = float(cadd_phred)<EOL><DEDENT>thousandg_freqs = []<EOL>gnomad_freqs = []<EOL>try:<EOL><INDENT>for key in entry:<EOL><INDENT>if not key.endswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>value = entry[key]<EOL>if not value:<EOL><INDENT>continue<EOL><DEDENT>if (key == '<STR_LIT>' or key == '<STR_LIT>'):<EOL><INDENT>transcript['<STR_LIT>'] = float(value)<EOL>continue<EOL><DEDENT>if key == '<STR_LIT>':<EOL><INDENT>transcript['<STR_LIT>'] = float(value)<EOL>continue<EOL><DEDENT>if key == '<STR_LIT>':<EOL><INDENT>transcript['<STR_LIT>'] = float(value)<EOL>transcript['<STR_LIT>'] = float(value)<EOL>continue<EOL><DEDENT>if '<STR_LIT>' in key:<EOL><INDENT>gnomad_freqs.append(float(value))<EOL><DEDENT>else:<EOL><INDENT>thousandg_freqs.append(float(value))<EOL><DEDENT><DEDENT>if thousandg_freqs:<EOL><INDENT>transcript['<STR_LIT>'] = max(thousandg_freqs)<EOL><DEDENT>if gnomad_freqs:<EOL><INDENT>transcript['<STR_LIT>'] = max(gnomad_freqs)<EOL><DEDENT><DEDENT>except Exception as err:<EOL><INDENT>LOG.debug("<STR_LIT>")<EOL>LOG.debug("<STR_LIT>")<EOL><DEDENT>clinsig = entry.get('<STR_LIT>')<EOL>if clinsig:<EOL><INDENT>transcript['<STR_LIT>'] = clinsig.split('<STR_LIT:&>')<EOL><DEDENT>transcript['<STR_LIT>'] = []<EOL>transcript['<STR_LIT>'] = []<EOL>variant_ids = entry.get('<STR_LIT>')<EOL>if variant_ids:<EOL><INDENT>for variant_id in variant_ids.split('<STR_LIT:&>'):<EOL><INDENT>if variant_id.startswith('<STR_LIT>'):<EOL><INDENT>transcript['<STR_LIT>'].append(variant_id)<EOL><DEDENT>elif variant_id.startswith('<STR_LIT>'):<EOL><INDENT>transcript['<STR_LIT>'].append(int(variant_id[<NUM_LIT:4>:]))<EOL><DEDENT><DEDENT><DEDENT>yield transcript<EOL><DEDENT>

Parse transcript information from VCF variants

    Args:
        raw_transcripts(iterable(dict)): An iterable with raw transcript
                                         information

    Yields:
        transcript(dict) A dictionary with transcript information


peddy_ped = []<EOL>header = []<EOL>for i,line in enumerate(lines):<EOL><INDENT>line = line.rstrip()<EOL>if i == <NUM_LIT:0>:<EOL><INDENT>header = line.lstrip('<STR_LIT:#>').split('<STR_LIT:\t>')<EOL><DEDENT>else:<EOL><INDENT>ind_info = dict(zip(header, line.split('<STR_LIT:\t>')))<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>peddy_ped.append(ind_info)<EOL><DEDENT><DEDENT>return peddy_ped<EOL>

Parse a peddy.ped file

    Args:
        lines(iterable(str))

    Returns:
        peddy_ped(list(dict))


ped_check = []<EOL>header = []<EOL>for i,line in enumerate(lines):<EOL><INDENT>line = line.rstrip()<EOL>if i == <NUM_LIT:0>:<EOL><INDENT>header = line.lstrip('<STR_LIT:#>').split('<STR_LIT:U+002C>')<EOL><DEDENT>else:<EOL><INDENT>pair_info = dict(zip(header, line.split('<STR_LIT:U+002C>')))<EOL>pair_info['<STR_LIT>'] = convert_number(pair_info['<STR_LIT>'])<EOL>pair_info['<STR_LIT>'] = convert_number(pair_info['<STR_LIT>'])<EOL>pair_info['<STR_LIT>'] = convert_number(pair_info['<STR_LIT>'])<EOL>pair_info['<STR_LIT>'] = convert_number(pair_info['<STR_LIT>'])<EOL>pair_info['<STR_LIT:n>'] = convert_number(pair_info['<STR_LIT:n>'])<EOL>pair_info['<STR_LIT>'] = convert_number(pair_info['<STR_LIT>'])<EOL>pair_info['<STR_LIT>'] = convert_number(pair_info['<STR_LIT>'])<EOL>pair_info['<STR_LIT>'] = convert_number(pair_info['<STR_LIT>'])<EOL>pair_info['<STR_LIT>'] = convert_number(pair_info['<STR_LIT>'])<EOL>pair_info['<STR_LIT>'] = make_bool(pair_info.get('<STR_LIT>'))<EOL>pair_info['<STR_LIT>'] = make_bool(pair_info.get('<STR_LIT>'))<EOL>pair_info['<STR_LIT>'] = make_bool(pair_info.get('<STR_LIT>'))<EOL>pair_info['<STR_LIT>'] = make_bool(pair_info.get('<STR_LIT>'))<EOL>ped_check.append(pair_info)<EOL><DEDENT><DEDENT>return ped_check<EOL>

Parse a .ped_check.csv file

    Args:
        lines(iterable(str))

    Returns:
        ped_check(list(dict))


sex_check = []<EOL>header = []<EOL>for i,line in enumerate(lines):<EOL><INDENT>line = line.rstrip()<EOL>if i == <NUM_LIT:0>:<EOL><INDENT>header = line.lstrip('<STR_LIT:#>').split('<STR_LIT:U+002C>')<EOL><DEDENT>else:<EOL><INDENT>ind_info = dict(zip(header, line.split('<STR_LIT:U+002C>')))<EOL>ind_info['<STR_LIT:error>'] = make_bool(ind_info.get('<STR_LIT:error>'))<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>ind_info['<STR_LIT>'] = convert_number(ind_info['<STR_LIT>'])<EOL>sex_check.append(ind_info)<EOL><DEDENT><DEDENT>return sex_check<EOL>

Parse a .ped_check.csv file

    Args:
        lines(iterable(str))

    Returns:
        sex_check(list(dict))


def get_panel_info(panel_lines=None, panel_id=None, institute=None, version=None, date=None,<EOL>display_name=None):

panel_info = {<EOL>'<STR_LIT>': panel_id,<EOL>'<STR_LIT>': institute,<EOL>'<STR_LIT:version>': version,<EOL>'<STR_LIT:date>': date,<EOL>'<STR_LIT>': display_name,<EOL>}<EOL>if panel_lines:<EOL><INDENT>for line in panel_lines:<EOL><INDENT>line = line.rstrip()<EOL>if not line.startswith('<STR_LIT>'):<EOL><INDENT>break<EOL><DEDENT>info = line[<NUM_LIT:2>:].split('<STR_LIT:=>')<EOL>field = info[<NUM_LIT:0>]<EOL>value = info[<NUM_LIT:1>]<EOL>if not panel_info.get(field):<EOL><INDENT>panel_info[field] = value<EOL><DEDENT><DEDENT><DEDENT>panel_info['<STR_LIT:date>'] = get_date(panel_info['<STR_LIT:date>'])<EOL>return panel_info<EOL>

Parse metadata for a gene panel

    For historical reasons it is possible to include all information about a gene panel in the
    header of a panel file. This function parses the header.

    Args:
        panel_lines(iterable(str))

    Returns:
        panel_info(dict): Dictionary with panel information


gene = {}<EOL>identifier = None<EOL>hgnc_id = None<EOL>try:<EOL><INDENT>if '<STR_LIT>' in gene_info:<EOL><INDENT>hgnc_id = int(gene_info['<STR_LIT>'])<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>hgnc_id = int(gene_info['<STR_LIT>'])<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>hgnc_id = int(gene_info['<STR_LIT>'])<EOL><DEDENT><DEDENT>except ValueError as e:<EOL><INDENT>raise SyntaxError("<STR_LIT>".format(hgnc_id))<EOL><DEDENT>gene['<STR_LIT>'] = hgnc_id<EOL>identifier = hgnc_id<EOL>hgnc_symbol = None<EOL>if '<STR_LIT>' in gene_info:<EOL><INDENT>hgnc_symbol = gene_info['<STR_LIT>']<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>hgnc_symbol = gene_info['<STR_LIT>']<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>hgnc_symbol = gene_info['<STR_LIT>']<EOL><DEDENT>gene['<STR_LIT>'] = hgnc_symbol<EOL>if not identifier:<EOL><INDENT>if hgnc_symbol:<EOL><INDENT>identifier = hgnc_symbol<EOL><DEDENT>else:<EOL><INDENT>raise SyntaxError("<STR_LIT>")<EOL><DEDENT><DEDENT>gene['<STR_LIT>'] = identifier<EOL>transcripts = "<STR_LIT>"<EOL>if '<STR_LIT>' in gene_info:<EOL><INDENT>transcripts = gene_info['<STR_LIT>']<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>transcripts = gene_info['<STR_LIT>']<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>transcripts = gene_info['<STR_LIT>']<EOL><DEDENT>gene['<STR_LIT>'] = [<EOL>transcript.strip() for transcript in<EOL>transcripts.split('<STR_LIT:U+002C>') if transcript<EOL>]<EOL>models = "<STR_LIT>"<EOL>if '<STR_LIT>' in gene_info:<EOL><INDENT>models = gene_info['<STR_LIT>']<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>models = gene_info['<STR_LIT>']<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>models = gene_info['<STR_LIT>']<EOL><DEDENT>elif '<STR_LIT>' in gene_info:<EOL><INDENT>models = gene_info['<STR_LIT>']<EOL><DEDENT>gene['<STR_LIT>'] = [<EOL>model.strip() for model in models.split('<STR_LIT:U+002C>')<EOL>if model.strip() in VALID_MODELS<EOL>]<EOL>gene['<STR_LIT>'] = True if gene_info.get('<STR_LIT>') else False<EOL>gene['<STR_LIT>'] = True if gene_info.get('<STR_LIT>') else False<EOL>gene['<STR_LIT>'] = gene_info.get('<STR_LIT>')<EOL>return gene<EOL>

Parse a gene line with information from a panel file

        Args:
            gene_info(dict): dictionary with gene info

        Returns:
            gene(dict): A dictionary with the gene information
                {
                'hgnc_id': int,
                'hgnc_symbol': str,
                'disease_associated_transcripts': list(str),
                'inheritance_models': list(str),
                'mosaicism': bool,
                'reduced_penetrance': bool,
                'database_entry_version': str,
                }


genes = []<EOL>header = []<EOL>hgnc_identifiers = set()<EOL>delimiter = '<STR_LIT:\t>'<EOL>delimiters = ['<STR_LIT:\t>', '<STR_LIT:U+0020>', '<STR_LIT:;>']<EOL>for i,line in enumerate(gene_lines):<EOL><INDENT>line = line.rstrip()<EOL>if not len(line) > <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if line.startswith('<STR_LIT:#>'):<EOL><INDENT>if not line.startswith('<STR_LIT>'):<EOL><INDENT>line_length = <NUM_LIT:0><EOL>delimiter = None<EOL>for alt in delimiters:<EOL><INDENT>head_line = line.split(alt)<EOL>if len(head_line) > line_length:<EOL><INDENT>line_length = len(head_line)<EOL>delimiter = alt<EOL><DEDENT><DEDENT>header = [word.lower() for word in line[<NUM_LIT:1>:].split(delimiter)]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if i == <NUM_LIT:0>:<EOL><INDENT>line_length = <NUM_LIT:0><EOL>for alt in delimiters:<EOL><INDENT>head_line = line.split(alt)<EOL>if len(head_line) > line_length:<EOL><INDENT>line_length = len(head_line)<EOL>delimiter = alt<EOL><DEDENT><DEDENT>if ('<STR_LIT>' in line or '<STR_LIT>' in line):<EOL><INDENT>header = [word.lower() for word in line.split(delimiter)]<EOL>continue<EOL><DEDENT>if line.split(delimiter)[<NUM_LIT:0>].isdigit():<EOL><INDENT>header = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>header = ['<STR_LIT>']<EOL><DEDENT><DEDENT>splitted_line = line.split(delimiter)<EOL>gene_info = dict(zip(header, splitted_line))<EOL>info_found = False<EOL>for key in gene_info:<EOL><INDENT>if gene_info[key]:<EOL><INDENT>info_found = True<EOL>break<EOL><DEDENT><DEDENT>if not info_found:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>gene = parse_gene(gene_info)<EOL><DEDENT>except Exception as e:<EOL><INDENT>LOG.warning(e)<EOL>raise SyntaxError("<STR_LIT>".format(i + <NUM_LIT:1>))<EOL><DEDENT>identifier = gene.pop('<STR_LIT>')<EOL>if not identifier in hgnc_identifiers:<EOL><INDENT>hgnc_identifiers.add(identifier)<EOL>genes.append(gene)<EOL><DEDENT><DEDENT><DEDENT>return genes<EOL>

Parse a file with genes and return the hgnc ids

    Args:
        gene_lines(iterable(str)): Stream with genes

    Returns:
        genes(list(dict)): Dictionaries with relevant gene info


gene_info = {}<EOL>confidence_level = app_gene['<STR_LIT>']<EOL>if not confidence_level == '<STR_LIT>':<EOL><INDENT>return gene_info<EOL><DEDENT>hgnc_symbol = app_gene['<STR_LIT>']<EOL>hgnc_ids = get_correct_ids(hgnc_symbol, hgnc_map)<EOL>if not hgnc_ids:<EOL><INDENT>LOG.warning("<STR_LIT>", hgnc_symbol)<EOL>return gene_info<EOL><DEDENT>if len(hgnc_ids) > <NUM_LIT:1>:<EOL><INDENT>LOG.warning("<STR_LIT>", hgnc_symbol)<EOL><DEDENT>gene_info['<STR_LIT>'] = hgnc_symbol<EOL>for hgnc_id in hgnc_ids:<EOL><INDENT>gene_info['<STR_LIT>'] = hgnc_id<EOL><DEDENT>gene_info['<STR_LIT>'] = INCOMPLETE_PENETRANCE_MAP.get(app_gene['<STR_LIT>'])<EOL>inheritance_models = []<EOL>for model in MODELS_MAP.get(app_gene['<STR_LIT>'],[]):<EOL><INDENT>inheritance_models.append(model)<EOL><DEDENT>gene_info['<STR_LIT>'] = inheritance_models<EOL>return gene_info<EOL>

Parse a panel app formated gene

    Args:
        app_gene(dict): Dict with panel app info
        hgnc_map(dict): Map from hgnc_symbol to hgnc_id

    Returns:
        gene_info(dict): Scout infromation


def parse_panel_app_panel(panel_info, hgnc_map, institute='<STR_LIT>', panel_type='<STR_LIT>'):

date_format = "<STR_LIT>"<EOL>gene_panel = {}<EOL>gene_panel['<STR_LIT:version>'] = float(panel_info['<STR_LIT:version>'])<EOL>gene_panel['<STR_LIT:date>'] = get_date(panel_info['<STR_LIT>'][:-<NUM_LIT:1>], date_format=date_format)<EOL>gene_panel['<STR_LIT>'] = panel_info['<STR_LIT>']<EOL>gene_panel['<STR_LIT>'] = institute<EOL>gene_panel['<STR_LIT>'] = panel_type<EOL>LOG.info("<STR_LIT>", gene_panel['<STR_LIT>'])<EOL>gene_panel['<STR_LIT>'] = []<EOL>nr_low_confidence = <NUM_LIT:1><EOL>nr_genes = <NUM_LIT:0><EOL>for nr_genes, gene in enumerate(panel_info['<STR_LIT>'],<NUM_LIT:1>):<EOL><INDENT>gene_info = parse_panel_app_gene(gene, hgnc_map)<EOL>if not gene_info:<EOL><INDENT>nr_low_confidence += <NUM_LIT:1><EOL>continue<EOL><DEDENT>gene_panel['<STR_LIT>'].append(gene_info)<EOL><DEDENT>LOG.info("<STR_LIT>", nr_genes)<EOL>LOG.info("<STR_LIT>", nr_low_confidence)<EOL>return gene_panel<EOL>

Parse a PanelApp panel

    Args:
        panel_info(dict)
        hgnc_map(dict): Map from symbol to hgnc ids
        institute(str)
        panel_type(str)

    Returns:
        gene_panel(dict)


def get_omim_panel_genes(genemap2_lines, mim2gene_lines, alias_genes):

parsed_genes = get_mim_genes(genemap2_lines, mim2gene_lines)<EOL>STATUS_TO_ADD = set(['<STR_LIT>', '<STR_LIT>'])<EOL>for hgnc_symbol in parsed_genes:<EOL><INDENT>try:<EOL><INDENT>gene = parsed_genes[hgnc_symbol]<EOL>keep = False<EOL>for phenotype_info in gene.get('<STR_LIT>',[]):<EOL><INDENT>if phenotype_info['<STR_LIT:status>'] in STATUS_TO_ADD:<EOL><INDENT>keep = True<EOL>break<EOL><DEDENT><DEDENT>if keep:<EOL><INDENT>hgnc_id_info = alias_genes.get(hgnc_symbol)<EOL>if not hgnc_id_info:<EOL><INDENT>for symbol in gene.get('<STR_LIT>', []):<EOL><INDENT>if symbol in alias_genes:<EOL><INDENT>hgnc_id_info = alias_genes[symbol]<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if hgnc_id_info:<EOL><INDENT>yield {<EOL>'<STR_LIT>': hgnc_id_info['<STR_LIT:true>'],<EOL>'<STR_LIT>': hgnc_symbol,<EOL>}<EOL><DEDENT>else:<EOL><INDENT>LOG.warning("<STR_LIT>", hgnc_symbol)<EOL><DEDENT><DEDENT><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

Return all genes that should be included in the OMIM-AUTO panel
    Return the hgnc symbols

    Genes that have at least one 'established' or 'provisional' phenotype connection
    are included in the gene panel

    Args:
        genemap2_lines(iterable)
        mim2gene_lines(iterable)
        alias_genes(dict): A dictionary that maps hgnc_symbol to hgnc_id

    Yields:
        hgnc_symbol(str)


variant_ids = get_submission_variants(form_fields) <EOL>variant_objs = get_objects_from_form(variant_ids, form_fields, '<STR_LIT>')<EOL>casedata_objs = get_objects_from_form(variant_ids, form_fields, '<STR_LIT>')<EOL>return (variant_objs, casedata_objs)<EOL>

Creates a list of submission objects (variant and case-data) from the clinvar submission form in blueprints/variants/clinvar.html.

        Args:
             form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and CASEDATA_HEADER

        Returns:
             submission_objects(list): a list of variant and case-data submission objects, ready to be included in the clinvar database collection


def get_objects_from_form(variant_ids, form_fields, object_type):

submission_fields = []<EOL>if object_type == '<STR_LIT>':<EOL><INDENT>submission_fields = CLINVAR_HEADER<EOL><DEDENT>else: <EOL><INDENT>submission_fields = CASEDATA_HEADER<EOL><DEDENT>submission_objects = []<EOL>for variant_id in variant_ids: <EOL><INDENT>subm_obj = {} <EOL>if object_type == '<STR_LIT>' and '<STR_LIT>'+variant_id not in form_fields:<EOL><INDENT>continue<EOL><DEDENT>subm_obj['<STR_LIT>'] = object_type<EOL>subm_obj['<STR_LIT>'] = form_fields.get('<STR_LIT>')<EOL>subm_obj['<STR_LIT>'] = form_fields.get('<STR_LIT>'+variant_id)<EOL>for key, values in submission_fields.items(): <EOL><INDENT>field_value = form_fields.get(key+'<STR_LIT:@>'+variant_id)<EOL>if field_value and not field_value == '<STR_LIT:->':<EOL><INDENT>if key == '<STR_LIT>': <EOL><INDENT>refseq_raw = field_value.split('<STR_LIT:|>')<EOL>subm_obj['<STR_LIT>'] = refseq_raw[<NUM_LIT:0>]<EOL>subm_obj['<STR_LIT>'] = refseq_raw[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>subm_obj[key] = field_value<EOL><DEDENT><DEDENT><DEDENT>if object_type == '<STR_LIT>':<EOL><INDENT>subm_obj['<STR_LIT>'] = str(subm_obj['<STR_LIT>']) + '<STR_LIT:_>' + variant_id + '<STR_LIT:_>' + str(subm_obj['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>subm_obj['<STR_LIT>'] = str(subm_obj['<STR_LIT>']) + '<STR_LIT:_>' + variant_id<EOL><DEDENT>submission_objects.append(subm_obj)<EOL><DEDENT>return submission_objects<EOL>

Extract the objects to be saved in the clinvar database collection.
       object_type param specifies if these objects are variant or casedata objects

       Args:
        variant_ids(list): list of database variant ids
        form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and CASEDATA_HEADER
        object_type(str): either 'variant' or 'case_data'

       Returns:
        submission_objects(list): list of submission objects of either type 'variant' or 'casedata'


clinvars = []<EOL>if '<STR_LIT>' in form_fields:<EOL><INDENT>for field, value in form_fields.items():<EOL><INDENT>if field.startswith('<STR_LIT>'):<EOL><INDENT>clinvars.append(form_fields[field].replace('<STR_LIT>','<STR_LIT>'))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>clinvars = [form_fields['<STR_LIT>']] <EOL><DEDENT>return clinvars<EOL>

Extracts a list of variant ids from the clinvar submission form in blueprints/variants/clinvar.html (creation of a new clinvar submission).

        Args:
             form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and CASEDATA_HEADER

        Returns:
             clinvars: A list of variant IDs


complete_header = {} <EOL>custom_header = {}   <EOL>if csv_type == '<STR_LIT>' :<EOL><INDENT>complete_header = CLINVAR_HEADER<EOL><DEDENT>else:<EOL><INDENT>complete_header = CASEDATA_HEADER<EOL><DEDENT>for header_key, header_value in complete_header.items(): <EOL><INDENT>for clinvar_obj in submission_objs: <EOL><INDENT>for key, value in clinvar_obj.items(): <EOL><INDENT>if not header_key in custom_header and header_key == key: <EOL><INDENT>custom_header[header_key] = header_value<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return custom_header<EOL>

Determine which fields to include in csv header by checking a list of submission objects

        Args:
            submission_objs(list): a list of objects (variants or casedata) to include in a csv file
            csv_type(str) : 'variant_data' or 'case_data'

        Returns:
            custom_header(dict): A dictionary with the fields required in the csv header. Keys and values are specified in CLINVAR_HEADER and CASEDATA_HEADER


submission_lines = []<EOL>for submission_obj in submission_objs: <EOL><INDENT>csv_line = []<EOL>for header_key, header_value in submission_header.items(): <EOL><INDENT>if header_key in submission_obj: <EOL><INDENT>csv_line.append('<STR_LIT:">'+submission_obj.get(header_key)+'<STR_LIT:">')<EOL><DEDENT>else: <EOL><INDENT>csv_line.append('<STR_LIT>')<EOL><DEDENT><DEDENT>submission_lines.append('<STR_LIT:U+002C>'.join(csv_line))<EOL><DEDENT>return submission_lines<EOL>

Create the lines to include in a Clinvar submission csv file from a list of submission objects and a custom document header

        Args:
            submission_objs(list): a list of objects (variants or casedata) to include in a csv file
            submission_header(dict) : as in constants CLINVAR_HEADER and CASEDATA_HEADER, but with required fields only

        Returns:
            submission_lines(list) a list of strings, each string represents a line of the clinvar csv file to be doenloaded


cytobands = {}<EOL>for line in lines:<EOL><INDENT>line = line.rstrip()<EOL>splitted_line = line.split('<STR_LIT:\t>')<EOL>chrom = splitted_line[<NUM_LIT:0>].lstrip('<STR_LIT>')<EOL>start = int(splitted_line[<NUM_LIT:1>])<EOL>stop = int(splitted_line[<NUM_LIT:2>])<EOL>name = splitted_line[<NUM_LIT:3>]<EOL>if chrom in cytobands:<EOL><INDENT>cytobands[chrom][start:stop] = name<EOL><DEDENT>else:<EOL><INDENT>new_tree = intervaltree.IntervalTree()<EOL>new_tree[start:stop] = name<EOL>cytobands[chrom] = new_tree<EOL><DEDENT><DEDENT>return cytobands<EOL>

Parse iterable with cytoband coordinates

    Args:
        lines(iterable): Strings on format "chr1\t2300000\t5400000\tp36.32\tgpos25"

    Returns:
        cytobands(dict): Dictionary with chromosome names as keys and
                         interval trees as values


lines = get_file_handle(infile)<EOL>cytobands = parse_cytoband(lines)<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>intervals = cytobands['<STR_LIT:1>'][<NUM_LIT:2>]<EOL>for interval in intervals:<EOL><INDENT>print(interval)<EOL>print(interval.begin)<EOL>print(interval.end)<EOL>print(interval.data)<EOL><DEDENT>print(cytobands['<STR_LIT:1>'][<NUM_LIT:2>])<EOL>print("<STR_LIT>")<EOL>print(cytobands['<STR_LIT>'][<NUM_LIT>])<EOL>print("<STR_LIT>")<EOL>print(cytobands['<STR_LIT:X>'][<NUM_LIT>:<NUM_LIT>])<EOL>


omim_info = dict(zip(header, line.split('<STR_LIT:\t>')))<EOL>return omim_info<EOL>


LOG.info("<STR_LIT>")<EOL>header = []<EOL>for i,line in enumerate(lines):<EOL><INDENT>line = line.rstrip()<EOL>if line.startswith('<STR_LIT:#>'):<EOL><INDENT>if i < <NUM_LIT:10>:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>header = line[<NUM_LIT:2>:].split('<STR_LIT:\t>')<EOL><DEDENT><DEDENT>continue<EOL><DEDENT>if len(line) < <NUM_LIT:5>:<EOL><INDENT>continue<EOL><DEDENT>parsed_entry = parse_omim_line(line, header)<EOL>parsed_entry['<STR_LIT>'] = int(parsed_entry['<STR_LIT>'])<EOL>parsed_entry['<STR_LIT>'] = line<EOL>hgnc_symbol = parsed_entry.get("<STR_LIT>")<EOL>gene_symbols = []<EOL>if parsed_entry.get('<STR_LIT>'):<EOL><INDENT>gene_symbols = [symbol.strip() for symbol in parsed_entry['<STR_LIT>'].split('<STR_LIT:U+002C>')]<EOL><DEDENT>parsed_entry['<STR_LIT>'] = gene_symbols<EOL>if not hgnc_symbol and gene_symbols:<EOL><INDENT>hgnc_symbol = gene_symbols[<NUM_LIT:0>]<EOL><DEDENT>parsed_entry['<STR_LIT>'] = hgnc_symbol<EOL>gene_inheritance = set()<EOL>parsed_phenotypes = []<EOL>for phenotype_info in parsed_entry.get('<STR_LIT>', '<STR_LIT>').split('<STR_LIT:;>'):<EOL><INDENT>if not phenotype_info:<EOL><INDENT>continue<EOL><DEDENT>phenotype_info = phenotype_info.lstrip()<EOL>phenotype_status = OMIM_STATUS_MAP.get(phenotype_info[<NUM_LIT:0>], '<STR_LIT>')<EOL>if phenotype_status == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>phenotype_description = "<STR_LIT>"<EOL>splitted_info = phenotype_info.split('<STR_LIT:U+002C>')<EOL>for i, text in enumerate(splitted_info):<EOL><INDENT>match = entry_pattern.search(text)<EOL>if not match:<EOL><INDENT>phenotype_description += text<EOL><DEDENT>else:<EOL><INDENT>mimnr_match = mimnr_pattern.search(phenotype_info)<EOL>if mimnr_match:<EOL><INDENT>phenotype_mim = int(mimnr_match.group())<EOL><DEDENT>else:<EOL><INDENT>phenotype_mim = parsed_entry['<STR_LIT>']<EOL>phenotype_description += text[:-<NUM_LIT:4>]<EOL><DEDENT>break<EOL><DEDENT><DEDENT>inheritance = set()<EOL>inheritance_text = '<STR_LIT:U+002C>'.join(splitted_info[i:])<EOL>for term in mim_inheritance_terms:<EOL><INDENT>if term in inheritance_text:<EOL><INDENT>inheritance.add(TERMS_MAPPER[term])<EOL>gene_inheritance.add(TERMS_MAPPER[term])<EOL><DEDENT><DEDENT>parsed_phenotypes.append(<EOL>{<EOL>'<STR_LIT>':phenotype_mim, <EOL>'<STR_LIT>': inheritance,<EOL>'<STR_LIT:description>': phenotype_description.strip('<STR_LIT>'),<EOL>'<STR_LIT:status>': phenotype_status,<EOL>}<EOL>)<EOL><DEDENT>parsed_entry['<STR_LIT>'] = parsed_phenotypes<EOL>parsed_entry['<STR_LIT>'] = gene_inheritance<EOL>yield parsed_entry<EOL><DEDENT>

Parse the omim source file called genemap2.txt

    Explanation of Phenotype field:
    Brackets, "[ ]", indicate "nondiseases," mainly genetic variations that
    lead to apparently abnormal laboratory test values.

    Braces, "{ }", indicate mutations that contribute to susceptibility to
    multifactorial disorders (e.g., diabetes, asthma) or to susceptibility
    to infection (e.g., malaria).

    A question mark, "?", before the phenotype name indicates that the
    relationship between the phenotype and gene is provisional.
    More details about this relationship are provided in the comment
    field of the map and in the gene and phenotype OMIM entries.

    The number in parentheses after the name of each disorder indicates
    the following:
        (1) the disorder was positioned by mapping of the wildtype gene;
        (2) the disease phenotype itself was mapped;
        (3) the molecular basis of the disorder is known;
        (4) the disorder is a chromosome deletion or duplication syndrome.

    Args:
        lines(iterable(str))

    Yields:
        parsed_entry(dict)


LOG.info("<STR_LIT>")<EOL>header = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>for i, line in enumerate(lines):<EOL><INDENT>if line.startswith('<STR_LIT:#>'):<EOL><INDENT>continue<EOL><DEDENT>if not len(line) > <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>line = line.rstrip()<EOL>parsed_entry = parse_omim_line(line, header)<EOL>parsed_entry['<STR_LIT>'] = int(parsed_entry['<STR_LIT>'])<EOL>parsed_entry['<STR_LIT>'] = line<EOL>if '<STR_LIT>' in parsed_entry:<EOL><INDENT>parsed_entry['<STR_LIT>'] = parsed_entry['<STR_LIT>']<EOL><DEDENT>if parsed_entry.get('<STR_LIT>'):<EOL><INDENT>parsed_entry['<STR_LIT>'] = int(parsed_entry['<STR_LIT>'])<EOL><DEDENT>if parsed_entry.get('<STR_LIT>'):<EOL><INDENT>ensembl_info = parsed_entry['<STR_LIT>'].split('<STR_LIT:U+002C>')<EOL>parsed_entry['<STR_LIT>'] = ensembl_info[<NUM_LIT:0>].strip()<EOL>if len(ensembl_info) > <NUM_LIT:1>:<EOL><INDENT>parsed_entry['<STR_LIT>'] = ensembl_info[<NUM_LIT:1>].strip()<EOL><DEDENT><DEDENT>yield parsed_entry<EOL><DEDENT>

Parse the file called mim2gene

    This file describes what type(s) the different mim numbers have.
    The different entry types are: 'gene', 'gene/phenotype', 'moved/removed',
    'phenotype', 'predominantly phenotypes'
    Where:
        gene: Is a gene entry
        gene/phenotype: This entry describes both a phenotype and a gene
        moved/removed: No explanation needed
        phenotype: Describes a phenotype
        predominantly phenotype: Not clearly established (probably phenotype)

    Args:
        lines(iterable(str)): The mim2gene lines

    Yields:
        parsed_entry(dict)

        {
            "mim_number": int,
            "entry_type": str,
            "entrez_gene_id": int,
            "hgnc_symbol": str,
            "ensembl_gene_id": str,
            "ensembl_transcript_id": str,
        }


header = []<EOL>for i,line in enumerate(lines):<EOL><INDENT>line = line.rstrip()<EOL>if line.startswith('<STR_LIT:#>'):<EOL><INDENT>if i < <NUM_LIT:10>:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>header = line[<NUM_LIT:2>:].split('<STR_LIT:\t>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>yield parse_omim_line(line, header)<EOL><DEDENT><DEDENT>


header = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>for i,line in enumerate(lines):<EOL><INDENT>line = line.rstrip()<EOL>if not line.startswith('<STR_LIT:#>'):<EOL><INDENT>parsed_entry = parse_omim_line(line, header)<EOL>parsed_entry['<STR_LIT>'] = int(parsed_entry['<STR_LIT>'])<EOL>parsed_entry['<STR_LIT>'] = parsed_entry['<STR_LIT>'].split('<STR_LIT:;>')[<NUM_LIT:0>]<EOL>yield parsed_entry<EOL><DEDENT><DEDENT>

Parse the mimTitles.txt file

    This file hold information about the description for each entry in omim.
    There is not information about entry type.
    parse_mim_titles collects the preferred title and maps it to the mim number.

    Args:
        lines(iterable): lines from mimTitles file

    Yields:
        parsed_entry(dict)

        {
        'mim_number': int, # The mim number for entry
        'preferred_title': str, # the preferred title for a entry
        }


LOG.info("<STR_LIT>")<EOL>genes = {}<EOL>hgnc_genes = {}<EOL>gene_nr = <NUM_LIT:0><EOL>no_hgnc = <NUM_LIT:0><EOL>for entry in parse_mim2gene(mim2gene_lines):<EOL><INDENT>if '<STR_LIT>' in entry['<STR_LIT>']:<EOL><INDENT>mim_nr = entry['<STR_LIT>']<EOL>gene_nr += <NUM_LIT:1><EOL>if not '<STR_LIT>' in entry:<EOL><INDENT>no_hgnc += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>genes[mim_nr] = entry<EOL><DEDENT><DEDENT><DEDENT>LOG.info("<STR_LIT>", str(no_hgnc))<EOL>for entry in parse_genemap2(genemap_lines):<EOL><INDENT>mim_number = entry['<STR_LIT>']<EOL>inheritance = entry['<STR_LIT>']<EOL>phenotype_info = entry['<STR_LIT>']<EOL>hgnc_symbol = entry['<STR_LIT>']<EOL>hgnc_symbols = entry['<STR_LIT>']<EOL>if mim_number in genes:<EOL><INDENT>genes[mim_number]['<STR_LIT>'] = inheritance<EOL>genes[mim_number]['<STR_LIT>'] = phenotype_info<EOL>genes[mim_number]['<STR_LIT>'] = hgnc_symbols<EOL><DEDENT><DEDENT>for mim_nr in genes:<EOL><INDENT>gene_info = genes[mim_nr]<EOL>hgnc_symbol = gene_info['<STR_LIT>']<EOL>if hgnc_symbol in hgnc_genes:<EOL><INDENT>existing_info = hgnc_genes[hgnc_symbol]<EOL>if not existing_info['<STR_LIT>']:<EOL><INDENT>hgnc_genes[hgnc_symbol] = gene_info<EOL><DEDENT><DEDENT>else:<EOL><INDENT>hgnc_genes[hgnc_symbol] = gene_info<EOL><DEDENT><DEDENT>return hgnc_genes<EOL>

Get a dictionary with genes and their omim information

    Args:
        genemap_lines(iterable(str))
        mim2gene_lines(iterable(str))

    Returns.
        hgnc_genes(dict): A dictionary with hgnc_symbol as keys


<EOL>phenotype_mims = set()<EOL>phenotypes_found = {}<EOL>for entry in parse_genemap2(genemap_lines):<EOL><INDENT>hgnc_symbol = entry['<STR_LIT>']<EOL>for phenotype in entry['<STR_LIT>']:<EOL><INDENT>mim_nr = phenotype['<STR_LIT>']<EOL>if mim_nr in phenotypes_found:<EOL><INDENT>phenotype_entry = phenotypes_found[mim_nr]<EOL>phenotype_entry['<STR_LIT>'] = phenotype_entry['<STR_LIT>'].union(phenotype['<STR_LIT>'])<EOL>phenotype_entry['<STR_LIT>'].add(hgnc_symbol)<EOL><DEDENT>else:<EOL><INDENT>phenotype['<STR_LIT>'] = set([hgnc_symbol])<EOL>phenotypes_found[mim_nr] = phenotype<EOL><DEDENT><DEDENT><DEDENT>return phenotypes_found<EOL>

Get a dictionary with phenotypes

    Use the mim numbers for phenotypes as keys and phenotype information as
    values.

    Args:
        genemap_lines(iterable(str))

    Returns:
        phenotypes_found(dict): A dictionary with mim_numbers as keys and
        dictionaries with phenotype information as values.

        {
             'description': str, # Description of the phenotype
             'hgnc_symbols': set(), # Associated hgnc symbols
             'inheritance': set(),  # Associated phenotypes
             'mim_number': int, # mim number of phenotype
        }


@click.command()<EOL>@click.option('<STR_LIT>', type=click.Path(exists=True))<EOL>@click.option('<STR_LIT>', type=click.Path(exists=True))<EOL>@click.option('<STR_LIT>', type=click.Path(exists=True))<EOL>@click.option('<STR_LIT>', type=click.Path(exists=True))<EOL>@click.option('<STR_LIT>', is_flag=True)<EOL>@click.pass_context<EOL>def cli(context, morbid, genemap, mim2gene, mim_titles, phenotypes):

<EOL>from scout.utils.handle import get_file_handle<EOL>from pprint import pprint as pp<EOL>print("<STR_LIT>" % morbid)<EOL>print("<STR_LIT>" % genemap)<EOL>print("<STR_LIT>" % mim2gene)<EOL>print("<STR_LIT>" % mim_titles)<EOL>if morbid:<EOL><INDENT>morbid_handle = get_file_handle(morbid)<EOL><DEDENT>if genemap:<EOL><INDENT>genemap_handle = get_file_handle(genemap)<EOL><DEDENT>if mim2gene:<EOL><INDENT>mim2gene_handle = get_file_handle(mim2gene)<EOL><DEDENT>if mim_titles:<EOL><INDENT>mimtitles_handle = get_file_handle(mim_titles)<EOL><DEDENT>mim_genes = get_mim_genes(genemap_handle, mim2gene_handle)<EOL>for entry in mim_genes: <EOL><INDENT>if entry == '<STR_LIT>':<EOL><INDENT>pp(mim_genes[entry])<EOL><DEDENT><DEDENT>context.abort()<EOL>if phenotypes:<EOL><INDENT>if not genemap:<EOL><INDENT>click.echo("<STR_LIT>")<EOL>context.abort()<EOL><DEDENT>phenotypes = get_mim_phenotypes(genemap_handle)<EOL>for i,mim_term in enumerate(phenotypes):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>print("<STR_LIT>" % i)<EOL>context.abort()<EOL>genes = get_mim_genes(genemap_handle, mim2gene_handle)<EOL>for hgnc_symbol in genes:<EOL><INDENT>if hgnc_symbol == '<STR_LIT>':<EOL><INDENT>print(genes[hgnc_symbol])<EOL><DEDENT><DEDENT>


LOG.info('<STR_LIT>'.format(case_obj.get('<STR_LIT>')))<EOL>features = []<EOL>case_features = case_obj.get('<STR_LIT>')<EOL>if case_features:<EOL><INDENT>for feature in case_features:<EOL><INDENT>feature_obj = {<EOL>"<STR_LIT:id>" : feature.get('<STR_LIT>'),<EOL>"<STR_LIT:label>" : feature.get('<STR_LIT>'),<EOL>"<STR_LIT>" : "<STR_LIT:yes>"<EOL>}<EOL>features.append(feature_obj)<EOL><DEDENT><DEDENT>return features<EOL>

Extract all phenotype-associated terms for a case. Drawback of this method is that
        it returns the same phenotype terms for each affected individual
        of the case.
        Args:
            case_obj(dict): a scout case object
        Returns:
            features(list): a list of phenotype objects that looks like this:
            [
              {
                "id": "HP:0001644",
                "label": "Dilated cardiomyopathy",
                "observed": "yes"
              },
              ...
            ]


LOG.info("<STR_LIT>".format(case_obj.get('<STR_LIT>')))<EOL>disorders = []<EOL>case_disorders = case_obj.get('<STR_LIT>') <EOL>if case_disorders:<EOL><INDENT>for disorder in case_disorders:<EOL><INDENT>disorder_obj = {<EOL>"<STR_LIT:id>" : '<STR_LIT::>'.join([ '<STR_LIT>', str(disorder)])<EOL>}<EOL>disorders.append(disorder_obj)<EOL><DEDENT><DEDENT>return disorders<EOL>

Extract all OMIM phenotypes available for the case
    Args:
        case_obj(dict): a scout case object
    Returns:
        disorders(list): a list of OMIM disorder objects


def genomic_features(store, case_obj, sample_name, genes_only):

g_features = []<EOL>build = case_obj['<STR_LIT>']<EOL>if not build in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>build = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>build = '<STR_LIT>'+build<EOL><DEDENT>individual_pinned_snvs = list(store.sample_variants( variants=case_obj.get('<STR_LIT>'),<EOL>sample_name=sample_name))<EOL>gene_set = set()<EOL>for var in individual_pinned_snvs:<EOL><INDENT>hgnc_genes = var.get('<STR_LIT>')<EOL>if not hgnc_genes:<EOL><INDENT>continue<EOL><DEDENT>for hgnc_id in hgnc_genes:<EOL><INDENT>gene_obj = store.hgnc_gene(hgnc_id)<EOL>if not gene_obj:<EOL><INDENT>continue<EOL><DEDENT>g_feature = {<EOL>'<STR_LIT>': {'<STR_LIT:id>': gene_obj.get('<STR_LIT>')}<EOL>}<EOL>if genes_only and not hgnc_id in gene_set: <EOL><INDENT>gene_set.add(hgnc_id)<EOL>g_features.append(g_feature)<EOL>continue<EOL><DEDENT>g_feature['<STR_LIT>'] = {<EOL>'<STR_LIT>' : var['<STR_LIT>'],<EOL>'<STR_LIT:start>' : var['<STR_LIT>'],<EOL>'<STR_LIT:end>' : var['<STR_LIT:end>'],<EOL>'<STR_LIT>' : build,<EOL>'<STR_LIT>' :var['<STR_LIT>'],<EOL>'<STR_LIT>' : var['<STR_LIT>'],<EOL>'<STR_LIT>' : True<EOL>}<EOL>zygosity = None<EOL>zygosities = var['<STR_LIT>'] <EOL>for zyg in zygosities:<EOL><INDENT>if zyg.get('<STR_LIT>') == sample_name: <EOL><INDENT>zygosity = zyg['<STR_LIT>'].count('<STR_LIT:1>') + zyg['<STR_LIT>'].count('<STR_LIT:2>')<EOL><DEDENT><DEDENT>g_feature['<STR_LIT>'] = zygosity<EOL>g_features.append(g_feature)<EOL><DEDENT><DEDENT>return g_features<EOL>

Extract and parse matchmaker-like genomic features from pinned variants
        of a patient
    Args:
        store(MongoAdapter) : connection to the database
        case_obj(dict): a scout case object
        sample_name(str): sample display name
        genes_only(bool): if True only gene names will be included in genomic features

    Returns:
        g_features(list): a list of genomic feature objects that looks like this:
            [
              {
                "gene": {
                  "id": "LIMS2"
                },
                "variant": {
                  "alternateBases": "C",
                  "assembly": "GRCh37",
                  "end": 128412081,
                  "referenceBases": "G",
                  "referenceName": "2",
                  "start": 128412080
                },
                "zygosity": 1
              },
              ....
            ]


LOG.info('<STR_LIT>'.format(patient_id))<EOL>parsed_matches = []<EOL>for match_obj in match_objs:<EOL><INDENT>milliseconds_date = match_obj['<STR_LIT>']['<STR_LIT>']<EOL>mdate = datetime.datetime.fromtimestamp(milliseconds_date/<NUM_LIT>)<EOL>match_type = '<STR_LIT>'<EOL>matching_patients = []<EOL>parsed_match = {<EOL>'<STR_LIT>' : match_obj['<STR_LIT>']['<STR_LIT>'],<EOL>'<STR_LIT>' : mdate<EOL>}<EOL>if match_obj['<STR_LIT:data>']['<STR_LIT>']['<STR_LIT:id>'] == patient_id:<EOL><INDENT>match_results = match_obj['<STR_LIT>'] <EOL>for node_result in match_results:<EOL><INDENT>if match_obj['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>match_type = '<STR_LIT>'<EOL><DEDENT>for patient in node_result['<STR_LIT>']:<EOL><INDENT>match_patient = {<EOL>'<STR_LIT>' : patient['<STR_LIT>']['<STR_LIT:id>'],<EOL>'<STR_LIT>' : patient['<STR_LIT>'],<EOL>'<STR_LIT>' : patient['<STR_LIT>'],<EOL>'<STR_LIT>' : node_result['<STR_LIT>']<EOL>}<EOL>matching_patients.append(match_patient)<EOL><DEDENT><DEDENT><DEDENT>else: <EOL><INDENT>m_patient = match_obj['<STR_LIT:data>']['<STR_LIT>']<EOL>contact_institution = m_patient['<STR_LIT>'].get('<STR_LIT>')<EOL>if contact_institution and '<STR_LIT>' in contact_institution:<EOL><INDENT>match_type = '<STR_LIT>'<EOL><DEDENT>score = None<EOL>for res in match_obj['<STR_LIT>']:<EOL><INDENT>for patient in res['<STR_LIT>']:<EOL><INDENT>LOG.info('<STR_LIT>'.format(patient['<STR_LIT>']['<STR_LIT:id>']))<EOL>if patient['<STR_LIT>']['<STR_LIT:id>'] == patient_id:<EOL><INDENT>score = patient['<STR_LIT>']<EOL>match_patient = {<EOL>'<STR_LIT>' : m_patient['<STR_LIT:id>'],<EOL>'<STR_LIT>' : score,<EOL>'<STR_LIT>' : m_patient,<EOL>'<STR_LIT>' : res['<STR_LIT>']<EOL>}<EOL>matching_patients.append(match_patient)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>parsed_match['<STR_LIT>'] = match_type<EOL>parsed_match['<STR_LIT>'] = matching_patients<EOL>parsed_matches.append(parsed_match)<EOL><DEDENT>parsed_matches = sorted(parsed_matches, key=lambda k: k['<STR_LIT>'], reverse=True)<EOL>return parsed_matches<EOL>

Parse a list of matchmaker matches objects and returns
       a readable list of matches to display in matchmaker matches view.

    Args:
        patient_id(str): id of a mme patient
        match_objs(list): list of match objs returned by MME server for the patient
                # match_objs looks like this:
                    [
                        {
                            'node' : { id : node_id , label: node_label},
                            'patients' : [
                                { 'patient': {patient1_data} },
                                { 'patient': {patient2_data} },
                                ..
                            ]
                        },
                        ..
                    ]

    Returns:
        parsed_matches(list): a list of parsed match objects


hgnc_gene = {}<EOL>line = line.rstrip().split('<STR_LIT:\t>')<EOL>raw_info = dict(zip(header, line))<EOL>if '<STR_LIT>' in raw_info['<STR_LIT:status>']:<EOL><INDENT>return hgnc_gene<EOL><DEDENT>hgnc_symbol = raw_info['<STR_LIT>']<EOL>hgnc_gene['<STR_LIT>'] = hgnc_symbol<EOL>hgnc_gene['<STR_LIT>'] = int(raw_info['<STR_LIT>'].split('<STR_LIT::>')[-<NUM_LIT:1>])<EOL>hgnc_gene['<STR_LIT:description>'] = raw_info['<STR_LIT:name>']<EOL>aliases = set([hgnc_symbol, hgnc_symbol.upper()])<EOL>previous_names = raw_info['<STR_LIT>']<EOL>if previous_names:<EOL><INDENT>for alias in previous_names.strip('<STR_LIT:">').split('<STR_LIT:|>'):<EOL><INDENT>aliases.add(alias)<EOL><DEDENT><DEDENT>alias_symbols = raw_info['<STR_LIT>']<EOL>if alias_symbols:<EOL><INDENT>for alias in alias_symbols.strip('<STR_LIT:">').split('<STR_LIT:|>'):<EOL><INDENT>aliases.add(alias)<EOL><DEDENT><DEDENT>hgnc_gene['<STR_LIT>'] = list(aliases)<EOL>hgnc_gene['<STR_LIT>'] = raw_info.get('<STR_LIT>')<EOL>omim_id = raw_info.get('<STR_LIT>')<EOL>if omim_id:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = int(omim_id.strip('<STR_LIT:">').split('<STR_LIT:|>')[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = None<EOL><DEDENT>entrez_id = hgnc_gene['<STR_LIT>'] = raw_info.get('<STR_LIT>')<EOL>if entrez_id:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = int(entrez_id)<EOL><DEDENT>else:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = None<EOL><DEDENT>ref_seq = raw_info.get('<STR_LIT>')<EOL>if ref_seq:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = ref_seq.strip('<STR_LIT:">').split('<STR_LIT:|>')<EOL><DEDENT>else:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = []<EOL><DEDENT>uniprot_ids = raw_info.get('<STR_LIT>')<EOL>if uniprot_ids:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = uniprot_ids.strip('<STR_LIT>').split('<STR_LIT:|>')<EOL><DEDENT>else:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = []<EOL><DEDENT>ucsc_id = raw_info.get('<STR_LIT>')<EOL>if ucsc_id:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = ucsc_id<EOL><DEDENT>else:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = None<EOL><DEDENT>vega_id = raw_info.get('<STR_LIT>')<EOL>if vega_id:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = vega_id<EOL><DEDENT>else:<EOL><INDENT>hgnc_gene['<STR_LIT>'] = None<EOL><DEDENT>return hgnc_gene<EOL>

Parse an hgnc formated line

        Args:
            line(list): A list with hgnc gene info
            header(list): A list with the header info

        Returns:
            hgnc_info(dict): A dictionary with the relevant info


header = []<EOL>logger.info("<STR_LIT>")<EOL>for index, line in enumerate(lines):<EOL><INDENT>if index == <NUM_LIT:0>:<EOL><INDENT>header = line.split('<STR_LIT:\t>')<EOL><DEDENT>elif len(line) > <NUM_LIT:1>:<EOL><INDENT>hgnc_gene = parse_hgnc_line(line=line, header=header)<EOL>if hgnc_gene:<EOL><INDENT>yield hgnc_gene<EOL><DEDENT><DEDENT><DEDENT>

Parse lines with hgnc formated genes

        This is designed to take a dump with genes from HGNC.
        This is downloaded from:
        ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt

        Args:
            lines(iterable(str)): An iterable with HGNC formated genes
        Yields:
            hgnc_gene(dict): A dictionary with the relevant information


exac_gene = {}<EOL>splitted_line = line.rstrip().split('<STR_LIT:\t>')<EOL>exac_gene = dict(zip(header, splitted_line))<EOL>exac_gene['<STR_LIT>'] = exac_gene['<STR_LIT>']<EOL>exac_gene['<STR_LIT>'] = float(exac_gene['<STR_LIT>'])<EOL>exac_gene['<STR_LIT>'] = line<EOL>return exac_gene<EOL>

Parse an exac formated line

        Args:
            line(list): A list with exac gene info
            header(list): A list with the header info

        Returns:
            exac_info(dict): A dictionary with the relevant info


header = []<EOL>logger.info("<STR_LIT>")<EOL>for index, line in enumerate(lines):<EOL><INDENT>if index == <NUM_LIT:0>:<EOL><INDENT>header = line.rstrip().split('<STR_LIT:\t>')<EOL><DEDENT>elif len(line) > <NUM_LIT:0>:<EOL><INDENT>exac_gene = parse_exac_line(line, header)<EOL>yield exac_gene<EOL><DEDENT><DEDENT>

Parse lines with exac formated genes

        This is designed to take a dump with genes from exac.
        This is downloaded from:
            ftp.broadinstitute.org/pub/ExAC_release//release0.3/functional_gene_constraint/
            fordist_cleaned_exac_r03_march16_z_pli_rec_null_data.txt

        Args:
            lines(iterable(str)): An iterable with ExAC formated genes
        Yields:
            exac_gene(dict): A dictionary with the relevant information


hpo_line = hpo_line.rstrip().split('<STR_LIT:\t>')<EOL>hpo_info = {}<EOL>hpo_info['<STR_LIT>'] = hpo_line[<NUM_LIT:0>]<EOL>hpo_info['<STR_LIT:description>'] = hpo_line[<NUM_LIT:1>]<EOL>hpo_info['<STR_LIT>'] = hpo_line[<NUM_LIT:3>]<EOL>return hpo_info<EOL>

Parse hpo phenotype

        Args:
            hpo_line(str): A iterable with hpo phenotype lines

        Yields:
            hpo_info(dict)


if not len(hpo_line) > <NUM_LIT:3>:<EOL><INDENT>return {}<EOL><DEDENT>hpo_line = hpo_line.rstrip().split('<STR_LIT:\t>')<EOL>hpo_info = {}<EOL>hpo_info['<STR_LIT>'] = hpo_line[<NUM_LIT:1>]<EOL>hpo_info['<STR_LIT:description>'] = hpo_line[<NUM_LIT:2>]<EOL>hpo_info['<STR_LIT>'] = hpo_line[<NUM_LIT:3>]<EOL>return hpo_info<EOL>

Parse hpo gene information

        Args:
            hpo_line(str): A iterable with hpo phenotype lines

        Yields:
            hpo_info(dict)


hpo_line = hpo_line.rstrip().split('<STR_LIT:\t>')<EOL>hpo_info = {}<EOL>disease = hpo_line[<NUM_LIT:0>].split('<STR_LIT::>')<EOL>hpo_info['<STR_LIT:source>'] = disease[<NUM_LIT:0>]<EOL>hpo_info['<STR_LIT>'] = int(disease[<NUM_LIT:1>])<EOL>hpo_info['<STR_LIT>'] = None<EOL>hpo_info['<STR_LIT>'] = None<EOL>if len(hpo_line) >= <NUM_LIT:3>:<EOL><INDENT>hpo_info['<STR_LIT>'] = hpo_line[<NUM_LIT:2>]<EOL>if len(hpo_line) >= <NUM_LIT:4>:<EOL><INDENT>hpo_info['<STR_LIT>'] = hpo_line[<NUM_LIT:3>]<EOL><DEDENT><DEDENT>return hpo_info<EOL>

Parse hpo disease line

        Args:
            hpo_line(str)


hpo_terms = {}<EOL>LOG.info("<STR_LIT>")<EOL>for index, line in enumerate(hpo_lines):<EOL><INDENT>if index > <NUM_LIT:0> and len(line) > <NUM_LIT:0>:<EOL><INDENT>hpo_info = parse_hpo_phenotype(line)<EOL>hpo_term = hpo_info['<STR_LIT>']<EOL>hgnc_symbol = hpo_info['<STR_LIT>']<EOL>if hpo_term in hpo_terms:<EOL><INDENT>hpo_terms[hpo_term]['<STR_LIT>'].append(hgnc_symbol)<EOL><DEDENT>else:<EOL><INDENT>hpo_terms[hpo_term] = {<EOL>'<STR_LIT>':hpo_term,<EOL>'<STR_LIT:description>': hpo_info['<STR_LIT:description>'],<EOL>'<STR_LIT>': [hgnc_symbol]<EOL>}<EOL><DEDENT><DEDENT><DEDENT>LOG.info("<STR_LIT>")<EOL>return hpo_terms<EOL>

Parse hpo phenotypes

        Group the genes that a phenotype is associated to in 'genes'

    Args:
        hpo_lines(iterable(str)): A file handle to the hpo phenotypes file

    Returns:
        hpo_terms(dict): A dictionary with hpo_ids as keys and terms as values

        {
            <hpo_id>: {
                'hpo_id':str,
                'description': str,
                'hgnc_symbols': list(str), # [<hgnc_symbol>, ...]
                }
        }


diseases = {}<EOL>LOG.info("<STR_LIT>")<EOL>for index, line in enumerate(hpo_lines):<EOL><INDENT>if index == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if not len(line) > <NUM_LIT:3>:<EOL><INDENT>continue<EOL><DEDENT>disease_info = parse_hpo_disease(line)<EOL>if not disease_info:<EOL><INDENT>continue<EOL><DEDENT>disease_nr = disease_info['<STR_LIT>']<EOL>hgnc_symbol = disease_info['<STR_LIT>']<EOL>hpo_term = disease_info['<STR_LIT>']<EOL>source = disease_info['<STR_LIT:source>']<EOL>disease_id = "<STR_LIT>".format(source, disease_nr)<EOL>if disease_id not in diseases:<EOL><INDENT>diseases[disease_id] = {<EOL>'<STR_LIT>': disease_nr,<EOL>'<STR_LIT:source>': source,<EOL>'<STR_LIT>': set(),<EOL>'<STR_LIT>': set(),<EOL>}<EOL><DEDENT>if hgnc_symbol:<EOL><INDENT>diseases[disease_id]['<STR_LIT>'].add(hgnc_symbol)<EOL><DEDENT>if hpo_term:<EOL><INDENT>diseases[disease_id]['<STR_LIT>'].add(hpo_term)<EOL><DEDENT><DEDENT>LOG.info("<STR_LIT>")<EOL>return diseases<EOL>

Parse hpo disease phenotypes

        Args:
            hpo_lines(iterable(str))

        Returns:
            diseases(dict): A dictionary with mim numbers as keys


for line in hpo_lines:<EOL><INDENT>if line.startswith('<STR_LIT:#>') or len(line) < <NUM_LIT:1>:<EOL><INDENT>continue<EOL><DEDENT>line = line.rstrip().split('<STR_LIT:\t>')<EOL>hpo_id = line[<NUM_LIT:0>]<EOL>hgnc_symbol = line[<NUM_LIT:3>]<EOL>yield {<EOL>'<STR_LIT>': hpo_id,<EOL>'<STR_LIT>': hgnc_symbol<EOL>}<EOL><DEDENT>

Parse the map from hpo term to hgnc symbol

    Args:
        lines(iterable(str)):

    Yields:
        hpo_to_gene(dict): A dictionary with information on how a term map to a hgnc symbol


LOG.info("<STR_LIT>")<EOL>genes = {}<EOL>for index, line in enumerate(hpo_lines):<EOL><INDENT>if index == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if len(line) < <NUM_LIT:5>:<EOL><INDENT>continue<EOL><DEDENT>gene_info = parse_hpo_gene(line)<EOL>hgnc_symbol = gene_info['<STR_LIT>']<EOL>description = gene_info['<STR_LIT:description>']<EOL>if hgnc_symbol not in genes:<EOL><INDENT>genes[hgnc_symbol] = {<EOL>'<STR_LIT>': hgnc_symbol<EOL>}<EOL><DEDENT>gene = genes[hgnc_symbol]<EOL>if description == '<STR_LIT>':<EOL><INDENT>gene['<STR_LIT>'] = True<EOL><DEDENT>if description == '<STR_LIT>':<EOL><INDENT>gene['<STR_LIT>'] = True<EOL><DEDENT>if description == '<STR_LIT>':<EOL><INDENT>gene['<STR_LIT>'] = True<EOL><DEDENT>if description == '<STR_LIT>':<EOL><INDENT>gene['<STR_LIT>'] = True<EOL><DEDENT>if description == '<STR_LIT>':<EOL><INDENT>gene['<STR_LIT>'] = True<EOL><DEDENT>if description == '<STR_LIT>':<EOL><INDENT>gene['<STR_LIT>'] = True<EOL><DEDENT>if description == '<STR_LIT>':<EOL><INDENT>gene['<STR_LIT:x>'] = True<EOL><DEDENT>if description == '<STR_LIT>':<EOL><INDENT>gene['<STR_LIT:y>'] = True<EOL><DEDENT><DEDENT>LOG.info("<STR_LIT>")<EOL>return genes<EOL>

Parse HPO gene information

        Args:
            hpo_lines(iterable(str))

        Returns:
            diseases(dict): A dictionary with hgnc symbols as keys


genes = parse_hpo_genes(hpo_lines)<EOL>incomplete_penetrance_genes = set()<EOL>for hgnc_symbol in genes:<EOL><INDENT>if genes[hgnc_symbol].get('<STR_LIT>'):<EOL><INDENT>incomplete_penetrance_genes.add(hgnc_symbol)<EOL><DEDENT><DEDENT>return incomplete_penetrance_genes<EOL>

Get a set with all genes that have incomplete penetrance according to HPO

    Args:
        hpo_lines(iterable(str))

    Returns:
        incomplete_penetrance_genes(set): A set with the hgnc symbols of all
                                          genes with incomplete penetrance


term = {}<EOL>for line in hpo_lines:<EOL><INDENT>if len(line) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>line = line.rstrip()<EOL>if line == '<STR_LIT>':<EOL><INDENT>if term:<EOL><INDENT>yield term<EOL><DEDENT>term = {}<EOL><DEDENT>elif line.startswith('<STR_LIT:id>'):<EOL><INDENT>term['<STR_LIT>'] = line[<NUM_LIT:4>:]<EOL><DEDENT>elif line.startswith('<STR_LIT:name>'):<EOL><INDENT>term['<STR_LIT:description>'] = line[<NUM_LIT:6>:]<EOL><DEDENT>elif line.startswith('<STR_LIT>'):<EOL><INDENT>if '<STR_LIT>' not in term:<EOL><INDENT>term['<STR_LIT>'] = []<EOL><DEDENT>term['<STR_LIT>'].append(line[<NUM_LIT:8>:])<EOL><DEDENT>elif line.startswith('<STR_LIT>'):<EOL><INDENT>if '<STR_LIT>' not in term:<EOL><INDENT>term['<STR_LIT>'] = []<EOL><DEDENT>term['<STR_LIT>'].append(line[<NUM_LIT:6>:<NUM_LIT:16>])<EOL><DEDENT><DEDENT>if term:<EOL><INDENT>yield term<EOL><DEDENT>


return [<EOL>os.path.join(dirpath, file_path)<EOL>for dirpath, subdirs, files in os.walk(root_dir)<EOL>for file_path in files<EOL>]<EOL>

Build a list containing absolute paths to the generated files.


<EOL>for path in paths:<EOL><INDENT>if is_binary(path):<EOL><INDENT>continue<EOL><DEDENT>for line in open(path, "<STR_LIT:r>"):<EOL><INDENT>match = RE_OBJ.search(line)<EOL>msg = "<STR_LIT>"<EOL>assert match is None, msg.format(path)<EOL><DEDENT><DEDENT>

Method to check all paths have correct substitutions,
    used by other tests cases


def generate_random_string(<EOL>length, using_digits=False, using_ascii_letters=False, using_punctuation=False<EOL>):

if not using_sysrandom:<EOL><INDENT>return None<EOL><DEDENT>symbols = []<EOL>if using_digits:<EOL><INDENT>symbols += string.digits<EOL><DEDENT>if using_ascii_letters:<EOL><INDENT>symbols += string.ascii_letters<EOL><DEDENT>if using_punctuation:<EOL><INDENT>all_punctuation = set(string.punctuation)<EOL>unsuitable = {"<STR_LIT:'>", '<STR_LIT:">', "<STR_LIT:\\>", "<STR_LIT:$>"}<EOL>suitable = all_punctuation.difference(unsuitable)<EOL>symbols += "<STR_LIT>".join(suitable)<EOL><DEDENT>return "<STR_LIT>".join([random.choice(symbols) for _ in range(length)])<EOL>

Example:
    opting out for 50 symbol-long, [a-z][A-Z][0-9] string
    would yield log_2((26+26+50)^50) ~= 334 bit strength.


Site = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>Site.objects.update_or_create(<EOL>id=settings.SITE_ID,<EOL>defaults={<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT:name>": "<STR_LIT>",<EOL>},<EOL>)<EOL>


Site = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>Site.objects.update_or_create(<EOL>id=settings.SITE_ID, defaults={"<STR_LIT>": "<STR_LIT>", "<STR_LIT:name>": "<STR_LIT>"}<EOL>)<EOL>


if sys.version_info < (<NUM_LIT:3>,<NUM_LIT:0>):<EOL><INDENT>return BytesIO()<EOL><DEDENT>else:<EOL><INDENT>return StringIO()<EOL><DEDENT>

Returns a file object of the same type as `sys.stdout`.


def run(parser, command_string, kwargs=None, exit=False):

kwargs = kwargs or {}<EOL>try:<EOL><INDENT>return call_cmd(parser, command_string, **kwargs)<EOL><DEDENT>except SystemExit as error:<EOL><INDENT>if exit:<EOL><INDENT>if error.args == (None,):<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return str(error)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if exit:<EOL><INDENT>raise AssertionError('<STR_LIT>')<EOL><DEDENT><DEDENT>

Calls the command and returns result.

    If SystemExit is raised, it propagates.

    :exit:
        if set to `True`, then any SystemExit exception is caught and its
        string representation is returned; if the exception is not raised,
        an AssertionError is raised.  In other words, this parameter inverts
        the function's behaviour and expects SystemExit as the correct event.


if COMPLETION_ENABLED:<EOL><INDENT>argcomplete.autocomplete(parser)<EOL><DEDENT>elif '<STR_LIT>' in os.getenv('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>logger.debug('<STR_LIT>')<EOL><DEDENT>

Adds support for shell completion via argcomplete_ by patching given
`argparse.ArgumentParser` (sub)class.

If completion is not enabled, logs a debug-level message.


def confirm(action, default=None, skip=False):

MAX_ITERATIONS = <NUM_LIT:3><EOL>if skip:<EOL><INDENT>return default<EOL><DEDENT>else:<EOL><INDENT>defaults = {<EOL>None: ('<STR_LIT:y>','<STR_LIT:n>'),<EOL>True: ('<STR_LIT:Y>','<STR_LIT:n>'),<EOL>False: ('<STR_LIT:y>','<STR_LIT:N>'),<EOL>}<EOL>y, n = defaults[default]<EOL>prompt = text_type('<STR_LIT>').format(**locals())<EOL>choice = None<EOL>try:<EOL><INDENT>if default is None:<EOL><INDENT>cnt = <NUM_LIT:1><EOL>while not choice and cnt < MAX_ITERATIONS:<EOL><INDENT>choice = safe_input(prompt)<EOL>cnt += <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>choice = safe_input(prompt)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if choice in ('<STR_LIT:yes>', '<STR_LIT:y>', '<STR_LIT:Y>'):<EOL><INDENT>return True<EOL><DEDENT>if choice in ('<STR_LIT>', '<STR_LIT:n>', '<STR_LIT:N>'):<EOL><INDENT>return False<EOL><DEDENT>if default is not None:<EOL><INDENT>return default<EOL><DEDENT>return None<EOL>

A shortcut for typical confirmation prompt.

:param action:

    a string describing the action, e.g. "Apply changes". A question mark
    will be appended.

:param default:

    `bool` or `None`. Determines what happens when user hits :kbd:`Enter`
    without typing in a choice. If `True`, default choice is "yes". If
    `False`, it is "no". If `None` the prompt keeps reappearing until user
    types in a choice (not necessarily acceptable) or until the number of
    iteration reaches the limit. Default is `None`.

:param skip:

    `bool`; if `True`, no interactive prompt is used and default choice is
    returned (useful for batch mode). Default is `False`.

Usage::

    def delete(key, silent=False):
        item = db.get(Item, args.key)
        if confirm('Delete '+item.title, default=True, skip=silent):
            item.delete()
            print('Item deleted.')
        else:
            print('Operation cancelled.')

Returns `None` on `KeyboardInterrupt` event.


if inspect.ismethod(func):<EOL><INDENT>func = func.im_func<EOL><DEDENT>if not (hasattr(func, "<STR_LIT>") and hasattr(func, "<STR_LIT>")):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(func))<EOL><DEDENT>args, varargs, varkw = inspect.getargs(func.func_code)<EOL>return inspect.ArgSpec(args, varargs, varkw, func.func_defaults)<EOL>

An `inspect.getargspec` with a relaxed sanity check to support Cython.

Motivation:

    A Cython-compiled function is *not* an instance of Python's
    types.FunctionType.  That is the sanity check the standard Py2
    library uses in `inspect.getargspec()`.  So, an exception is raised
    when calling `argh.dispatch_command(cythonCompiledFunc)`.  However,
    the CyFunctions do have perfectly usable `.func_code` and
    `.func_defaults` which is all `inspect.getargspec` needs.

    This function just copies `inspect.getargspec()` from the standard
    library but relaxes the test to a more duck-typing one of having
    both `.func_code` and `.func_defaults` attributes.


params = dict(vars(action), prog=self._prog)<EOL>for name in list(params):<EOL><INDENT>if params[name] is argparse.SUPPRESS:<EOL><INDENT>del params[name]<EOL><DEDENT><DEDENT>for name in list(params):<EOL><INDENT>if hasattr(params[name], '<STR_LIT>'):<EOL><INDENT>params[name] = params[name].__name__<EOL><DEDENT><DEDENT>if params.get('<STR_LIT>') is not None:<EOL><INDENT>choices_str = '<STR_LIT:U+002CU+0020>'.join([str(c) for c in params['<STR_LIT>']])<EOL>params['<STR_LIT>'] = choices_str<EOL><DEDENT>if '<STR_LIT:default>' in params:<EOL><INDENT>if params['<STR_LIT:default>'] is None:<EOL><INDENT>params['<STR_LIT:default>'] = '<STR_LIT:->'<EOL><DEDENT>else:<EOL><INDENT>params['<STR_LIT:default>'] = repr(params['<STR_LIT:default>'])<EOL><DEDENT><DEDENT>return self._get_help_string(action) % params<EOL>

This method is copied verbatim from ArgumentDefaultsHelpFormatter with
a couple of lines added just before the end.  Reason: we need to
`repr()` default values instead of simply inserting them as is.
This helps notice, for example, an empty string as the default value;
moreover, it prevents breaking argparse due to logical quirks inside
of its formatters.

Ideally this could be achieved by simply defining
:attr:`DEFAULT_ARGUMENT_TEMPLATE` as ``{default!r}`` but unfortunately
argparse only supports the old printf syntax.


guessed = {}<EOL>TYPE_AWARE_ACTIONS = '<STR_LIT:store>', '<STR_LIT>'<EOL>value = kwargs.get('<STR_LIT:default>')<EOL>if value is not None:<EOL><INDENT>if isinstance(value, bool):<EOL><INDENT>if kwargs.get('<STR_LIT:action>') is None:<EOL><INDENT>guessed['<STR_LIT:action>'] = '<STR_LIT>' if value else '<STR_LIT:store_true>'<EOL><DEDENT><DEDENT>elif kwargs.get('<STR_LIT:type>') is None:<EOL><INDENT>if kwargs.get('<STR_LIT:action>', '<STR_LIT:store>') in TYPE_AWARE_ACTIONS:<EOL><INDENT>guessed['<STR_LIT:type>'] = type(value)<EOL><DEDENT><DEDENT><DEDENT>if kwargs.get('<STR_LIT>') and '<STR_LIT:type>' not in list(guessed) + list(kwargs):<EOL><INDENT>guessed['<STR_LIT:type>'] = type(kwargs['<STR_LIT>'][<NUM_LIT:0>])<EOL><DEDENT>return dict(kwargs, **guessed)<EOL>

Adds types, actions, etc. to given argument specification.
For example, ``default=3`` implies ``type=int``.

:param arg: a :class:`argh.utils.Arg` instance


if parser._subparsers:<EOL><INDENT>_require_support_for_default_command_with_subparsers()<EOL><DEDENT>spec = get_arg_spec(function)<EOL>declared_args = getattr(function, ATTR_ARGS, [])<EOL>inferred_args = list(_get_args_from_signature(function))<EOL>if inferred_args and declared_args:<EOL><INDENT>dests = OrderedDict()<EOL>for argspec in inferred_args:<EOL><INDENT>dest = _get_parser_param_kwargs(parser, argspec)['<STR_LIT>']<EOL>dests[dest] = argspec<EOL><DEDENT>for declared_kw in declared_args:<EOL><INDENT>dest = _get_dest(parser, declared_kw)<EOL>if dest in dests:<EOL><INDENT>decl_positional = _is_positional(declared_kw['<STR_LIT>'])<EOL>infr_positional = _is_positional(dests[dest]['<STR_LIT>'])<EOL>if decl_positional != infr_positional:<EOL><INDENT>kinds = {True: '<STR_LIT>', False: '<STR_LIT>'}<EOL>raise AssemblingError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(<EOL>func=function.__name__,<EOL>dest=dest,<EOL>kind_i=kinds[infr_positional],<EOL>kind_d=kinds[decl_positional],<EOL>))<EOL><DEDENT>dests[dest].update(**declared_kw)<EOL><DEDENT>else:<EOL><INDENT>varkw = getattr(spec, '<STR_LIT>', getattr(spec, '<STR_LIT>', []))<EOL>if varkw:<EOL><INDENT>dests[dest] = declared_kw<EOL><DEDENT>else:<EOL><INDENT>xs = (dests[x]['<STR_LIT>'] for x in dests)<EOL>raise AssemblingError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>flags='<STR_LIT:U+002CU+0020>'.join(declared_kw['<STR_LIT>']),<EOL>func=function.__name__,<EOL>sig='<STR_LIT:U+002CU+0020>'.join('<STR_LIT:/>'.join(x) for x in xs)))<EOL><DEDENT><DEDENT><DEDENT>inferred_args = dests.values()<EOL><DEDENT>command_args = inferred_args or declared_args<EOL>command_args = [_guess(x) for x in command_args]<EOL>for draft in command_args:<EOL><INDENT>draft = draft.copy()<EOL>if '<STR_LIT>' not in draft:<EOL><INDENT>draft.update(help=DEFAULT_ARGUMENT_TEMPLATE)<EOL><DEDENT>dest_or_opt_strings = draft.pop('<STR_LIT>')<EOL>if parser.add_help and '<STR_LIT>' in dest_or_opt_strings:<EOL><INDENT>dest_or_opt_strings = [x for x in dest_or_opt_strings if x != '<STR_LIT>']<EOL><DEDENT>completer = draft.pop('<STR_LIT>', None)<EOL>try:<EOL><INDENT>action = parser.add_argument(*dest_or_opt_strings, **draft)<EOL>if COMPLETION_ENABLED and completer:<EOL><INDENT>action.completer = completer<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>raise type(e)('<STR_LIT>'.format(<EOL>args='<STR_LIT:/>'.join(dest_or_opt_strings), func=function.__name__, msg=e))<EOL><DEDENT><DEDENT>if function.__doc__ and not parser.description:<EOL><INDENT>parser.description = function.__doc__<EOL><DEDENT>parser.set_defaults(**{<EOL>DEST_FUNCTION: function,<EOL>})<EOL>

Sets default command (i.e. a function) for given parser.

If `parser.description` is empty and the function has a docstring,
it is used as the description.

.. note::

   An attempt to set default command to a parser which already has
   subparsers (e.g. added with :func:`~argh.assembling.add_commands`)
   results in a `AssemblingError`.

.. note::

   If there are both explicitly declared arguments (e.g. via
   :func:`~argh.decorators.arg`) and ones inferred from the function
   signature (e.g. via :func:`~argh.decorators.command`), declared ones
   will be merged into inferred ones. If an argument does not conform
   function signature, `AssemblingError` is raised.

.. note::

   If the parser was created with ``add_help=True`` (which is by default),
   option name ``-h`` is silently removed from any argument.


def add_commands(parser, functions, namespace=None, namespace_kwargs=None,<EOL>func_kwargs=None,<EOL>title=None, description=None, help=None):

<EOL>if DEST_FUNCTION in parser._defaults:<EOL><INDENT>_require_support_for_default_command_with_subparsers()<EOL><DEDENT>namespace_kwargs = namespace_kwargs or {}<EOL>if title:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>', DeprecationWarning)<EOL>namespace_kwargs['<STR_LIT:description>'] = title<EOL><DEDENT>if help:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>', DeprecationWarning)<EOL>namespace_kwargs['<STR_LIT>'] = help<EOL><DEDENT>if description:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>', DeprecationWarning)<EOL>namespace_kwargs['<STR_LIT:description>'] = description<EOL><DEDENT>subparsers_action = get_subparsers(parser, create=True)<EOL>if namespace:<EOL><INDENT>subsubparser_kw = {<EOL>'<STR_LIT>': namespace_kwargs.get('<STR_LIT:title>'),<EOL>}<EOL>subsubparser = subparsers_action.add_parser(namespace, **subsubparser_kw)<EOL>subparsers_action = subsubparser.add_subparsers(**namespace_kwargs)<EOL><DEDENT>else:<EOL><INDENT>assert not namespace_kwargs, ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>for func in functions:<EOL><INDENT>cmd_name, func_parser_kwargs = _extract_command_meta_from_func(func)<EOL>if func_kwargs:<EOL><INDENT>func_parser_kwargs.update(func_kwargs)<EOL><DEDENT>command_parser = subparsers_action.add_parser(cmd_name, **func_parser_kwargs)<EOL>set_default_command(command_parser, func)<EOL><DEDENT>

Adds given functions as commands to given parser.

:param parser:

    an :class:`argparse.ArgumentParser` instance.

:param functions:

    a list of functions. A subparser is created for each of them.
    If the function is decorated with :func:`~argh.decorators.arg`, the
    arguments are passed to :class:`argparse.ArgumentParser.add_argument`.
    See also :func:`~argh.dispatching.dispatch` for requirements
    concerning function signatures. The command name is inferred from the
    function name. Note that the underscores in the name are replaced with
    hyphens, i.e. function name "foo_bar" becomes command name "foo-bar".

:param namespace:

    an optional string representing the group of commands. For example, if
    a command named "hello" is added without the namespace, it will be
    available as "prog.py hello"; if the namespace if specified as "greet",
    then the command will be accessible as "prog.py greet hello". The
    namespace itself is not callable, so "prog.py greet" will fail and only
    display a help message.

:param func_kwargs:

    a `dict` of keyword arguments to be passed to each nested ArgumentParser
    instance created per command (i.e. per function).  Members of this
    dictionary have the highest priority, so a function's docstring is
    overridden by a `help` in `func_kwargs` (if present).

:param namespace_kwargs:

    a `dict` of keyword arguments to be passed to the nested ArgumentParser
    instance under given `namespace`.

Deprecated params that should be moved into `namespace_kwargs`:

:param title:

    passed to :meth:`argparse.ArgumentParser.add_subparsers` as `title`.

    .. deprecated:: 0.26.0

       Please use `namespace_kwargs` instead.

:param description:

    passed to :meth:`argparse.ArgumentParser.add_subparsers` as
    `description`.

    .. deprecated:: 0.26.0

       Please use `namespace_kwargs` instead.

:param help:

    passed to :meth:`argparse.ArgumentParser.add_subparsers` as `help`.

    .. deprecated:: 0.26.0

       Please use `namespace_kwargs` instead.

.. note::

    This function modifies the parser object. Generally side effects are
    bad practice but we don't seem to have any choice as ArgumentParser is
    pretty opaque.
    You may prefer :class:`~argh.helpers.ArghParser.add_commands` for a bit
    more predictable API.

.. note::

   An attempt to add commands to a parser which already has a default
   function (e.g. added with :func:`~argh.assembling.set_default_command`)
   results in `AssemblingError`.


def add_subcommands(parser, namespace, functions, **namespace_kwargs):

add_commands(parser, functions, namespace=namespace,<EOL>namespace_kwargs=namespace_kwargs)<EOL>

A wrapper for :func:`add_commands`.

These examples are equivalent::

    add_commands(parser, [get, put], namespace='db',
                 namespace_kwargs={
                     'title': 'database commands',
                     'help': 'CRUD for our silly database'
                 })

    add_subcommands(parser, 'db', [get, put],
                    title='database commands',
                    help='CRUD for our silly database')


def set_default_command(self, *args, **kwargs):

return set_default_command(self, *args, **kwargs)<EOL>


def add_commands(self, *args, **kwargs):

return add_commands(self, *args, **kwargs)<EOL>


return autocomplete(self)<EOL>


return dispatch(self, *args, **kwargs)<EOL>


def parse_args(self, args=None, namespace=None):

namespace = namespace or ArghNamespace()<EOL>return super(ArghParser, self).parse_args(args, namespace)<EOL>

Wrapper for :meth:`argparse.ArgumentParser.parse_args`.  If `namespace`
is not defined, :class:`argh.dispatching.ArghNamespace` is used.
This is required for functions to be properly used as commands.


def dispatch(parser, argv=None, add_help_command=True,<EOL>completion=True, pre_call=None,<EOL>output_file=sys.stdout, errors_file=sys.stderr,<EOL>raw_output=False, namespace=None,<EOL>skip_unknown_args=False):

if completion:<EOL><INDENT>autocomplete(parser)<EOL><DEDENT>if argv is None:<EOL><INDENT>argv = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>if add_help_command:<EOL><INDENT>if argv and argv[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>argv.pop(<NUM_LIT:0>)<EOL>argv.append('<STR_LIT>')<EOL><DEDENT><DEDENT>if skip_unknown_args:<EOL><INDENT>parse_args = parser.parse_known_args<EOL><DEDENT>else:<EOL><INDENT>parse_args = parser.parse_args<EOL><DEDENT>if not namespace:<EOL><INDENT>namespace = ArghNamespace()<EOL><DEDENT>namespace_obj = parse_args(argv, namespace=namespace)<EOL>function = _get_function_from_namespace_obj(namespace_obj)<EOL>if function:<EOL><INDENT>lines = _execute_command(function, namespace_obj, errors_file,<EOL>pre_call=pre_call)<EOL><DEDENT>else:<EOL><INDENT>lines = [parser.format_usage()]<EOL><DEDENT>if output_file is None:<EOL><INDENT>if sys.version_info < (<NUM_LIT:3>,<NUM_LIT:0>):<EOL><INDENT>f = compat.BytesIO()<EOL><DEDENT>else:<EOL><INDENT>f = compat.StringIO()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>f = output_file<EOL><DEDENT>for line in lines:<EOL><INDENT>io.dump(line, f)<EOL>if not raw_output:<EOL><INDENT>io.dump('<STR_LIT:\n>', f)<EOL><DEDENT><DEDENT>if output_file is None:<EOL><INDENT>f.seek(<NUM_LIT:0>)<EOL>return f.read()<EOL><DEDENT>

Parses given list of arguments using given parser, calls the relevant
function and prints the result.

The target function should expect one positional argument: the
:class:`argparse.Namespace` object. However, if the function is decorated with
:func:`~argh.decorators.plain_signature`, the positional and named
arguments from the namespace object are passed to the function instead
of the object itself.

:param parser:

    the ArgumentParser instance.

:param argv:

    a list of strings representing the arguments. If `None`, ``sys.argv``
    is used instead. Default is `None`.

:param add_help_command:

    if `True`, converts first positional argument "help" to a keyword
    argument so that ``help foo`` becomes ``foo --help`` and displays usage
    information for "foo". Default is `True`.

:param output_file:

    A file-like object for output. If `None`, the resulting lines are
    collected and returned as a string. Default is ``sys.stdout``.

:param errors_file:

    Same as `output_file` but for ``sys.stderr``.

:param raw_output:

    If `True`, results are written to the output file raw, without adding
    whitespaces or newlines between yielded strings. Default is `False`.

:param completion:

    If `True`, shell tab completion is enabled. Default is `True`. (You
    will also need to install it.)  See :mod:`argh.completion`.

:param skip_unknown_args:

    If `True`, unknown arguments do not cause an error
    (`ArgumentParser.parse_known_args` is used).

:param namespace:

    An `argparse.Namespace`-like object.  By default an
    :class:`ArghNamespace` object is used.  Please note that support for
    combined default and nested functions may be broken if a different
    type of object is forced.

By default the exceptions are not wrapped and will propagate. The only
exception that is always wrapped is :class:`~argh.exceptions.CommandError`
which is interpreted as an expected event so the traceback is hidden.
You can also mark arbitrary exceptions as "wrappable" by using the
:func:`~argh.decorators.wrap_errors` decorator.


def _execute_command(function, namespace_obj, errors_file, pre_call=None):

if pre_call:  <EOL><INDENT>pre_call(namespace_obj)<EOL><DEDENT>def _call():<EOL><INDENT>if getattr(function, ATTR_EXPECTS_NAMESPACE_OBJECT, False):<EOL><INDENT>result = function(namespace_obj)<EOL><DEDENT>else:<EOL><INDENT>_flat_key = lambda key: key.replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>all_input = dict((_flat_key(k), v)<EOL>for k,v in vars(namespace_obj).items())<EOL>spec = get_arg_spec(function)<EOL>positional = [all_input[k] for k in spec.args]<EOL>kwonly = getattr(spec, '<STR_LIT>', [])<EOL>keywords = dict((k, all_input[k]) for k in kwonly)<EOL>if spec.varargs:<EOL><INDENT>positional += getattr(namespace_obj, spec.varargs)<EOL><DEDENT>varkw = getattr(spec, '<STR_LIT>', getattr(spec, '<STR_LIT>', []))<EOL>if varkw:<EOL><INDENT>not_kwargs = [DEST_FUNCTION] + spec.args + [spec.varargs] + kwonly<EOL>for k in vars(namespace_obj):<EOL><INDENT>if k.startswith('<STR_LIT:_>') or k in not_kwargs:<EOL><INDENT>continue<EOL><DEDENT>keywords[k] = getattr(namespace_obj, k)<EOL><DEDENT><DEDENT>result = function(*positional, **keywords)<EOL><DEDENT>if isinstance(result, (GeneratorType, list, tuple)):<EOL><INDENT>for line in result:<EOL><INDENT>yield line<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if result is not None:<EOL><INDENT>yield result<EOL><DEDENT><DEDENT><DEDENT>wrappable_exceptions = [CommandError]<EOL>wrappable_exceptions += getattr(function, ATTR_WRAPPED_EXCEPTIONS, [])<EOL>try:<EOL><INDENT>result = _call()<EOL>for line in result:<EOL><INDENT>yield line<EOL><DEDENT><DEDENT>except tuple(wrappable_exceptions) as e:<EOL><INDENT>processor = getattr(function, ATTR_WRAPPED_EXCEPTIONS_PROCESSOR,<EOL>lambda e: '<STR_LIT>'.format(e))<EOL>errors_file.write(compat.text_type(processor(e)))<EOL>errors_file.write('<STR_LIT:\n>')<EOL><DEDENT>

Assumes that `function` is a callable.  Tries different approaches
to call it (with `namespace_obj` or with ordinary signature).
Yields the results line by line.

If :class:`~argh.exceptions.CommandError` is raised, its message is
appended to the results (i.e. yielded by the generator as a string).
All other exceptions propagate unless marked as wrappable
by :func:`wrap_errors`.


def dispatch_command(function, *args, **kwargs):

parser = argparse.ArgumentParser(formatter_class=PARSER_FORMATTER)<EOL>set_default_command(parser, function)<EOL>dispatch(parser, *args, **kwargs)<EOL>

A wrapper for :func:`dispatch` that creates a one-command parser.
Uses :attr:`PARSER_FORMATTER`.

This::

    dispatch_command(foo)

...is a shortcut for::

    parser = ArgumentParser()
    set_default_command(parser, foo)
    dispatch(parser)

This function can be also used as a decorator.


def dispatch_commands(functions, *args, **kwargs):

parser = argparse.ArgumentParser(formatter_class=PARSER_FORMATTER)<EOL>add_commands(parser, functions)<EOL>dispatch(parser, *args, **kwargs)<EOL>

A wrapper for :func:`dispatch` that creates a parser, adds commands to
the parser and dispatches them.
Uses :attr:`PARSER_FORMATTER`.

This::

    dispatch_commands([foo, bar])

...is a shortcut for::

    parser = ArgumentParser()
    add_commands(parser, [foo, bar])
    dispatch(parser)


<EOL>if parser._subparsers:<EOL><INDENT>actions = [a for a in parser._actions<EOL>if isinstance(a, argparse._SubParsersAction)]<EOL>assert len(actions) == <NUM_LIT:1><EOL>return actions[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>if create:<EOL><INDENT>return parser.add_subparsers()<EOL><DEDENT><DEDENT>

Returns the :class:`argparse._SubParsersAction` instance for given
:class:`ArgumentParser` instance as would have been returned by
:meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
it only works once and raises an exception on the second attempt, and the
public API seems to lack a method to get *existing* subparsers.

:param create:
    If `True`, creates the subparser if it does not exist. Default if
    `False`.


while hasattr(function, '<STR_LIT>'):<EOL><INDENT>function = function.__wrapped__<EOL><DEDENT>spec = compat.getargspec(function)<EOL>if inspect.ismethod(function):<EOL><INDENT>spec = spec._replace(args=spec.args[<NUM_LIT:1>:])<EOL><DEDENT>return spec<EOL>

Returns argument specification for given function.  Omits special
arguments of instance methods (`self`) and static methods (usually `cls`
or something like this).


def wrapper(func):<EOL><INDENT>setattr(func, ATTR_NAME, new_name)<EOL>return func<EOL><DEDENT>return wrapper<EOL>

Sets given string as command name instead of the function name.
The string is used verbatim without further processing.

Usage::

    @named('load')
    def do_load_some_stuff_and_keep_the_original_function_name(args):
        ...

The resulting command will be available only as ``load``.  To add aliases
without renaming the command, check :func:`aliases`.

.. versionadded:: 0.19


def wrapper(func):<EOL><INDENT>setattr(func, ATTR_ALIASES, names)<EOL>return func<EOL><DEDENT>return wrapper<EOL>

Defines alternative command name(s) for given function (along with its
original name). Usage::

    @aliases('co', 'check')
    def checkout(args):
        ...

The resulting command will be available as ``checkout``, ``check`` and ``co``.

.. note::

   This decorator only works with a recent version of argparse (see `Python
   issue 9324`_ and `Python rev 4c0426`_).  Such version ships with
   **Python 3.2+** and may be available in other environments as a separate
   package.  Argh does not issue warnings and simply ignores aliases if
   they are not supported.  See :attr:`~argh.assembling.SUPPORTS_ALIASES`.

   .. _Python issue 9324: http://bugs.python.org/issue9324
   .. _Python rev 4c0426: http://hg.python.org/cpython/rev/4c0426261148/

.. versionadded:: 0.19


def wrapper(func):<EOL><INDENT>declared_args = getattr(func, ATTR_ARGS, [])<EOL>declared_args.insert(<NUM_LIT:0>, dict(option_strings=args, **kwargs))<EOL>setattr(func, ATTR_ARGS, declared_args)<EOL>return func<EOL><DEDENT>return wrapper<EOL>

Declares an argument for given function. Does not register the function
anywhere, nor does it modify the function in any way.

The signature of the decorator matches that of
:meth:`argparse.ArgumentParser.add_argument`, only some keywords are not
required if they can be easily guessed (e.g. you don't have to specify type
or action when an `int` or `bool` default value is supplied).

Typical use cases:

- In combination with :func:`expects_obj` (which is not recommended);
- in combination with ordinary function signatures to add details that
  cannot be expressed with that syntax (e.g. help message).

Usage::

    from argh import arg

    @arg('path', help='path to the file to load')
    @arg('--format', choices=['yaml','json'])
    @arg('-v', '--verbosity', choices=range(0,3), default=2)
    def load(path, something=None, format='json', dry_run=False, verbosity=1):
        loaders = {'json': json.load, 'yaml': yaml.load}
        loader = loaders[args.format]
        data = loader(args.path)
        if not args.dry_run:
            if verbosity < 1:
                print('saving to the database')
            put_to_database(data)

In this example:

- `path` declaration is extended with `help`;
- `format` declaration is extended with `choices`;
- `dry_run` declaration is not duplicated;
- `verbosity` is extended with `choices` and the default value is
  overridden.  (If both function signature and `@arg` define a default
  value for an argument, `@arg` wins.)

.. note::

    It is recommended to avoid using this decorator unless there's no way
    to tune the argument's behaviour or presentation using ordinary
    function signatures.  Readability counts, don't repeat yourself.