#!/usr/bin/env python 
"""
master script to control different operations in training examples generating pipeline.

usage:
    python experiment_run.py <YAML config> -h 

    sample yaml config file located at config/

requirement:
    pygridtools for distributed computing 
    packages/modules depends on the operation  
"""

import os 
import sys 
import yaml 

try:
    import libpyjobrunner as pg
except:
    sys.stdout.write('warning: pygridtools are not available, distributed computing task will be disrupted\n')

from optparse import OptionParser
from signal_labels import experiment_details_db as expdb

assert sys.version_info[:2] >= ( 2, 4 )

def main():
    """
    Managing the exper
iment run in different operation mode: 

    Options

    -1 download_sra file from NCBI SRA service
    -d decompose_sra decompress the SRA file  
    -a annotation fetch genome annotation file from public database servers mainly ensembl, phytozome 
    -g genome fet
ch genome sequence file from public database

    manual cleaning of genome sequence and annotation 
    
    -2 genome_index create genome indices for STAR alignment 
    -i insert_size calculate the insert size based on the raw fastq files  
    -3 read_mapping aligning reads to the genome using STAR aligner 
    -m multi_map resolving the right place for read mapped in multiple location on the genome
    -u uniq_read recover uniquely aligned reads from the star alignment 
    -4 trsk_pred transcript prediction using TranscriptSkimmer
    -c cuff_pred transcript assembly by Cufflinks 
    -s stringtie_pred transcript assembly by StringTie
    -5 filter_trsk applying filter to the trsk predicted gene models 
    -b filter_cuff applying filter to the cufflinks predicted gene models 
    -f filter_db applying filter to the online db genome annotations
    -6 trsk_label generating labels for genomic signal based on the trsk feature annotation  
    -t cuff_label generating labels for genomic signal based on the cufflinks feature annotation 
    -p db_label generating labels for genomic signal based on online db annotations
    """

    parser = OptionParser(usage='usage: %prog <YAML config> [required option]') 

    parser.add_option( "-1", "--download_sra", action="store_true", dest="download_sra", default=False, help="Download sra file based on run id from NCBI SRA/ENA repositories.")
    parser.add_option( "-d", "--decompose_sra", action="store_true", dest="decompose_sra", default=False, help="Decompress the sra file according to the library type.")
    parser.add_option( "-a", "--annotation", action="store_true", dest="annotation", default=False, help="Download genome annotation from public database resources.")
    parser.add_option( "-g", "--genome", action="store_true", dest="genome", default=False, help="Download genome sequence from public database resources.")
    parser.add_option( "-2", "--genome_index", action="store_true", dest="genome_index", default=False, help="Create STAR genome index based on genome sequence and annotations." )
    parser.add_option( "-i", "--insert_size", action="store_true", dest="insert_size", default=False, help="Calculate the library insert size from fastq files.")
    parser.add_option( "-3", "--read_mapping", action="store_true", dest="read_mapping", default=False, help="RNASeq read mapping to genome using STAR aligner." )
    parser.add_option( "-m", "--multi_map", action="store_true", dest="multi_map", default=False, help="MMR on aligned reads to resolve multimapping of reads." )
    parser.add_option( "-u", "--uniq_read", action="store_true", dest="uniq_read", default=False, help="Fetching uniquely mapped reads from bam file." )
    parser.add_option( "-4", "--trsk_pred", action="store_true", dest="trsk_pred", default=False, help="Transcript prediction using TranscriptSkimmer." )
    parser.add_option( "-c", "--cuff_pred", action="store_true", dest="cuff_pred", default=False, help="Transcript assembly using Cufflinks." )
    parser.add_option( "-s", "--stringtie_pred", action="store_true", dest="stringtie_pred", default=False, help="Transcript assembly using StringTie." )
    parser.add_option( "-5", "--filter_trsk", action="store_true", dest="filter_trsk", default=False, help="Apply filters to trsk predicted gene models." )
    parser.add_option( "-b", "--filter_cuff", action="store_true", dest="filter_cuff", default=False, help="Apply filter to the cufflinks predicted gene models." )
    parser.add_option( "-f", "--filter_db", action="store_true", dest="filter_db", default=False, help="Apply filter to the online db annotation gene models." )
    parser.add_option( "-6", "--trsk_label", action="store_true", dest="trsk_label", default=False, help="Fetch label sequences from TranscriptSkimmer annotations." )
    parser.add_option( "-t", "--cuff_label", action="store_true", dest="cuff_label", default=False, help="Fetch label sequences from cufflinks annotations." )
    parser.add_option( "-p", "--db_label", action="store_true", dest="db_label", default=False, help="Fetch label sequences from public online db annotation files." )

    ( options, args ) = parser.parse_args()
    try:
        config_file = args[0]
    except:
        exit(__doc__)

    if not (options.download_sra ^ options.decompose_sra ^ options.annotation ^ \
            options.genome ^ options.genome_index ^ options.insert_size ^ \
            options.read_mapping ^ options.multi_map ^ options.uniq_read ^ \
            options.trsk_pred ^ options.cuff_pred ^ options.filter_trsk ^ \
            options.trsk_label ^ options.filter_cuff ^ options.filter_db ^ \
            options.cuff_label ^ options.db_label ^ options.stringtie_pred):
        parser.print_help()
        sys.exit(-1)
        
    print('Using config file %s for the experiment.' % config_file)

    if options.download_sra:
        print 'Operation selected: Download sequencing reads file from ncbi-sra'
        download_sra_data(config_file)
    elif options.decompose_sra:
        print 'Operation selected: Decompress sra file'
        decompose_sra_file(config_file)
    elif options.annotation:
        print 'Operation selected: Downloading genome annotation file'
        download_gtf(config_file)
    elif options.genome:
        print 'Operation selected: Downloading genome sequence file'
        download_fasta(config_file)
    elif options.genome_index:
        print 'Operation selected: Create STAR genome index'
        create_genome_index(config_file)
    elif options.insert_size:
        print 'Operation selected: Calculate the library insert size from sequencing \
            read files'
        calculate_insert_size(config_file)
    elif options.read_mapping: 
        print 'Operation selected: Read alignment with STAR'
        align_rnaseq_reads(config_file)
    elif options.multi_map:
        print 'Operation selected: Multiple read mapper resolution with MMR'
        alignment_filter(config_file) 
    elif options.uniq_read:
        print 'Operation selected: Find uniquely mapped reads from star alignment'
        find_uniq_reads(config_file) 
    elif options.trsk_pred:
        print 'Operation selected: Transcript prediction based on mapped RNASeq read \
            data with TranscriptSkimmer'
        transcript_prediction_trsk(config_file)
    elif options.cuff_pred:
        print 'Operation selected: Transcript assembly based on mapped RNASeq read data \
            with Cufflinks'
        transcript_prediction_cuff(config_file)
    elif options.stringtie_pred:
        print 'Operation selected: Transcript assembly based on mapped RNASeq read data \
            with StringTie'
        transcript_prediction_stringtie(config_file)
    elif options.filter_trsk:
        print 'Operation selected: Filter out gene models from TranscriptSkimmer \
            predictions - criteria: splice-site consensus and length of the ORF.'
        filter_genes(config_file, "trsk")
    elif options.filter_cuff:
        print 'Operation selected: Filter out gene models from cufflinks predictions - \
            criteria: splice-site consensus, length of the ORF and read coverage to the \
            region.'
    