Skip to content
Snippets Groups Projects
parse_motif_search.py 23.3 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
#!/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 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'
        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'
                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 + ' ' + 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'
# 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)