# AUTOGENERATED! DO NOT EDIT! File to edit: u01_kallisto.ipynb (unless otherwise specified).

__all__ = ['kallisto_quant_merge']

# Cell

import pandas as pd

# Cell

def kallisto_quant_merge(prefix,abundances,samples):
    '''
    Merge kallisto quant results

    :param str prefix: output prefix, outputs contain two files: prefix_count.tsv and prefix_tpm.tsv
    :param list[str] abundances: kallisto quant results, e.g. /path/to/1/abundance.tsv /path/to/2/abundance.tsv ...
    :param list[str] samples: sample names consistent with kallisto quant results.

    '''
    if len(abundances) != len(samples):
        raise ValueError('length of abundance files and samples should be the same. len(abundance):'+
                         str(len(abundance))+
                         ', while len(samples):'+
                         str(len(samples)))

    sample = samples.pop(0)
    abundance = abundances.pop(0)
    df = pd.read_csv(abundance,sep='\t')
    count = df[['target_id','est_counts']]
    tpm =  df[['target_id','tpm']]
    count.columns=['Geneid',sample]
    tpm.columns=['Geneid',sample]
    for ab,sa in zip(abundances,samples):
        print(f'Reading {ab}')
        tmp_df = pd.read_csv(ab,sep='\t')
        tmp_count = tmp_df[['target_id','est_counts']]
        tmp_tpm =  tmp_df[['target_id','tpm']]
        tmp_count.columns=['Geneid',sa]
        tmp_tpm.columns=['Geneid',sa]
        count = count.merge(tmp_count,how='outer',on='Geneid')
        tpm = tpm.merge(tmp_tpm,how='outer',on='Geneid')
    tpm.to_csv(f'{prefix}_tpm.tsv',sep='\t',index=False)
    count= count.set_index('Geneid')
    count = count.astype(int)
    count.to_csv(f'{prefix}_count.tsv',sep='\t')