#!/usr/bin/env python
"""

Copyright (c) 2015, Konrad Foerstner <konrad@foerstner.org>

Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all
copies.

THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
 
"""
__description__ = ""
__author__ = "Konrad Foerstner <konrad@foerstner.org>"
__copyright__ = "2015 by Konrad Foerstner <konrad@foerstner.org>"
__license__ = "ISC license"
__email__ = "konrad@foerstner.org"
__version__ = ""


import argparse
from collections import defaultdict
import pandas as pd
import matplotlib
matplotlib.use('Agg')
from scipy import stats


def main():
    parser = argparse.ArgumentParser(description=__description__)
    parser.add_argument("edger_files", nargs="+")
    args = parser.parse_args()
    time_course_correlator = TimeCourseCorrelator(args.edger_files)
    time_course_correlator.read_edger_result_files()
    time_course_correlator.calc_correlation_values()


class TimeCourseCorrelator(object):

    def __init__(self, edger_files):
        self._edger_files = edger_files
        self._genes_and_log2foldchanges = defaultdict(list)

    def read_edger_result_files(self):

        for index, edger_file in enumerate(self._edger_files):
            edger_results = pd.read_table(edger_file, comment="#")
            edger_results["Gene_name"] = edger_results[
                "Unnamed: 0"].apply(lambda x: x.split("|")[1])
            edger_results["Gene_start"] = edger_results[
                "Unnamed: 0"].apply(lambda x: x.split("|")[2])
            edger_results = edger_results.sort("Gene_name")
            for index, row in edger_results.iterrows():
                # Needed as some genes occure more than once
                gene_name = row["Gene_name"]
                if gene_name != "pinT":
                    gene_name = row["Gene_name"] + ":::" + row["Gene_start"]
                self._genes_and_log2foldchanges[
                    gene_name].append(row["logFC"])

    def calc_correlation_values(self):
        stnc440_counting = [0.0] + self._genes_and_log2foldchanges["pinT"]
        print("Gene\tPearson_corr_coeff\tp_value\tUnderlying values")
        for gene, countings in self._genes_and_log2foldchanges.items():
            gene = gene.split(":::")[0]
            # Add the values of the 0 h to anchor the distribution
            countings = [0.0] + countings
            corr_coeff, p_value = stats.pearsonr(stnc440_counting, countings)
            print("{}\t{}\t{}\t{}".format(
                gene, corr_coeff, p_value,
                ",".join([str(counting) for counting in countings])))

main()
