# Read alignment-based profile counting using `jgi_summarize_bam_contig_depths`
# from the MetaBAT pipeline

rule bowtie_index:
    input:   "assembly/{frags}/{group}.fasta"
    output:  "profile/jgi/{frags}/{group}/index.done"
    params:  "profile/jgi/{frags}/{group}/index"
    threads: THREADS
    log:     "profile/jgi/{frags}/{group}/index.log"
    message: "Building bowtie index for {wildcards.group}"
    shell:   "bowtie2-build {input} {params} --threads {THREADS} >{log} 2>&1 && touch {output}"

rule bowtie_align:
    input:   left=left_sample_reads, right=right_sample_reads,
             index="profile/jgi/{frags}/{group}/index.done"
    output:  "profile/jgi/{frags}/{group}/{sample}.bam"
    params:  flag=lambda w: "-q" if is_fastq(w) else "-f",
             index="profile/jgi/{frags}/{group}/index"
    threads: THREADS
    log:     "profile/jgi/{frags}/{group}/{sample}.log"
    message: "Aligning {wildcards.sample} onto {wildcards.group} with bowtie"
    shell:   "bowtie2 -x {params.index} {params.flag} -p {threads}"
             " -1 {input.left} -2 {input.right} 2>{log} | samtools view -bS - >{output}"

rule depth:
    input:   expand("profile/jgi/{{frags}}/{{group}}/{sample}.bam", sample=SAMPLES)
    output:  "profile/jgi/{frags}/{group}.{type,mpl|var}"
    params:  lambda w: "" if w.type == "var" else "--noIntraDepthVariance"
    log:     "profile/jgi/{frags}/{group}.log"
    message: "Calculating depths for {wildcards.frags} contigs from {wildcards.group}"
    shell:   "{SOFT}/metabat/jgi_summarize_bam_contig_depths {params}"
             " --outputDepth {output} {input} >{log} 2>&1"

rule convert:
    input:   expand("profile/jgi/{frags}/{group}.{type}", frags=FRAGS, group=GROUPS, type=PROF_TYPE)
    output:  "binning/profiles.tsv"
    message: "Converting JGI profiles into unified format"
    run:
        shell("rm -f {output}")
        for sample_ann in input:
            sample, _ = os.path.splitext(os.path.basename(sample_ann))
            shell("tail -q -n +2 {sample_ann} | cut -f1,4- | sed -e 's/^/{sample}-/' >>{output}")
