Skip to content
Snippets Groups Projects
parse_motif_search.py 24.2 KiB
Newer Older
#!/usr/bin/env python
import csv
from collections import defaultdict
import sys, getopt
import os
import math
from shutil import copyfile
import pandas as pd
from scipy.stats import chi2
from Bio import SeqIO
import os.path


SOFTWARES = {'meme','dreme','centrimo','meme_tomtom'}
##TYPES_SEARCHES = {'All','Narrow','Const','Max'}


def get_size_fasta(path_motif, exp_design_name):
    with open(path_motif + 'Fasta_Summary.txt', 'w') as fasta_summary:
        for data_name in os.listdir(path_motif+'fasta/'):
            if data_name.endswith('.fasta'):
                print(data_name)
                fasta_seq = SeqIO.to_dict(SeqIO.parse(path_motif+'fasta/'+data_name, "fasta"))
                print(data_name,len(fasta_seq))
                fasta_summary.write(data_name.replace('.fasta','')+'\t'+str(len(fasta_seq))+'\n')


def parse_all_logs(path_motif, exp_design_name):
    with open(path_motif + '../Motif_search.log', 'w') as general_log:
        header = 'Data_name\t' + '\t'.join(SOFTWARES)
        general_log.write(header+'\n')
        for data_name in os.listdir(path_motif):
            if not data_name.startswith('.') and not data_name.endswith('.log') and not data_name.endswith('.sh'):
                progress_filename = path_motif + data_name + '/progress_log.txt'
                line = data_name + '\t'
                for software in SOFTWARES:
                    found = False
                    with open(progress_filename,'r') as file:
                        for row in file:
                            status_soft = 'name: '+software+'  status: 0'
                            if status_soft in row:
                                found = True
                    if found:
                        line += '1\t'
                    else:
                        line += '0\t'
                general_log.write(line.strip() + '\n')


def parse_dreme(path_motif, exp_design_name):
    with open(path_motif + 'dreme.sh', 'w') as dreme_file:
        for data_name in os.listdir(path_motif):
            if exp_design_name in data_name:
                print(data_name)
                if not data_name.startswith('.') and not data_name.endswith('.log') and not data_name.endswith('.sh'):
                    # print(data_name)
                    dreme_xml = path_motif + data_name + '/dreme_out/dreme.xml'
                    if os.path.exists(dreme_xml):
                        dreme_list = list()
                        with open(dreme_xml, 'r') as file:
                            for row in file:
                                dreme_list.append(row.strip())
                                if '<command_line>' in row:
                                    dreme_file.write(row)

                        dreme_txt = path_motif + data_name + '/dreme_out/dreme.txt'
                        dreme_txt_list = list()
                        with open(dreme_txt, 'r') as file:
                            for row in file:
                                dreme_txt_list.append(row.strip())
                        dreme_txt_intro = ''
                        write_intro = False
                        for row in dreme_txt_list:
                            if row.startswith('MOTIF '):
                                break
                            if 'MEME version' in row:
                                write_intro = True
                            if write_intro:
                                dreme_txt_intro += row + '\n'

                        #print(dreme_txt_intro)

                        # parse dreme
                        with open(path_motif + '../logs/Dreme_' + data_name + '.log', 'w') as general_log:
                            header = 'ID\tMotif\tNb_sites\tPos_Occurence\tNeg_Occurence\tNb_Seq\t' \
                                     'Percent\tPos_Percent\tNeg_Percent\tEvalue'
                            general_log.write(header + '\n')
                            # search length fasta
                            for line in dreme_list:
                                if '<positives name=' in line:
                                    number_seq = float(line.split(' ')[2].replace('\"','').replace('count=',''))
                            # search motifs
                            for i in range(1, len(dreme_list)):
                                line = dreme_list[i]
                                if '<motifs>' in line:
                                    index_motifs = i
                                    break

                            # get motifs info
                            for k in range(index_motifs+1, len(dreme_list)):
                                if '<motif' in dreme_list[k]:
                                    new_line = dreme_list[k].replace('\"','').split(' ')
                                    #print(new_line)
                                    id = new_line[1].replace('id=', '')
                                    #print(id,data_name)
                                    print(dreme_txt_intro)
                                    seq = new_line[2].replace('seq=', '')
                                    occ = float(new_line[4].replace('nsites=', ''))
                                    pos_occ = float(new_line[5].replace('p=', ''))
                                    neg_occ = float(new_line[6].replace('n=', ''))
                                    evalue = new_line[8].replace('evalue=', '')

                                    # save table
                                    line_to_write = [id, seq, str(occ), str(pos_occ),str(neg_occ), str(number_seq),
                                                     str(occ/number_seq), str(pos_occ/number_seq), str(neg_occ/number_seq),
                                                     str(evalue)]
                                    general_log.write('\t'.join(line_to_write) + '\n')

                                    # copy png file
                                    for imagefile in os.listdir(path_motif + data_name + '/dreme_out/'):
                                        if id in imagefile:
                                            if 'nc_' in imagefile:
                                                src = path_motif + data_name + '/dreme_out/' + imagefile
                                                dst = path_motif + '../motif_figure/'+seq + '_nc.png'
                                                copyfile(src, dst)
                                            else:
                                                src = path_motif + data_name + '/dreme_out/' + imagefile
                                                dst = path_motif + '../motif_figure/' + seq + '_rc.png'
                                                copyfile(src, dst)

                                    # save motif
                                    with open(path_motif + '../motif/' + seq + '.meme', 'w') as meme_file:
                                        meme_file.write(dreme_txt_intro+'\n')
                                        # find motif info
                                        dreme_txt_motif = ''
                                        write_motif = False
                                        for row in dreme_txt_list:
                                            if write_motif and row.startswith('MOTIF '):
                                                break
                                            if ('MOTIF '+seq+' DREME') in row:
                                                write_motif = True
                                            if write_motif:
                                                dreme_txt_motif += row + '\n'

                                        print(dreme_txt_motif)
                                        meme_file.write(dreme_txt_motif + '\n')


def regroup_motifs(path_motif, exp_design_name):
    motif_set = set()
    dict_dataset = defaultdict(list)
    dict_evalue = defaultdict(list)
    for data_name in os.listdir(path_motif+'logs/'):
        if data_name.startswith('Dreme_') and data_name.endswith('.log'):
            type_data = data_name.replace('Dreme_','').replace('.log','')
            print(type_data,data_name)
            with open(path_motif+'logs/'+data_name,'r') as log_file:
                log_file.readline()
                for line in log_file:
                    motif = line.split('\t')[1]
                    evalue = line.strip().split('\t')[-1]
                    motif_set.add(motif)
                    dict_dataset[motif].append(type_data)
                    dict_evalue[motif].append(evalue)

    with open(path_motif + 'Motif_'+exp_design_name+'.txt','w') as motif_log:
        motif_log.write("Motif\tData\tP-value\n")
        for motif in motif_set:
            motif_log.write(motif+'\t'+';'.join(dict_dataset[motif])+'\t'+';'.join(dict_evalue[motif])+'\n')


def add_motif(path_motif, motif, motif_list_filename):
    motif_file = path_motif + '/motif/' + motif + '.meme'
    motif_figure_file = path_motif + '/motif_figure/' + motif + '_nc.png'
    # Meme-suite as to be installed for using = iupac2meme
    os.system('iupac2meme -dna ' + motif + ' > ' + motif_file)
    # os.system('ceqlogo -i ' + motif_file + ' -m ' + motif + ' -o '+motif_figure_file+' -f png')
    #
    # list_motif = list()
    # with open(path_motif + motif_list_filename + '.txt', 'r') as motif_file:
    #     motif_file.readline()



def regroup_figures(path_motif, motif_list):
    '''
    Create SVG file with all motifs included
    :param path_motif:
    :param motif_list:
    :return:
    '''
    print('Create PNG file with all motifs')
    df_summary = pd.read_csv(path_motif + motif_list + '.txt', sep='\t')
    df_summary = df_summary.sort_values(by=['Motif'], ascending=[True])
    svg_text = '<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Generator: Adobe Illustrator 15.0.0, SVG Export ' \
               'Plug-In . SVG Version: 6.00 Build 0)  -->\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"' \
               'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg version=\"1.1\" id=\"Calque_1\" ' \
               'xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"' \
               ' width=\"1300px\" height=\"'+str(len(df_summary.index)*100)+'px\" viewBox=\"0 0 1300 '\
               +str(len(df_summary.index)*100)+'\" xml:space=\"preserve\">\n'
    i=0
    for index, row in df_summary.iterrows():
        motif = row['Motif']
        data = row['Data']
        pvalue = row['P-value']
        image_file = 'motif_figure/' + motif + '_nc.png'
        new_row = '<image overflow=\"visible\" width=\"299\" height=\"176\" xlink:href=\"'+image_file+'\"  ' \
                    'transform=\"matrix(0.5184 0 0 0.5184 10.00 '+ str(float(100*i))+')\">\n</image>\n'
        image_file = 'motif_figure/' + motif + '_rc.png'
        if os.path.isfile(image_file):
            new_row += '<image overflow=\"visible\" width=\"299\" height=\"176\" xlink:href=\"' + image_file + '\"  ' \
                        'transform=\"matrix(0.5184 0 0 0.5184 170.00 '+ str(float(100*i))+')\">\n</image>\n'
        new_row += '<text transform=\"matrix(0.5184 0 0 0.5184 340 '+ str(float(50+100*i))+')\" font-family=' \
                    '\"\'MyriadPro-Regular\'\" font-size=\"40\">'+data+'</text>\n'
        new_row += '<text transform=\"matrix(0.5184 0 0 0.5184 800 '+ str(float(50+100*i))+')\" font-family=' \
                    '\"\'MyriadPro-Regular\'\" font-size=\"40\">'+pvalue+'</text>\n'
        svg_text += new_row
        i+=1
    svg_text += '</svg>\n'

    with open(path_motif + motif_list + '.svg', 'w') as figure_file:
        figure_file.write(svg_text)
    print('Convert svg to png')
    os.system('convert '+path_motif + motif_list + '.svg '+path_motif + motif_list + '.png')
    os.system('convert '+path_motif + motif_list + '.svg '+path_motif + '../../All_Figures/Motif/' + motif_list + '.png')


def run_fimo(path_motif, path_script, exp_design_name, motif_list_filename, data_list_filename):

    motif_list = list()
    with open(path_motif + motif_list_filename + '.txt', 'r') as motif_file:
        for row in motif_file:
            motif_list.append(row.split('\t')[0].strip())
    data_list = list()
    with open(path_motif + data_list_filename + '.txt', 'r') as data_file:
        for row in data_file:
            data_list.append(row.split('\t')[0].strip())


    with open(path_motif + 'Fimo.sh', 'w') as motif_sh:
        for motif in motif_list:
            motif_file = path_script + 'motif/' + motif + '.meme'
            print(motif_file)
            for data_name in data_list:
                fasta_file = path_script + 'fasta/' + data_name + '.fasta'
                background_file = path_script + 'results/' +  data_name + '/background'
                folder_fimo = path_script + 'fimo/' + motif + '_' + data_name
                fimo_sh = 'fimo --parse-genomic-coord --verbosity 1 --thresh 1e-2 --max-stored-scores 1000000 '\
                          '--oc ' + folder_fimo + ' --bgfile ' + background_file + ' ' + motif_file + ' ' + fasta_file
                print(fimo_sh)
                motif_sh.write(fimo_sh+'\n')


def run_centrimo(path_motif, path_script, exp_design_name, motif_list_filename, data_list_filename):

    motif_list = list()
    with open(path_motif + motif_list_filename + '.txt', 'r') as motif_file:
        for row in motif_file:
            motif_list.append(row.split('\t')[0].strip())
    data_list = list()
    with open(path_motif + data_list_filename + '.txt', 'r') as data_file:
        for row in data_file:
            data_list.append(row.split('\t')[0].strip())


    with open(path_motif + 'Centrimo.sh', 'w') as motif_sh:
        for motif in motif_list:
            motif_file = path_motif + 'motif/' + motif + '.meme'
            print(motif_file)
            for data_name in data_list:
                fasta_file = path_motif + 'fasta/' + data_name + '.fasta'
                folder_centrimo = path_motif + 'centrimo/' + motif + '_' + data_name
                centrimo_sh = 'centrimo -seqlen 100 -verbosity 1 -oc ' + folder_centrimo + ' -score 5.0 '\
                              '-ethresh 10.0 ' + fasta_file + ' '+motif_file
                print(centrimo_sh)
                motif_sh.write(centrimo_sh + '\n')


def parse_fimo(path_motif, exp_design_name, motif_list_filename, data_list_filename):
    motif_list = list()
    with open(path_motif + motif_list_filename + '.txt', 'r') as motif_file:
        for row in motif_file:
            motif_list.append(row.split('\t')[0].strip())
    data_list = list()
    with open(path_motif + data_list_filename + '.txt', 'r') as data_file:
        for row in data_file:
            data_list.append(row.split('\t')[0].strip())
    fasta_to_length = dict()
    with open(path_motif + 'Fasta_Summary.txt', 'r') as fasta_summary:
        for row in fasta_summary:
            fasta_to_length[row.split('\t')[0]] = int(row.strip().split('\t')[1])

    with open(path_motif + 'Fimo_Summary_Max.txt', 'w') as fimo_summary_max, \
            open(path_motif + 'Fimo_Summary_All.txt', 'w') as fimo_summary_all:
        headers = 'Data_Name\tSeq\tData\tTotal_Occurence\tNb_Peaks\tNb_Peaks_Fasta\tRatio\n'
        fimo_summary_max.write(headers)
        fimo_summary_all.write(headers)
        for seq in motif_list:
            for data_type in data_list:
                data_name = seq + '_'+ data_type
                print(data_name)
                if not os.path.exists(path_motif + 'fimo/' + data_name + '/fimo.txt'):
                    print('Cannot find:' + path_motif + 'fimo/' + data_name + '/fimo.txt')
                    print('Create void table to proceed motif algorithm')
                    with open(path_motif + 'fimo_template.txt', 'r') as fimo_file, \
                            open(path_motif + 'fimo/' + data_name + '/fimo.txt', 'w') as fimo_table:
                        fimo_table.write(fimo_file.readline())
                        fimo_table.write(fimo_file.readline())

                with open(path_motif + 'fimo/' + data_name + '/fimo.txt','r') as fimo_file, \
                        open(path_motif + 'fimo/' + data_name + '/fimo_table.txt', 'w') as fimo_table:
                    fimo_table.write('Peak\tOcc\tchi_fisher\tscore\n')
                    fimo_file_csv = csv.DictReader(fimo_file, delimiter='\t')
                    peak_to_value = defaultdict(list)
                    peak_to_occurence = defaultdict(int)
                    for row in fimo_file_csv:
                        value = float(row['score'])
                        if value > 0:
                            peak_to_occurence[row['sequence name']] += 1
                            peak_to_value[row['sequence name']].append(str(row['score']))
                    total_occ = 0
                    for peak, occ in peak_to_occurence.items():
                        chi_fisher = 0
                        for pvalue in peak_to_value[peak]:
                            #chi_fisher += -2 * math.log1p(float(pvalue))
                            chi_fisher += float(pvalue)
                        #print chi_fisher
                        fimo_table.write(peak+'\t'+str(occ)+'\t'+str(chi_fisher)+'\t'+';'.join(peak_to_value[peak])+'\n')
                        total_occ += occ

                    seq = data_name[0:data_name.index('_')]

                    fasta_name = data_name[data_name.index('_')+1:len(data_name)]
                    fasta_length = fasta_to_length[fasta_name]
                    new_line = data_name + '\t' + seq + '\t' + fasta_name + '\t' + str(total_occ) + '\t' \
                               + str(len(peak_to_occurence)) + '\t' + str(fasta_length) + '\t' + \
                               str(total_occ) + '\n'
                    if 'All_' in data_name:
                        fimo_summary_all.write(new_line)
                    else:
                        fimo_summary_max.write(new_line)



def create_motif_table(path_motif, exp_design_name, path_peaks, motif_list_filename, data_list_filename, type_search):
    set_seq = set()
    set_type_data = set()
    df_summary = pd.read_csv(path_motif + 'Fimo_Summary_' + type_search + '.txt', index_col=0, sep='\t')

    motif_list = list()
    with open(path_motif + motif_list_filename + '.txt', 'r') as motif_file:
        for row in motif_file:
            motif_list.append(row.split('\t')[0].strip())
    data_list = list()
    with open(path_motif + data_list_filename + '.txt', 'r') as data_file:
        for row in data_file:
            data_type = row.split('\t')[0].strip()
            data_list.append(data_type)


    set_peaks = set()
    df_peaks = pd.read_csv(path_peaks+ exp_design_name + '_Peaks.txt', index_col=0, sep='\t')
    for index in df_peaks.index:
        set_peaks.add(index)


    for seq in motif_list:
        print(seq)
        with open(path_motif + 'mutual_information/Fimo_Table_' + type_search + '_' + seq + '.txt', 'w') as fimo_table, \
                open(path_motif + 'mutual_information/Fimo_Table_' + type_search + '_' + seq + '_Count.txt', 'w') as fimo_summary:
            header_type_data = list(data_list)
            #header_type_data[0] = 'All'
            fimo_summary.write('Pres_Abs\t' + '\t'.join(header_type_data)+'\n')
            fimo_table.write('Peak\t' + '\t'.join(header_type_data) + '\n')

            peak_to_occ = defaultdict(dict)
            data_to_count = dict()
            for type_data in data_list:
                print(type_data)
                data_name = seq + '_' + type_data
                df_motif = pd.read_csv(path_motif + 'fimo/' + data_name + '/fimo_table.txt', index_col=0, sep='\t')
                count_occ = 0
                for peak in set_peaks:
                    if peak in df_motif.index:
                        peak_to_occ[peak][type_data] = df_motif['chi_fisher'][peak]
                        count_occ += df_motif['chi_fisher'][peak]
                    else:
                        peak_to_occ[peak][type_data] = 0
                data_to_count[type_data] = count_occ

            new_line = 'Present\t'
            for index in data_list:
                new_line += str(data_to_count[index]) + '\t'
            fimo_summary.write(new_line.strip() + '\n')

            for peak in peak_to_occ:
                new_line = peak + '\t'
                for index in data_list:
                    new_line += str(peak_to_occ[peak][index]) + '\t'
                fimo_table.write(new_line.strip() + '\n')


def create_occurence_table(path_motif, exp_design_name, motif_list_filename, data_list_filename, type_search):
    fasta_to_length = dict()
    with open(path_motif + 'Fasta_Summary.txt', 'r') as fasta_summary:
        for row in fasta_summary:
            fasta_to_length[row.split('\t')[0]] = int(row.strip().split('\t')[1])

    motif_list = list()
    with open(path_motif + motif_list_filename + '.txt', 'r') as motif_file:
        for row in motif_file:
            motif_list.append(row.split('\t')[0].strip())
    data_list = list()
    with open(path_motif + data_list_filename + '.txt', 'r') as data_file:
        for row in data_file:
            data_type = row.split('\t')[0].strip()
            data_list.append(data_type)

    with open(path_motif + 'Fimo_Table_' + type_search + '.txt', 'w') as fimo_summary:
        header = 'Sequence\t' + '\t'.join(list(data_list))
        fimo_summary.write(header + '\n')
        for seq in motif_list:
            print(seq)
            df_motif = pd.read_csv(path_motif + 'mutual_information/Fimo_Table_' + type_search + '_' + seq + '_Count.txt'
                                   , index_col=0, sep='\t')

            new_line = seq + '\t'
            print(df_motif.columns)
            for type_data in data_list:
                row_name = seq + '_' + type_search + '_' + exp_design_name + type_data
                length = fasta_to_length[type_data]
                print(length)
                if type_data == '':
                    type_data = 'All'
                value = df_motif[type_data]['Present']
                if length != 0 :
                    new_line += str(float(value)/float(length)) + '\t'
                else:
                    new_line += str(0) + '\t'

            fimo_summary.write(new_line.strip() + '\n')



#exp_design_name = 'LivOld'
exp_design_name = 'CecAm_MaxMaxValues'
#path = '/Users/cbecavin/Documents/m6aAkker/'
path = '/Volumes/m6aAkker/'
path_motif = path + 'PeakDiffExpression/' + exp_design_name + '/Motif/'
path_peaks = path + 'PeakDetection/Peaks/'

if not os.path.isdir(path_motif + 'logs/'):
    os.mkdir(path_motif + 'logs/')
if not os.path.isdir(path_motif + 'motif/'):
    os.mkdir(path_motif + 'motif/')
if not os.path.isdir(path_motif + 'motif_figure/'):
    os.mkdir(path_motif + 'motif_figure/')
if not os.path.isdir(path_motif + 'fimo/'):
    os.mkdir(path_motif + 'fimo/')

#path_script = path + 'PeakDiffExpression/' + exp_design_name + '/Motif/'
path_script = '/pasteur/projets/policy01/m6aAkker/' + 'PeakDiffExpression/' + exp_design_name + '/Motif/'

# get size fasta
#get_size_fasta(path_motif, exp_design_name)
# first look at log to see which software crashed
#parse_all_logs(path_motif+'/results/', exp_design_name)
# Parse meme results and extract all motifs
#parse_dreme(path_motif+'/results/', exp_design_name)
# regroup all motifs
#regroup_motifs(path_motif, exp_design_name)


motif_list_filename = 'Motif_'+exp_design_name+'_Filter'
# add new motif
# motif = 'RRACH'
# add_motif(path_motif, motif, motif_list_filename)
# motif = 'BCA'
# add_motif(path_motif, motif, motif_list_filename)

# put all motifs figures together to filter the list
#regroup_figures(path_motif, motif_list_filename)

data_list_filename = 'list_data_' + exp_design_name
#data_list_filename = 'list_data_All'
# write sh file for running fimo
run_fimo(path_motif, path_script, exp_design_name, motif_list_filename, data_list_filename)
# write sh file for running centrimo
#run_centrimo(path_motif, path_script, exp_design_name, motif_list_filename, data_list_filename)
# parse fimo results
#parse_fimo(path_motif, exp_design_name, motif_list_filename, data_list_filename)


#motif_list_filename = 'list_motifs_All'
#motif_list_filename = 'list_motifs_Max'

#data_list_filename = 'list_data_All'
#data_list_filename = 'list_data_Max'

#type_search = 'All'
#type_search = 'Max'
# create a table for each motif of occurence in list
#create_motif_table(path_motif, exp_design_name, path_peaks, motif_list_filename, data_list_filename, type_search)
# create a table for occurence of each motif
#create_occurence_table(path_motif, exp_design_name, motif_list_filename, data_list_filename, type_search)