Class: SequenceAnnotation

Inherits:
Object
  • Object
show all
Defined in:
lib/bacterial-annotator/sequence-annotation.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root, outdir, file_ref, type) ⇒ SequenceAnnotation

Initialize then genbank file



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 17

def initialize root, outdir, file_ref, type

  @root = root
  @outdir = outdir
  @coding_seq = {}
  @rna_seq = {}

  case type
  when "refGbk"
    # reference genome use for annotation
    reference_gbk file_ref
  when "db"
    # reference database use for annotation
    reference_db file_ref
  when "fasta"
    # single fasta database for annotation (completion)
    single_fasta file_ref
  when "newGbk"
    # new genbank holder to be annotated
    new_gbk file_ref
  end

end

Instance Attribute Details

#cds_fileObject

Returns the value of attribute cds_file.



14
15
16
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 14

def cds_file
  @cds_file
end

#coding_seqObject

Returns the value of attribute coding_seq.



14
15
16
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 14

def coding_seq
  @coding_seq
end

#gbkObject

Returns the value of attribute gbk.



14
15
16
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 14

def gbk
  @gbk
end

#rna_fileObject

Returns the value of attribute rna_file.



14
15
16
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 14

def rna_file
  @rna_file
end

#rna_seqObject

Returns the value of attribute rna_seq.



14
15
16
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 14

def rna_seq
  @rna_seq
end

Instance Method Details

#add_annotation_ref_synteny_prot(synteny_prot, annotations, ref_genome = nil) ⇒ Object

add annotation from reference prot synteny



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
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 365

def add_annotation_ref_synteny_prot synteny_prot, annotations, ref_genome=nil

  contig = @gbk.definition

  prot_iterator = 0
  @gbk.features.each_with_index do |cds, ft_index|

    next if cds.feature != "CDS"

    prot_iterator+=1
    prot_id = contig+"_"+prot_iterator.to_s

    ftArray = []
    cds.qualifiers = []

    hit = nil

    if ! synteny_prot.has_key? prot_id or
       ! synteny_prot[prot_id].has_key? :homology or
       ! annotations.has_key? synteny_prot[prot_id][:homology][:hits][0] or
       synteny_prot[prot_id][:homology][:assert_cutoff].inject(:+) < 3

      qLocusTag = Bio::Feature::Qualifier.new('locus_tag', "#{prot_id}")
      qProd = Bio::Feature::Qualifier.new('product', "hypothetical protein")

      ftArray.push(qLocusTag)
      ftArray.push(qProd)

      if synteny_prot.has_key? prot_id and
        synteny_prot[prot_id].has_key? :homology and
        synteny_prot[prot_id][:homology][:assert_cutoff] == [1,1,0]
        hit = annotations[synteny_prot[prot_id][:homology][:hits][0]]
        qNote = Bio::Feature::Qualifier.new('note', "possible pseudo gene of #{hit[:locustag]} from #{ref_genome}")
        ftArray.push(qNote)
      end

    else

      hit = annotations[synteny_prot[prot_id][:homology][:hits][0]]

      if synteny_prot.has_key? prot_id

        locus, gene, product, note, inference = nil
        locus = hit[:locustag]
        gene = hit[:gene]
        product = hit[:product]
        note = hit[:note]
        inference = hit[:inference]
        pId = synteny_prot[prot_id][:homology][:pId]
        cov_query = (synteny_prot[prot_id][:homology][:cov_query]*100).round(2)
        cov_subject = (synteny_prot[prot_id][:homology][:cov_subject]*100).round(2)
        reference_prot_id = synteny_prot[prot_id][:homology][:hits][0]

        qLocusTag = Bio::Feature::Qualifier.new('locus_tag', "#{prot_id}")
        ftArray.push(qLocusTag)

        if gene != nil
          qGene = Bio::Feature::Qualifier.new('gene', gene)
          ftArray.push(qGene)
        end

        if product != nil
          qProd = Bio::Feature::Qualifier.new('product', product)
          ftArray.push(qProd)
        end

        # check if there is a reference genome.. reference_locus shouldn't be nil in that case
        if locus != nil

          qNote = Bio::Feature::Qualifier.new('note', "corresponds to #{locus} locus (AA identity: #{pId}%; coverage(q,s): #{cov_query}%,#{cov_subject}%) from #{ref_genome}")
          ftArray.push(qNote)

          db_source = "[DBSource]"
          if reference_prot_id.include? "_"
            db_source = "RefSeq"
          else
            db_source = "INSD"
          end
          qInference = Bio::Feature::Qualifier.new('inference', "similar to AA sequence:#{db_source}:#{reference_prot_id}")
          ftArray.push(qInference)

        end

        if note != nil
          qNote = Bio::Feature::Qualifier.new('note', note)
          ftArray.push(qNote)
        end

        if inference != nil
          qInference = Bio::Feature::Qualifier.new('inference', inference)
          ftArray.push(qInference)
        end

      end

    end

    cds.qualifiers = ftArray

  end


end

#add_annotations(annotations, mode, reference_locus = nil) ⇒ Object

add annotation to a genbank file produced by prodigal



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 471

def add_annotations annotations, mode, reference_locus=nil

  # nb_of_added_ft = 0
  i = 0

  contig = @gbk.definition

  if mode == "inplace"

    # iterate through
    @gbk.features.each_with_index do |cds, ft_index|

      next if cds.feature != "CDS"

      ftArray = []
      cds.qualifiers = []

      i += 1
      prot_id = contig+"_"+i.to_s
      hit = nil

      if annotations.has_key? prot_id
        hit = annotations[prot_id]
      else
        puts "no hit for #{prot_id}"
        next
      end

      if hit != nil

        locus, gene, product, note = nil
        locus = hit[:locustag]
        gene = hit[:gene]
        product = hit[:product]
        note = hit[:note]
        pId = hit[:pId]

        if gene != nil
          qGene = Bio::Feature::Qualifier.new('gene', gene)
          ftArray.push(qGene)
        end

        if product != nil
          qProd = Bio::Feature::Qualifier.new('product', product)
          ftArray.push(qProd)
        end

        # check if there is a reference genome.. reference_locus shouldn't be nil in that case
        if locus != nil
          qNote = Bio::Feature::Qualifier.new('note', "corresponds to #{locus} locus (#{pId}% identity) from #{reference_locus.entry_id}")
          ftArray.push(qNote)
        end

        if note != nil
          qNote = Bio::Feature::Qualifier.new('note', note)
          ftArray.push(qNote)
        end

      end
      cds.qualifiers = ftArray

    end


  elsif mode == "new"

    sorted_annotations = annotations.sort_by { |k, v| v[:query_location][0][0] }

    new_features = {}
    annotations_done = {}
    gbk_features_len = @gbk.features.length

    @gbk.features.each_with_index do |ft, ft_index|

      sorted_annotations.each do |k,v|

        next if annotations_done.has_key? k

        if v[:query_location][0][0] < ft.locations[0].from or ft_index == gbk_features_len-1

          pp v
          if v[:subject_location][0][0] > v[:subject_location][0][1]
            location = "complement(#{v[:query_location][0][0]}..#{v[:query_location][0][1]})"
          else
            location = "#{v[:query_location][0][0]}..#{v[:query_location][0][1]}"
          end

          feature = Bio::Feature.new(v[:feature][0],location)
          feature.qualifiers.push(Bio::Feature::Qualifier.new('product',v[:product][0])) if ! v[:product][0].nil? or v[:product][0] != ""
          if ft_index == gbk_features_len-1
            new_features[gbk_features_len] = feature
          else
            new_features[ft_index] = feature
          end

          annotations_done[k] = 1
          break

        end

      end

    end

    new_features.each do |k,v|
      @gbk.features.insert(k,v)
    end

  end

end

#get_cdsObject

Prepare CDS/proteins



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
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 220

def get_cds

  if @coding_seq.empty?

    # Iterate over each CDS
    @gbk.each_cds do |ft|
      ftH = ft.to_hash
      loc = ft.locations
      gene = []
      product = []
      protId = ""
      if ftH.has_key? "pseudo"
        next
      end
      gene = ftH["gene"] if !ftH["gene"].nil?
      product = ftH["product"] if !ftH["product"].nil?
      protId = ftH["protein_id"][0] if !ftH["protein_id"].nil?
      locustag = ftH["locus_tag"][0] if !ftH["locus_tag"].nil?

      dna = get_DNA(ft,@bioseq)
      pep = dna.translate
      pepBioSeq = Bio::Sequence.auto(pep)
      dnaBioSeq = Bio::Sequence.auto(dna)

      if protId.strip == ""
        protId = locustag
      end

      @coding_seq[protId] = {
        protId: protId,
        location: loc,
        locustag: locustag,
        gene: gene[0],
        product: product[0],
        bioseq: pepBioSeq,
        bioseq_gene: dnaBioSeq,
        length: pepBioSeq.length
      }

    end

  end

  @coding_seq

end

#get_rnaObject

Prepare rRNA tRNA



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
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 268

def get_rna

  if @rna_seq.empty?

    @rna_seq = {}
    @gbk.features do |ft|

      next if ! ft.feature.to_s.include? "RNA"

      ftH = ft.to_hash
      loc = ft.locations
      # seqBeg = loc[0].from.to_s
      # seqEnd = loc[0].to.to_s
      # strand = loc[0].strand.to_s
      if ftH.has_key? "pseudo"
        next
      end
      # gene = ftH["gene"] if !ftH["gene"].nil?
      # protId = ftH["protein_id"][0] if !ftH["protein_id"].nil?
      product = ""

      if !ftH["product"].nil?
        product = ftH["product"][0]
        # puts ftH["product"].join(",") + "---" + ftH["product"][0]
      end

      locustag = ftH["locus_tag"][0] if !ftH["locus_tag"].nil?

      # puts "#{@accession}\t#{seqBeg}\t#{seqEnd}\t#{strand}\t#{protId}\t#{locustag}\t#{gene[0]}\t#{product[0]}"
      dna = get_DNA(ft,@bioseq)
      dnaBioSeq = Bio::Sequence.auto(dna)

      @rna_seq[locustag] = {
        type: ft.feature.to_s,
        location: loc,
        locustag: locustag,
        product: product,
        bioseq_gene: dnaBioSeq
      }

    end

  end

  @rna_seq

end

#new_gbk(gbk_file) ⇒ Object

New Genbank Holder to add annotation to it



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 197

def new_gbk gbk_file

  if ! File.exists? gbk_file
    fetch_ncbi_genome(gbk_file)
    gbk_file = "#{@outdir}/#{gbk_file}.gbk"
    # gbk_file += ".gbk"
  end

  flat_gbk = Bio::FlatFile.auto(gbk_file)

  # Check if gbk is valid
  if flat_gbk.dbclass != Bio::GenBank
    abort "Aborting : The input #{gbk_file} is not a valid genbank file !"
  else
    @gbk = flat_gbk.next_entry
  end

  @bioseq = @gbk.to_biosequence

end

#reference_db(dir) ⇒ Object

Use a MERGEM database to get annotation from it



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
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 43

def reference_db dir

  abort "Aborting: Can't find MERGEM db direcotry" if ! File.exists? dir

  @cds_file = "#{dir}/cds.dmnd"
  @rna_file = "#{dir}/rnas.fasta"

  json_genes = {}
  Zlib::GzipReader.open("#{dir}/cds.json.gz") {|gz|
    json_genes = JSON.parse(gz.read)
  }

  json_genes.each do |gene|

    prot_id = gene["cluster_id"]
    @coding_seq[prot_id] = {
      protId: prot_id,
      location: nil,
      product: gene["consensus_name"],
      length: gene["consensus_length"]
    }

  end

  # File.open("#{dir}/cds.txt") do |f|
  #   while l = f.gets
  #     lA = l.chomp.split(" ")
  #     @coding_seq[lA[0].gsub(">","")] = {
  #       protId: lA[0].gsub(">",""),
  #       location: nil,
  #       product: lA[1..-1].join(' '),
  #     }
  #   end
  # end

  File.open("#{dir}/rnas.txt") do |f|
    while l = f.gets
      lA = l.chomp.split(" ")
      @rna_seq[lA[0].gsub(">","")] = {
        protId: lA[0].gsub(">",""),
        location: nil,
        product: lA[1..-1].join(' '),
      }
    end
  end

end

#reference_gbk(gbk_file) ⇒ Object

Use a Genbank Reference and read annotation from it



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 92

def reference_gbk gbk_file

  puts "# Preparing reference genome files.."
  if ! File.exists? gbk_file
    fetch_ncbi_genome(gbk_file)
    gbk_file = "#{@outdir}/#{gbk_file}.gbk"
    # gbk_file += ".gbk"
  end

  flat_gbk = Bio::FlatFile.auto(gbk_file)

  # Check if gbk is valid
  if flat_gbk.dbclass != Bio::GenBank
    abort "Aborting : The input #{gbk_file} is not a valid genbank file !"
  else
    @gbk = flat_gbk.next_entry
  end

  @bioseq = @gbk.to_biosequence

  write_cds_to_file
  write_rna_to_file

end

#save_genbank_to_fileObject



584
585
586
587
588
589
590
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 584

def save_genbank_to_file

  File.open("#{@outdir}/#{@gbk.definition}.gbk", "w") do |f|
    f.write(@gbk.to_biosequence.output(:genbank))
  end

end

#single_fasta(fasta_file) ⇒ Object

Use a Genbank Reference and read annotation from it



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
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 118

def single_fasta fasta_file

  return "" if ! File.exists? fasta_file

  File.open(fasta_file, "r") do |dbfile|

    while l=dbfile.gets

      if l[0] == ">"

        lA = l.chomp.split("|")

        if lA.length > 1      # refseq, ncbi, trembl, swissprot

          key_gi = l.split(" ")[0][1..-1]
          product_long = lA[-1]

          organism = ""
          product = ""
          db_source = "[DBSource]"

          if product_long.scan(/|/).count >= 5 # FROM BIORUBY SCRIPTS
            product = product_long
            db_source = "RefSeq"
          elsif product_long.include? " [" and product_long.include? "]" # NCBI
            organism = product_long[/\[.*?\]/]
            product = product_long.split(" [")[0].strip
          elsif product_long.include? "OS=" # Swissprot / TrEMBL
            product_tmp = product.split("OS=")
            organism = product_tmp[1].split(/[A-Z][A-Z]=/)[0].strip
            product = product_tmp[0].strip
          elsif product_long.include? "[A-Z][A-Z]=" # NCBI
            product = product_long.split(/[A-Z][A-Z]=/)[0].strip
          else
            product = product_long
          end

          org = organism.gsub("[","").gsub("]","")

          product.lstrip!
          prot_id = nil

          if key_gi.count("|") == 4
            if lA[2] == "ref"
              db_source = "RefSeq"
            end
            prot_id = lA[3]
          elsif key_gi.count("|") == 2
            if lA[0].include? == "sp" or
              lA[0].include? == "tr"
              db_source = "UniProtKB"
            end
            prot_id = lA[1]
          elsif key_gi.count("|") == 5
            db_source = "RefSeq"
            prot_id = lA[2]
          end


        else                  # mergem


        end

        @coding_seq[key_gi] = { product: product,
                                org: org,
                                prot_id: prot_id,
                                db_source: db_source }

      end

    end

  end

end

#write_cds_to_fileObject

Print CDS to files RETURN : cds_file path



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 318

def write_cds_to_file

  cds_file = "#{@gbk.accession}.pep"
  dna_file = "#{@gbk.accession}.dna"

  if @coding_seq.empty?
    get_cds
  end

  dna_out = File.open("#{@outdir}/#{dna_file}", "w")
  File.open("#{@outdir}/#{cds_file}", "w") do |fwrite|
    @coding_seq.each_key do |k|
      seqout = @coding_seq[k][:bioseq].output_fasta("#{k}",60)
      seqout_dna = @coding_seq[k][:bioseq_gene].output_fasta("#{k}",60)
      fwrite.write(seqout)
      dna_out.write(seqout_dna)
    end
  end
  dna_out.close

  @cds_file = "#{@outdir}/" + cds_file

end

#write_rna_to_fileObject

Print RNA to files RETURN : rna_file path



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/bacterial-annotator/sequence-annotation.rb', line 344

def write_rna_to_file

  rna_file = "#{@gbk.accession}.rna"

  if @rna_seq.empty?
    get_rna
  end

  File.open("#{@outdir}/#{rna_file}", "w") do |fwrite|
    @rna_seq.each_key do |k|
      seqout_dna = @rna_seq[k][:bioseq_gene].output_fasta("#{k}|#{@rna_seq[k][:type]}|#{@rna_seq[k][:product]}",60)
      fwrite.write(seqout_dna)
    end
  end

  @rna_file = "#{@outdir}/" + rna_file

end