Class: BacterialComparator

Inherits:
Object
  • Object
show all
Defined in:
lib/bacterial-comparator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, root) ⇒ BacterialComparator

Initialize BacterialAnnotator options, options, ROOT, options, options)



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
# File 'lib/bacterial-comparator.rb', line 20

def initialize options, root

  @root = root
  @outdir = File.expand_path(File.dirname(options[:outdir])) + "/#{File.basename(options[:outdir])}"
  Dir.mkdir(@outdir) if ! Dir.exists? @outdir
  @genomes_list = options[:genomes_list]
  @proc = options[:proc].to_i
  @phylo_nb_genes = options[:phylo_nb_genes]
  if ["fasttree","raxml"].include? options[:software]
    @software = options[:software]
  else
    @software = "fasttree"
  end

  min_cov = options[:min_cov].to_f
  min_pid = options[:pidentity].to_f
  if min_cov > 1
    min_cov = min_cov/100
  end
  if min_pid > 1
    min_pid = min_pid/100
  end

  @aln_opt = options[:align].downcase
  @run_phylo = 0
  if options[:phylogeny] == 1
    @bootstrap = options[:bootstrap]
    @run_phylo = 1
  end

  @ref_prot = get_ref_prot
  @synteny = read_prot_synteny
  @stats = extract_syntenic_fasta min_cov, min_pid

end

Instance Attribute Details

#genomes_listObject (readonly)

Returns the value of attribute genomes_list.



16
17
18
# File 'lib/bacterial-comparator.rb', line 16

def genomes_list
  @genomes_list
end

#statsObject (readonly)

Returns the value of attribute stats.



16
17
18
# File 'lib/bacterial-comparator.rb', line 16

def stats
  @stats
end

Instance Method Details

#build_multifasta(synteny_list) ⇒ Object



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
# File 'lib/bacterial-comparator.rb', line 127

def build_multifasta synteny_list

  pep_out_dir = "#{@outdir}/align-genes-pep"

  ref_proteins = load_genome_cds(Dir["#{@genomes_list[0]}/*.pep"][0])
  synteny_list.each do |k,v|
    pep_out = File.open(pep_out_dir+"/#{k}.pep", "w")
    pep_out.write(ref_proteins[k])
    pep_out.close
  end

  @genomes_list.each_with_index do |g,i|

    genome_proteins = load_genome_cds("#{g}/Proteins.fa")
    synteny_list.each do |k,v|
      pep_out = File.open(pep_out_dir+"/#{k}.pep", "a")
      pep_out.write(genome_proteins[v[i][:query_prot]])
      pep_out.close
    end

  end

  dna_out_dir = "#{@outdir}/align-genes-dna"
  ref_genes = load_genome_cds(Dir["#{@genomes_list[0]}/*.dna"][0])
  synteny_list.each do |k,v|
    dna_out = File.open(dna_out_dir+"/#{k}.dna", "w")
    dna_out.write(ref_genes[k])
    dna_out.close
  end

  @genomes_list.each_with_index do |g,i|

    genome_genes = load_genome_cds("#{g}/Genes.fa")
    synteny_list.each do |k,v|
      dna_out = File.open(dna_out_dir+"/#{k}.dna", "a")
      dna_out.write(genome_genes[v[i][:query_prot]])
      dna_out.close
    end

  end

end

#concat_alignments(outfile, ref_id) ⇒ Object



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
# File 'lib/bacterial-comparator.rb', line 355

def concat_alignments outfile, ref_id

  if File.exists?("#{outfile}") and File.size("#{outfile}") > 0
    puts "..Alignment concatenated file already exists, skipping."
    return
  end

  fout = File.open("#{outfile}", "w")

  seq = ""
  aln_dir = outfile.split(".")[0..-3].join(".")

  Dir["#{aln_dir}/*.aln"].each do |f|
    flat = Bio::FlatFile.auto(f)
    ref_seq = flat.entries[0]
    flat.close
    seq += ref_seq.seq
  end

  bioseq = Bio::Sequence.auto(seq)
  out = bioseq.output_fasta("#{ref_id}", 60)
  fout.write(out)

  for i in 1..@genomes_list.length
    seq = ""
    Dir["#{aln_dir}/*.aln"].each do |f|
      flat = Bio::FlatFile.auto(f)
      j=0
      flat.each_entry do |entry|
        if j<i
          j+=1
          next
        elsif i == j
          seq += entry.seq
          j+=1
        else
          break
        end
      end
      flat.close
    end
    bioseq = Bio::Sequence.auto(seq)
    # get the file name without path prefix and extension
    genome_name = genomes_list[i-1].split("/")[-1].split(".")[0]
    out = bioseq.output_fasta(genome_name,60)
    fout.write(out)
  end

  fout.close

end

#extract_syntenic_fasta(min_cov, min_pid) ⇒ Object

extract and dump multifasta for syntenic genes and proteins



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
# File 'lib/bacterial-comparator.rb', line 171

def extract_syntenic_fasta min_cov, min_pid

  puts "# Extracting Proteins and Genes multifasta  START.."
  start_time = Time.now

  nb_of_syntenic = 0
  stats = {}
  stats[:syntenic] = []
  fout = File.open("#{@outdir}/cds-synteny.tsv", "w")
  genomes_name = []
  @genomes_list.each do |g|
    genomes_name.push(File.basename(g))
  end
  fout.write("Gene\t"+genomes_name.join("\t")+"\n")

  to_build_multifasta = []

  @synteny.each do |k,v|

    is_syntenic = 1
    v.each do |v_|
      if v_[:query_cov] == "-"
        is_syntenic = 0
        break
      elsif v_[:query_cov] > min_cov and
           v_[:ref_cov] > min_cov and
           v_[:pId] > min_pid
      # synteny -> great !
      else
        is_syntenic = 0
        break
      end
    end

    fout.write("#{k}")
    if is_syntenic == 1
      nb_of_syntenic += 1
      # build_multifasta k, v
      to_build_multifasta << [k,v]
      v.each do |x|
        fout.write("\t#{x[:query_prot]}|#{x[:pId]}|#{x[:query_cov]}|#{x[:ref_cov]}")
        stats[:syntenic] << k
      end
      fout.write("\n")
    else
      v.each do |x|
        if x[:pId] == 0.0
          fout.write("\t-")
        else
          fout.write("\t#{x[:query_prot]}|#{x[:pId]}|#{x[:query_cov]}|#{x[:ref_cov]}")
        end
      end
      fout.write("\n")
    end

  end

  fout.close

  pep_out_dir = "#{@outdir}/align-genes-pep"
  dna_out_dir = "#{@outdir}/align-genes-dna"
  Dir.mkdir(pep_out_dir) if ! Dir.exists? pep_out_dir
  Dir.mkdir(dna_out_dir) if ! Dir.exists? dna_out_dir

  synteny_list = to_build_multifasta.each_slice((to_build_multifasta.length/@proc)+1).to_a

  Parallel.map(synteny_list, in_processes: @proc) { |list|
    build_multifasta list
  }

  end_time = Time.now
  c_time = Helper.sec2str(end_time-start_time)
  puts "# Extracting Proteins and Genes multifasta  [DONE] (in #{c_time})"

  stats[:nb_of_syntenic] = nb_of_syntenic
  #puts "   Syntenic genes : " + nb_of_syntenic.to_s + " / " + @ref_prot.length.to_s

end

#fasttree_tree_dna(bt) ⇒ Object



457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/bacterial-comparator.rb', line 457

def fasttree_tree_dna bt
  puts "# Genes DNA tree creation (FastTree)  START.."
  start_time = Time.now
  ori_dir = Dir.pwd
  Dir.chdir(@outdir)
  Dir.mkdir("tree-genes-dna") if ! Dir.exists?("tree-genes-dna")
  current_dir = Dir.pwd
  cmd = system("export OMP_NUM_THREADS=#{@proc} && #{@root}/fasttree.linux -nosupport -fastest -nt -gtr align-genes-dna.all.fasta > tree-genes-dna.nwk")
  Dir.chdir(ori_dir)
  end_time = Time.now
  c_time = Helper.sec2str(end_time-start_time)
  puts "# Genes DNA tree creation (FastTree)  [DONE] (in #{c_time})"
end

#fasttree_tree_pep(bt) ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/bacterial-comparator.rb', line 472

def fasttree_tree_pep bt
  puts "# Proteins AA tree creation (FastTree)  START.."
  start_time = Time.now
  ori_dir = Dir.pwd
  Dir.chdir(@outdir)
  Dir.mkdir("tree-genes-pep") if ! Dir.exists?("tree-genes-pep")
  current_dir = Dir.pwd
  cmd = system("export OMP_NUM_THREADS=#{@proc} && #{@root}/fasttree.linux -nosupport -fastest align-genes-pep.all.fasta > tree-proteins-aa.nwk")
  Dir.chdir(ori_dir)
  end_time = Time.now
  c_time = Helper.sec2str(end_time-start_time)
  puts "# Proteins AA tree creation (FastTree)  [DONE] (in #{c_time})"
end

#get_ref_protObject



98
99
100
101
102
103
104
105
106
107
# File 'lib/bacterial-comparator.rb', line 98

def get_ref_prot
  ref_prot = []
  pep_file = Dir["#{@genomes_list[0]}/*.pep"]
  flatfile = Bio::FlatFile.auto("#{pep_file[0]}")
  flatfile.each_entry do |entry|
    ref_prot << entry.definition.split(" ")[0]
  end
  flatfile.close
  ref_prot
end

#load_genome_cds(file) ⇒ Object

load all id => sequences from multifasta



111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/bacterial-comparator.rb', line 111

def load_genome_cds file

  proteins = {}
  flatfile = Bio::FlatFile.auto(file)
  flatfile.each_entry do |entry|
    name = entry.definition.split(" ")[0]
    bioseq = Bio::Sequence.auto(entry.seq)
    out = bioseq.output_fasta("#{name}",60)
    proteins[name] = out
  end

  proteins

end

#mafft_align(f) ⇒ Object



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/bacterial-comparator.rb', line 250

def mafft_align f

  trying = 0
  begin
    cmd = system("#{@root}/mafft.linux --quiet #{f} > #{f}.aln")
    if File.size("#{f}.aln") == 0
      puts "File size of 0.. --#{f}--"
      puts "Command used : #{@root}/mafft.linux --quiet #{f} > #{f}.aln"
      fail
    else
      status = "OK"
      status = "FAILED" if cmd != true
      # puts "Alignment #{f} : #{status}"
    end
  rescue
    if trying < 3
      trying += 1
      retry
    end
    status = "FAILED"
    puts "Alignment #{f} : #{status}"
  end

end

#mafft_align_all_dnaObject



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
# File 'lib/bacterial-comparator.rb', line 315

def mafft_align_all_dna

  puts "# Sequence alignments - individual genes dna (MAFFT)  START.."
  start_time = Time.now

  ori_dir = Dir.pwd
  Dir.chdir("#{@outdir}/align-genes-dna/")

  is_done = 1
  if Dir["*.dna"].length == Dir["*.aln"].length
    Dir["*.aln"].each do |a|
      if File.size(a) == 0
        is_done = 0
      end
    end
  else
    is_done = 0
  end

  if is_done == 0
    Parallel.map(Dir["*.dna"], in_processes: @proc) { |f|
      mafft_align f
    }
  end

  # ugly hack to find out the reference genome FIXME
  Dir.chdir(ori_dir)
  ref_id = Dir["#{@genomes_list[0]}/*.pep"][0].split('/')[-1].gsub(".pep","")

  end_time = Time.now
  c_time = Helper.sec2str(end_time-start_time)
  puts "# Sequence alignments - individual genes dna (MAFFT)  [DONE] (in #{c_time})"

  concat_alignments "#{@outdir}/align-genes-dna.all.fasta", ref_id

  Dir.chdir(ori_dir)

end

#mafft_align_all_pepObject



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
# File 'lib/bacterial-comparator.rb', line 276

def mafft_align_all_pep

  puts "# Sequence alignments - individual proteins a.a. (MAFFT)  START.."
  start_time = Time.now

  ori_dir = Dir.pwd
  Dir.chdir("#{@outdir}/align-genes-pep/")

  is_done = 1
  if Dir["*.pep"].length == Dir["*.aln"].length
    Dir["*.aln"].each do |a|
      if File.size(a) == 0
        is_done = 0
      end
    end
  else
    is_done = 0
  end

  if is_done==0
    Parallel.map(Dir["*.pep"], in_processes: @proc) { |f|
      mafft_align f
    }
  end

  end_time = Time.now
  c_time = Helper.sec2str(end_time-start_time)
  puts "# Sequence alignments - individual proteins a.a. (MAFFT)  [DONE] (in #{c_time})"

  # FIXME ugly hack to find out the reference genome
  Dir.chdir(ori_dir)
  ref_id = Dir["#{@genomes_list[0]}/*.pep"][0].split('/')[-1].gsub(".pep","")

  concat_alignments "#{@outdir}/align-genes-pep.all.fasta", ref_id

  Dir.chdir(ori_dir)

end

#raxml_tree_dna(bt) ⇒ Object



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/bacterial-comparator.rb', line 420

def raxml_tree_dna bt
  puts "# Genes DNA tree creation (RAXML)  START.."
  start_time = Time.now
  ori_dir = Dir.pwd
  Dir.chdir(@outdir)
  Dir.mkdir("tree-genes-dna") if ! Dir.exists?("tree-genes-dna")
  current_dir = Dir.pwd
  tree_dir = "#{current_dir}/tree-genes-dna"
  cmd = system("#{@root}/raxml.linux -T #{@proc} -f d -N #{bt} -s align-genes-dna.all.fasta  -m GTRGAMMA -p 123454321 -n DnaTree -w #{tree_dir} > /dev/null 2>&1")
  cmd = system("cat #{tree_dir}/RAxML_result.DnaTree.RUN.* >> #{tree_dir}/RAxML_result.BS")
  cmd = system("#{@root}/raxml.linux -T #{@proc} -f b -z #{tree_dir}/RAxML_result.BS -t #{tree_dir}/RAxML_bestTree.DnaTree -m GTRGAMMA -n DNA_BS_TREE -w #{tree_dir} > /dev/null 2>&1")
  cmd = system("ln -s #{tree_dir}/RAxML_bipartitionsBranchLabels.DNA_BS_TREE #{tree_dir}/../tree-genes-dna.nwk")
  Dir.chdir(ori_dir)
  end_time = Time.now
  c_time = Helper.sec2str(end_time-start_time)
  puts "# Genes DNA tree creation (RAXML)  [DONE] (in #{c_time})"
end

#raxml_tree_pep(bt) ⇒ Object



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/bacterial-comparator.rb', line 438

def raxml_tree_pep bt
  puts "# Proteins AA tree creation (RAXML)  START.."
  start_time = Time.now
  ori_dir = Dir.pwd
  Dir.chdir(@outdir)
  Dir.mkdir("tree-genes-pep") if ! Dir.exists?("tree-genes-pep")
  current_dir = Dir.pwd
  tree_dir = "#{current_dir}/tree-genes-pep"
  cmd = system("#{@root}/raxml.linux -T #{@proc} -f d -N #{bt} -s align-genes-pep.all.fasta  -m PROTGAMMAAUTO -p 123454321 -n PepTree -w #{tree_dir} > /dev/null 2>&1")
  cmd = system("cat #{tree_dir}/RAxML_result.PepTree.RUN.* >> #{tree_dir}/RAxML_result.BS")
  cmd = system("#{@root}/raxml.linux -T #{@proc} -f b -z #{tree_dir}/RAxML_result.BS -t #{tree_dir}/RAxML_bestTree.PepTree -m PROTGAMMAAUTO -n PEP_BS_TREE -w #{tree_dir} > /dev/null 2>&1")
  cmd = system("ln -s #{tree_dir}/RAxML_bipartitionsBranchLabels.PEP_BS_TREE #{tree_dir}/../tree-proteins-aa.nwk")
  Dir.chdir(ori_dir)
  end_time = Time.now
  c_time = Helper.sec2str(end_time-start_time)
  puts "# Proteins AA tree creation (RAXML)  [DONE] (in #{c_time})"
end

#read_prot_syntenyObject



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
# File 'lib/bacterial-comparator.rb', line 66

def read_prot_synteny

  puts "# Reading genome synteny files START.."
  start_time = Time.now
  synteny = {}
  @genomes_list.each do |g|
    genome_synteny = []
    file = File.open("#{g}/Prot-Synteny.tsv", "r")
    l = file.gets             # skip header
    while l = file.gets
      # AAK98805.1      spr0001 453     1.0     100.0   ABAC01000005_14 453     1.0 1|0
      lA = l.chomp.split("\t")
      synteny[lA[0]] =  [] if ! synteny.has_key? lA[0]
      synteny[lA[0]] << {ref_cov: lA[3].to_f, pId: lA[4].to_f, query_prot: lA[5], query_cov: lA[7].to_f}
      genome_synteny << lA[0]
    end
    @ref_prot.each do |ref_prot|
      if ! genome_synteny.include? ref_prot
        synteny[lA[0]] << {ref_cov: "-", pId: "-", query_prot: "-", query_cov: "-"}
      end
    end
    file.close
  end
  end_time = Time.now
  c_time = Helper.sec2str(end_time-start_time)

  puts "# Reading genome synteny files [DONE] (in #{c_time})"

  synteny

end

#run_comparisonObject



57
58
59
60
61
62
63
# File 'lib/bacterial-comparator.rb', line 57

def run_comparison

  run_mafft_aln

  run_phylo if @run_phylo != 0

end

#run_mafft_alnObject



407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/bacterial-comparator.rb', line 407

def run_mafft_aln

  if @aln_opt == "both"
    mafft_align_all_pep
    mafft_align_all_dna
  elsif @aln_opt == "prot"
    mafft_align_all_pep
  elsif @aln_opt == "dna"
    mafft_align_all_dna
  end

end

#run_phyloObject



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/bacterial-comparator.rb', line 487

def run_phylo

  if @software == "raxml"
    if @aln_opt == "both"
      raxml_tree_dna @bootstrap
      raxml_tree_pep @bootstrap
    elsif @aln_opt == "prot"
      raxml_tree_pep @bootstrap
    elsif @aln_opt == "dna"
      raxml_tree_dna @bootstrap
    end
  elsif @software == "fasttree"
    if @aln_opt == "both"
      fasttree_tree_dna @bootstrap
      fasttree_tree_pep @bootstrap
    elsif @aln_opt == "prot"
      fasttree_tree_pep @bootstrap
    elsif @aln_opt == "dna"
      fasttree_tree_dna @bootstrap
    end
  end

end