configfile: 'config.yml'

GENOMES, = glob_wildcards("fna/{genome}.fna")

#localrules: all,  make_path, calc_complexity



def aggregate_input(wildcards):
    return expand("Results/ortho/coreogs_aligned/{og}.fasta.iqtree",
                og=glob_wildcards(os.path.join("Results/ortho/coreogs/", "{og}.fasta")).og )

rule all:
	input: aggregate_input

rule tree_for_core:
	input:
		"Results/ortho/coreogs_aligned/{og}.fasta"	
	output:
		"Results/ortho/coreogs_aligned/{og}.fasta.iqtree"
	shell:
		"{config[iqtree.bin]} -s {input}"

rule align_core:
	input:
		"Results/ortho/coreogs/{og}.fasta"
	output:
		"Results/ortho/coreogs_aligned/{og}.fasta"
	shell:
		"scripts/./muscle -in {input} -out {output} -quiet"
	
checkpoint makeCoreOGfastas:
	input:
		og="Results/ortho/Orthogroups.txt",
		coreOg="Results/ortho/SingleCopyOrthogroups.txt",
		ffns=expand("ffn/{qu}.fasta", qu=GENOMES)
	output:
		coreog=directory("Results/ortho/coreogs/")
	shell:
		"""
		cat ffn/*.fasta > tmp/all_genes.fasta
		mkdir -p Results/ortho/coreogs
		perl scripts/splitToOg.pl Results/ortho/Orthogroups.txt tmp/all_genes.fasta Results/ortho/coreogs Results/ortho/SingleCopyOrthogroups.txt
		"""		

rule orthofinder:
	input: 
		expand("faa/{qu}.fasta", qu=GENOMES)
	output:
		"Results/ortho/Orthogroups.txt"
	threads: 4
	conda: "envs/ortho.yaml"
	log: "log_of.txt"
	shell:
		"bash scripts/run_orthofinder.sh {threads} > {log}"
rule prokka:
	input:
		ancient("fna/{qu}.fna")
	output:
		directory("prokka/{qu}")
	threads: 4
	conda: "envs/prokka.yaml"
	shell:
		"""
		name=$(basename {input} .fna);
		prokka --cpus {threads} --outdir {output} --force --prefix $name --locustag $name {input}
		"""

rule make_faa:
	input:
		ancient("prokka/{qu}")
	output:
		"faa/{qu}.fasta"
	conda: "envs/scripts.yaml"
	shell:
		"""
		name=$(basename {input})
		python3 scripts/GBfaa.py -gb  {input}/$name.gbk > {output}
		"""
