Class: Bioroebe::ParseFasta

Inherits:
CommandlineApplication show all
Defined in:
lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb

Overview

Bioroebe::ParseFasta

Constant Summary collapse

REGEX_NON_NUCLEOTIDES =
#

REGEX_NON_NUCLEOTIDES

All non-nucleotides will be handled here via this regex.

N is excluded because it may stand for “any” nucleotide too, at the least for a purine.

#
/BDEFHIJKLMOPQRSVWXYZ/
DEFAULT_FASTA =
#

DEFAULT_FASTA

This String can be used to quickly test code depending on FASTA entries.

#
'>Rosalind_6404
CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
TCCCACTAATAATTCTGAGG
>Rosalind_5959
CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
ATATCCATTTGTCAGCAGACACGC
>Rosalind_0808
CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
TGGGAACCTGCGGGCAGTAGGTGGAAT'
DEFAULT_ROUND_TO =
#

DEFAULT_ROUND_TO

#
2

Constants inherited from CommandlineApplication

CommandlineApplication::OLD_VERBOSE_VALUE

Constants included from ColoursForBase

ColoursForBase::ARRAY_HTML_COLOURS_IN_USE

Constants inherited from Base

Base::NAMESPACE

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from CommandlineApplication

#all_aminoacids?, #append_what_into, #at_home?, #be_silent, #be_verbose?, #cat, #ccliner, #change_directory, #cliner, #codon_table_dataset?, #codon_to_aminoacid, #codons_for?, #colourize_this_dna_sequence, #complement, #cp, #disable_warnings, #download_dir?, #editor?, #enable_warnings, #ensure_that_the_base_directories_exist, #esystem, #extract, #is_this_a_start_codon?, #is_this_a_stop_codon?, #leading_five_prime, #load_bioroebe_yaml_file, #log_directory?, #one_letter_to_long_name, #one_to_three, #only_numbers?, #open_in_browser, #opne, #pad_with_double_quotes, #pad_with_single_quotes, #partner_nucleotide, #remove_numbers, #remove_trailing_ansii_escape_code, #return_all_possible_start_codons, #return_array_of_one_letter_aminoacids, #return_cheerful_person, #return_chunked_display, #return_ubiquitin_sequence, #set_be_verbose, #start_codon?, #stop_codons?, #strict_filter_away_invalid_aminoacids, #taxonomy_download_directory?, #three_to_one, #to_rna, #trailing_three_prime, #verbose_truth, #was_or_were, #without_extname, #write_what_into

Methods included from CommandlineArguments

#commandline_arguments?, #commandline_arguments_that_are_files?, #e, #first?, #first_non_hyphen_argument?, #remove_hyphens_from_the_commandline_arguments, #return_commandline_arguments_as_string, #return_commandline_arguments_that_are_not_files, #return_entries_without_two_leading_hyphens, #select_commandline_arguments, #select_entries_starting_with_two_hyphens, #set_commandline_arguments

Methods included from ColoursForBase

#colourize_this_aminoacid_sequence_for_the_commandline, #colourize_this_nucleotide_sequence, #disable_colours, #ecomment, #efancy, #egold, #enable_colours, #eorange, #eparse, #erev, #red, #remove_trailing_escape_part, #return_colour_for_nucleotides, #rev, #sdir, #set_use_colours, #sfancy, #sfile, #simp, #swarn, #use_colours?, #use_colours_within_the_bioroebe_namespace?

Methods inherited from Base

#append_what_into, #can_base_pair?, #convert_global_env, #delete_file, #directory_to_the_codon_tables?, #file_readlines, #infer_the_namespace, #is_on_roebe?, #is_palindrome?, #main_encoding?, #mkdir, #move_file, #mv, #namespace?, #no_file_exists_at, #no_newlines, #project_yaml_directory?, #rds, #register_sigint, #return_pwd, #return_the_first_line_of_this_file, #word_wrap, #write_what_into

Constructor Details

#initialize(i = DEFAULT_FASTA, run_already = true, &block) ⇒ ParseFasta

#

initialize

#

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
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 66

def initialize(
    i           = DEFAULT_FASTA,
    run_already = true,
    &block
  )
  reset
  # ======================================================================= #
  # === Handle blocks next
  # ======================================================================= #
  if block_given?
    yielded = yield
    # ===================================================================== #
    # First handle Symbols.
    # ===================================================================== #
    case yielded
    # ===================================================================== #
    # === :be_verbose
    # ===================================================================== #
    when :be_verbose,
         :verbose
      set_be_verbose_and_report_the_sequence
    # ===================================================================== #
    # === :be_quiet
    # ===================================================================== #
    when :be_quiet,
         :be_silent
      be_quiet
    # ===================================================================== #
    # === :sizeseq
    # ===================================================================== #
    when :sizeseq
      @sort_by_size = true
    end
    # ===================================================================== #
    # === Handle Hashes next
    # ===================================================================== #
    if yielded.is_a? Hash
      # =================================================================== #
      # === :be_verbose
      # =================================================================== #
      if yielded.has_key? :be_verbose
        set_be_verbose(yielded.delete(:be_verbose))
        @internal_hash[:report_the_sequence] = true
      end
      # =================================================================== #
      # === :use_colours
      # =================================================================== #
      if yielded.has_key? :use_colours
        set_use_colours(
          yielded.delete(:use_colours)
        )
      end
      # =================================================================== #
      # === :sizeseq
      # =================================================================== #
      if yielded.has_key? :sizeseq
        @sort_by_size = true
      end
    end
  end
  set_commandline_arguments(i)
  case run_already
  # ======================================================================= #
  # === :dont_run_yet
  # ======================================================================= #
  when :dont_run_yet,
       :do_not_run_yet
    run_already = false
  end
  run if run_already
end

Class Method Details

.[](i) ⇒ Object

#

Bioroebe::ParseFasta[]

#

1222
1223
1224
1225
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1222

def self.[](i)
  _ = new(i)
  _.sequences?
end

Instance Method Details

#[](i) ⇒ Object

#

[]

This is a simpler query-interface for obtaining the DNA/RNA sequence of the FASTA file (or aminoacid sequence, if we have a protein at hand here).

Using the method sequences? here, which in turn works on @hash, is ok because Hashes are kept in a sorted manner in ruby since some time.

#

1215
1216
1217
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1215

def [](i)
  sequences?[i]
end

#add_length_information_to_the_headerObject

#

add_length_information_to_the_header

#

1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1099

def add_length_information_to_the_header
  _ = header?.strip
  _ << ' length='+sequence_size?.to_s+';'
  # ======================================================================= #
  # Next, designate where to store this file.
  # ======================================================================= #
  into = 'new_fasta_file.fasta'
  if overwrite_the_original_file?
    into = @input_file
  end
  what = ''.dup
  what << "> "+_+"\n"
  what << raw_body?
  if what and into
    erev 'Storing into `'+sfile(into)+rev+'`.'
    write_what_into(what, into)
  end
end

#calculate_gc_contentObject

#

calculate_gc_content

Calculate the gc content through this method, which is called from within the method run().

#

722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 722

def calculate_gc_content
  _ = @hash.values.join.delete(N)
  if is_polynucleotide? _
    @hash.each_pair {|key, content|
      # =================================================================== #
      # Delegate towards the method Bioroebe.gc_content next, including
      # to round towards 5 positions:
      # =================================================================== #
      gc_content = ::Bioroebe.gc_content(content.upcase, round_to?)
      gc_content = gc_content.first if gc_content.is_a? Array
      gc_content = gc_content.to_s
      minimal_key = key.to_s
      if minimal_key.include? '|'
        minimal_key = minimal_key.split('|').last.strip
      end
      if be_verbose?
        _ = minimal_key.strip
        if _.size > 40 # Shorten the content a bit if it is too long.
          _ = _[0 .. 40]+' [...]'
        end
        erev 'GC content of "'+simp(_)+rev+'" is: '+
             "#{sfancy(gc_content)}#{rev} %"
      end
    }
  else
    erev '`'+simp(_)+rev+'` is not a polynucleotide.' if be_verbose?
  end
end

#condense_the_sequence_onto_a_single_line?Boolean

#

condense_the_sequence_onto_a_single_line?

#

Returns:

  • (Boolean)

888
889
890
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 888

def condense_the_sequence_onto_a_single_line?
  @internal_hash[:condense_the_sequence_onto_a_single_line]
end

#current_key?Boolean Also known as: id?, sequence_id?, title, title?

#

current_key?

#

Returns:

  • (Boolean)

688
689
690
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 688

def current_key?
  @current_key
end

#data?Boolean Also known as: input?, dataset?

#

data?

This will contain the full content of the (whole) .fasta file, including the header.

#

Returns:

  • (Boolean)

791
792
793
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 791

def data?
  @data
end

#do_process_the_commandline_arguments_that_are_files(these_files = commandline_arguments_that_are_files? ) ⇒ Object

#

do_process_the_commandline_arguments_that_are_files

#

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
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 421

def do_process_the_commandline_arguments_that_are_files(
    these_files = commandline_arguments_that_are_files?
  )
  unless these_files.is_a? Array
    these_files = [these_files].flatten.compact
  end
  these_files.each {|this_file|
    set_input_file(this_file)
    set_data # This will use the default file.
    split_into_proper_sections
    report_the_FASTA_header if @show_the_header
    if @sort_by_size
      run_sizeseq_comparison
    else
      # =================================================================== #
      # === Handle cases where the input is a protein
      # =================================================================== #
      if is_the_sequence_a_polypeptide?
        if be_verbose?
          erev "This sequence is assumed to be a #{royalblue('protein')}#{rev}."
          report_how_many_elements_we_have_found
        end
      else # Must be a protein.
        # =================================================================== #
        # === Else it must be RNA or DNA
        # =================================================================== #
        if be_verbose?
          erev "This sequence is assumed to "\
               "be #{royalblue('DNA')}#{rev} or #{royalblue('RNA')}#{rev}."
        end
        calculate_gc_content # GC content makes only sense for nucleotides.
        report_how_many_elements_we_have_found if be_verbose?
      end
      if be_verbose?
        report_the_nucleotide_composition
        report_on_how_many_entries_we_did_work
        if report_the_sequence?
          do_report_the_sequence
        end
      end
    end
  }
end

#do_report_the_sequenceObject Also known as: display, report

#

do_report_the_sequence (report tag)

This method is used to display the main sequence at hand.

#

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
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 514

def do_report_the_sequence
  _ = main_sequence?
  # ======================================================================= #
  # Honour the --limit commandline flag next.
  # ======================================================================= #
  if @internal_hash[:limit_the_display_to_n_nucleotides]
    _ = _[0 .. (@internal_hash[:limit_the_display_to_n_nucleotides] - 1)]
  end
  if @colourize_sequence
    if is_polynucleotide?
      # =================================================================== #
      # Else assume this is DNA/RNA input.
      # =================================================================== #
      _.gsub!(/A/, teal('A')+rev)
      _.gsub!(/C/, slateblue('C')+rev)
      _.gsub!(/G/, royalblue('G')+rev)
      _.gsub!(/T/, steelblue('T')+rev)
      _.gsub!(/U/, steelblue('U')+rev)
    #else
    end
  end
  if condense_the_sequence_onto_a_single_line?
    _ = _.delete("\n")
  end
  erev colourize_this_nucleotide_sequence(_)
  e if condense_the_sequence_onto_a_single_line?
  if show_the_translated_protein_sequence?
    # ===================================================================== #
    # Do show the translated protein sequence next:
    # ===================================================================== #
    translated_into_aa = Bioroebe.to_aa(_)
    translated_into_aa_and_colourized = translated_into_aa.dup
    if translated_into_aa.include? '*'
      translated_into_aa_and_colourized = translated_into_aa.gsub(/\*/,tomato('*'))
    end
    erev 'The translated aminoacid sequence of '+
         sfancy(translated_into_aa.size.to_s)+rev+
         ' aminoacids is:'
    e
    erev steelblue("  #{translated_into_aa_and_colourized}")
    e
  end
end

#do_show_the_headerObject

#

do_show_the_header

#

975
976
977
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 975

def do_show_the_header
  @show_the_header = true
end

#do_sort_by_sizeObject Also known as: run_sizeseq_comparison

#

do_sort_by_size

This method will sort the hash by size of the sequence. It has been inspired by the EMBOSS sizeq functionality.

The output that should be generated might look like this:

https://www.bioinformatics.nl/cgi-bin/emboss/help/sizeseq#input.1

Invocation example:

x = Bioroebe::ParseFasta.new('/Depot/j/globins.fasta'); x.do_sort_by_size
#

916
917
918
919
920
921
922
923
924
925
926
927
928
929
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 916

def do_sort_by_size
  # ======================================================================= #
  # Sort it here first, by the size of the "value", aka the sequence body.
  # ======================================================================= #
  @hash = return_size_sorted_hash(@hash)
  _ = ''.dup
  @hash.each_pair {|key, sequence|
    _ << '> ID '+sequence.size.to_s+' AA.; DE: '+key.to_s+
         ' SQ '+sequence.size.to_s+' AA'+N # ; unknown MW as of yet; '\
         #'unknown CRC64 as of yet'+N
    _ << sequence+N+N
  }
  e _
end

#entries?Boolean

#

entries?

#

Returns:

  • (Boolean)

491
492
493
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 491

def entries?
  @data
end

#first_key?Boolean

#

first_key?

Obtain the very first entry.

#

Returns:

  • (Boolean)

952
953
954
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 952

def first_key?
  headers?.first
end

#first_valueObject

#

first_value

This will return the first entry of the Fasta files.

#

756
757
758
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 756

def first_value
  sequences?.first
end

#gc_content?Boolean Also known as: gc_content

#

gc_content?

#

Returns:

  • (Boolean)

1296
1297
1298
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1296

def gc_content?
  return ::Bioroebe.gc_content(main_sequence?).to_f # Must be a float.
end

#hash?Boolean

#

hash?

#

Returns:

  • (Boolean)

799
800
801
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 799

def hash?
  @hash
end

#header?Boolean

#

header?

This variant will always return the first entry.

#

Returns:

  • (Boolean)

961
962
963
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 961

def header?
  headers?.first.to_s
end

#headers?Boolean

#

headers?

#

Returns:

  • (Boolean)

943
944
945
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 943

def headers?
  @hash.keys
end

#is_polynucleotide?(i = main_sequence?) ) ⇒ Boolean Also known as: is_a_nucleotide?

#

is_polynucleotide?

#

Returns:

  • (Boolean)

774
775
776
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 774

def is_polynucleotide?(i = main_sequence?)
  !is_protein?(i)
end

#is_the_sequence_a_polypeptide?(i = main_sequence? ) ⇒ Boolean Also known as: is_protein?, is_a_protein?

#

is_the_sequence_a_polypeptide?

This method can be used to determine whether a given input sequence is a polypeptide (aka a protein) or whether it is not.

If this sequence is a polypeptide then this method will return true. Otherwise false will be returned.

#

Returns:

  • (Boolean)

1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1249

def is_the_sequence_a_polypeptide?(
    i = main_sequence?
  )
  return_value = false # Set the default return value here.
  # ======================================================================= #
  # Look at the first 120 positions to determine whether this is a protein
  # or a nucleotide sequence.
  # ======================================================================= #
  subsequence = i[0 .. 119] # Must deduct 1 at the end since Arrays in ruby start at 0.
  # ======================================================================= #
  # Build a frequency of the characters there.
  # ======================================================================= #
  hash = {}
  hash.default = 0
  subsequence.chars.each {|character|
    hash[character] += 1
  }
  keys_to_check_for = %w(
    B D E F H I J K L M O P Q R S V W X Y Z
  )

  values = hash.select {|key, value|
    if keys_to_check_for.include? key
      true
    else
      false
    end
  }.values.sum
  if values > 0
    return_value = true
  end
  return return_value
end

#is_this_sequence_a_polynucleotide_sequence?Boolean

#

is_this_sequence_a_polynucleotide_sequence?

#

Returns:

  • (Boolean)

781
782
783
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 781

def is_this_sequence_a_polynucleotide_sequence?
  !is_protein?
end

#main_sequence?Boolean

#

main_sequence?

This will always return the first entry.

#

Returns:

  • (Boolean)

1289
1290
1291
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1289

def main_sequence?
  @hash.values.first
end
#

menu (menu tag)

#

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
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 255

def menu(
    i = return_commandline_arguments_that_are_not_files
  )
  if i.is_a? Array
    i.each {|entry| menu(entry) }
  else
    case i # case tag
    # ===================================================================== #
    # === --to-protein
    #
    # Invocation example:
    #
    #   pfasta *.fasta --toprotein
    #
    # ===================================================================== #
    when /^-?-?to(-|_)?protein/i
      @internal_hash[:show_the_translated_protein_sequence] = true
    # ===================================================================== #
    # === --one-line
    #
    # Invocation example:
    #
    #   pfasta rpoS_NC_000913.3.fasta --one-line
    #
    # ===================================================================== #
    when /^-?-?one(-|_)?liner?/i
      @internal_hash[:condense_the_sequence_onto_a_single_line] = true
    # ===================================================================== #
    # === --limit=1000
    #
    # Invocation example:
    #
    #   pfasta --limit=1000
    #
    # ===================================================================== #
    when /^-?-?limit=(\d+)$/i
      @internal_hash[:limit_the_display_to_n_nucleotides] = $1.to_s.dup.to_i
    # ===================================================================== #
    # === --overwrite
    # ===================================================================== #
    when /^-?-?overwrite/i
      @internal_hash[:overwrite_the_original_file] = true
    # ===================================================================== #
    # === --help
    #
    # Usage example:
    #
    #   parse_fasta --help
    #
    # ===================================================================== #
    when /^-?-?help/i
      show_help
      exit
    # ===================================================================== #
    # === --save-file
    # ===================================================================== #
    when /^-?-?save(-|_)?file/i
      @internal_hash[:save_the_file] = true
    # ===================================================================== #
    # === --also-show-the-sequence
    #
    # To invoke this method try:
    #
    #   parsefasta /Depot/Bioroebe/NP_013521.3_289_aa.fasta --show
    #
    # ===================================================================== #
    when /^-?-?also(-|_)?show(-|_)?the(-|_)?sequence$/i,
         /^-?-?report$/i,
         /^-?-?show$/i
      @internal_hash[:report_the_sequence] = true
    # ===================================================================== #
    # === --header
    # ===================================================================== #
    when /^-?-?header/i
      do_show_the_header
    # ===================================================================== #
    # === --short
    #
    # This entry point can be used to show 300 nucleotides and not
    # more, by simply using the --short commandline flag.
    # ===================================================================== #
    when /^-?-?short/i
      @internal_hash[:limit_the_display_to_n_nucleotides] = 300
    # ===================================================================== #
    # === --size
    #
    # This will simply tell us how many nucleotides the given sequence 
    # has, then exit.
    #
    # To invoke this method try:
    #
    #   parsefasta /Depot/Bioroebe/NP_013521.3_289_aa.fasta --size
    #
    # ===================================================================== #
    when /^-?-?size$/i
      set_be_quiet
      do_process_the_commandline_arguments_that_are_files
      erev size? # Report the size here.
      exit
    end
  end
end

#n_nucleotides?Boolean Also known as: return_n_aminoacids, size?, sequence_size?

#

n_nucleotides?

#

Returns:

  • (Boolean)

934
935
936
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 934

def n_nucleotides?
  @hash.values.first.delete("\n").size
end

#nucleotides_or_aminoacids?Boolean

#

nucleotides_or_aminoacids?

#

Returns:

  • (Boolean)

763
764
765
766
767
768
769
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 763

def nucleotides_or_aminoacids?
  if is_polynucleotide?
    'nucleotides'
  else
    'aminoacids'
  end
end

#opnnObject

#

opnn

#

705
706
707
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 705

def opnn
  super(namespace?) if use_opn?
end

#output_resultsObject

#

output_results

#

505
506
507
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 505

def output_results
  pp @hash
end

#overwrite_the_original_file?Boolean

#

overwrite_the_original_file?

#

Returns:

  • (Boolean)

1033
1034
1035
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1033

def overwrite_the_original_file?
  @internal_hash[:overwrite_the_original_file]
end

#raw_body?Boolean

#

raw_body?

#

Returns:

  • (Boolean)

968
969
970
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 968

def raw_body?
  @hash.values.first
end

#report_how_many_elements_we_have_foundObject

#

report_how_many_elements_we_have_found

#

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 590

def report_how_many_elements_we_have_found
  if @hash
    first = @hash.values.first.delete("\n")
    size = first.size.to_s
    if be_verbose?
      n_start_codons = first.count('ATG')
      # =================================================================== #
      # We upcase it since as of October 2021, as some FASTA files may
      # include the sequence in lowercased characters.
      # =================================================================== #
      n_start_codons += first.reverse.upcase.count('ATG')
      result = "This sequence contains #{simp(size.to_s)}#{rev}"\
               " #{nucleotides_or_aminoacids?}".dup
      if is_a_nucleotide?
        result << " and #{n_start_codons} "\
                  "ATG codons (on both strands) in total"
      end
      result << '.'
      if size.to_i > 1_000_000
        # ================================================================= #
        # Format the number with '_' characters.
        # ================================================================= #
        formatted = size.to_i.to_s.reverse.split(/(.{3})/).reject(&:empty?).join('_').reverse
        result = result.dup if result.frozen?
        result << ' ('+simp(formatted+' bp')+rev+')'
      end
      erev result
    end
  end
end

#report_on_how_many_entries_we_did_workObject

#

report_on_how_many_entries_we_did_work

#

624
625
626
627
628
629
630
631
632
633
634
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 624

def report_on_how_many_entries_we_did_work
  if be_verbose?
    entry_or_entries = 'entry'
    if @hash.keys.size > 1
      entry_or_entries = 'entries'
    end
    erev "We have identified a total of #{orange(@hash.keys.size)}"\
         "#{rev} #{entry_or_entries} in this fasta dataset."
    e
  end
end

#report_the_FASTA_headerObject

#

report_the_FASTA_header

#

639
640
641
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 639

def report_the_FASTA_header
  e "#{rev}The header is: #{steelblue(header?)}"
end

#report_the_nucleotide_compositionObject Also known as: report_the_protein_composition

#

report_the_nucleotide_composition

#

562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 562

def report_the_nucleotide_composition
  if is_this_sequence_a_polynucleotide_sequence?
    first = @hash.values.first.upcase
    total_size   = first.size
    n_adenines   = first.count('A')
    n_thymidines = first.count('T')
    n_cytodines  = first.count('C')
    n_guanines   = first.count('G')
    erev "The nucleotide composition is as follows:"
    e "  "\
      "#{steelblue(n_adenines)}#{rev}x A (#{(n_adenines * 100.0 / total_size).round(2)}%), "\
      "#{steelblue(n_thymidines)}#{rev}x T (#{(n_thymidines * 100.0 / total_size).round(2)}%), "\
      "#{steelblue(n_cytodines)}#{rev}x C (#{(n_cytodines * 100.0 / total_size).round(2)}%), "\
      "#{steelblue(n_guanines)}#{rev}x G (#{(n_guanines * 100.0 / total_size).round(2)}%)"
  elsif is_a_protein?
    # ===================================================================== #
    # Report the composition of the protein:
    # ===================================================================== #
    sequence = @hash.values.first.delete("\n")
    erev "The protein composition (aminoacids) is as follows:"
    # e colourize_this_aminoacid_sequence_for_the_commandline("  #{sequence}")
    e orchid("  #{sequence}")
  end
end

#report_the_sequence?Boolean

#

report_the_sequence?

#

Returns:

  • (Boolean)

646
647
648
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 646

def report_the_sequence?
  @internal_hash[:report_the_sequence]
end

#resetObject

#

reset (reset tag)

#

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
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 141

def reset
  super()
  infer_the_namespace
  # ======================================================================= #
  # === @is_a_genbank_file
  # ======================================================================= #
  @is_a_genbank_file = false
  # ======================================================================= #
  # === @input_file
  #
  # This variable denotes which input file is used to read data from.
  #
  # It is nil initially because we may skip reading from an existing
  # file and e. g. only read from a String or some other non-file
  # entity.
  # ======================================================================= #
  @input_file = nil
  # ======================================================================= #
  # === @hash
  #
  # This is the main variable for the class. It will keep entries such
  # as this one here:
  #
  #   {
  #     "ENSMUSG00000020122|ENSMUST08" => "CCCTCC"
  #   }
  #
  # ======================================================================= #
  @hash = {}
  # ======================================================================= #
  # === @internal_hash
  #
  # This Hash exists for internal configuration of the class.
  # ======================================================================= #
  @internal_hash = {}
  # ======================================================================= #
  # === :report_the_sequence
  # ======================================================================= #
  @internal_hash[:report_the_sequence] = false
  # ======================================================================= #
  # === :overwrite_the_original_file
  # ======================================================================= #
  @internal_hash[:overwrite_the_original_file] = false
  # ======================================================================= #
  # === :save_the_file
  # ======================================================================= #
  @internal_hash[:save_the_file] = false
  # ======================================================================= #
  # === :remove_numbers_from_input
  # ======================================================================= #
  @internal_hash[:remove_numbers_from_input] = false
  # ======================================================================= #
  # === :show_the_translated_protein_sequence
  #
  # This setting is false initially. If set to true via the commandline
  # then report() will show the translated protein sequence as well.
  # ======================================================================= #
  @internal_hash[:show_the_translated_protein_sequence] = false
  # ======================================================================= #
  # === :condense_the_sequence_onto_a_single_line
  #
  # By default the output of this class will include newlines for the
  # sequence. If this is not wanted by the user then the following
  # variable keeps track of that behaviour. You can use the flag
  # called --one-line to enable a condensed output, with newlines
  # being removed.
  # ======================================================================= #
  @internal_hash[:condense_the_sequence_onto_a_single_line] = false
  # ======================================================================= #
  # === :limit_the_display_to_n_nucleotides
  #
  # If this variable is a number rather than nil, then it will be used
  # to display only a limited number of nucleotides, e. g. "1000" if
  # the user passes in 1000.
  # ======================================================================= #
  @internal_hash[:limit_the_display_to_n_nucleotides] = nil
  # ======================================================================= #
  # === @may_we_exit
  # ======================================================================= #
  @may_we_exit = false
  # ======================================================================= #
  # === @current_key
  # ======================================================================= #
  @current_key = nil
  # ======================================================================= #
  # === @use_opn
  # ======================================================================= #
  @use_opn = ::Bioroebe.use_opn?
  # ======================================================================= #
  # === @colourize_sequence
  # ======================================================================= #
  @colourize_sequence = false
  # ======================================================================= #
  # === @sort_by_size
  #
  # If the following variable is set to true, then this class will
  # run a sizeseq-comparison, that is, it will compare all sequences
  # and output them in a size-sorted manner, similar to the EMBOSS
  # sizeseq action.
  # ======================================================================= #
  @sort_by_size = false
  # ======================================================================= #
  # === @show_the_header
  #
  # If this variable is true then the header will be shown.
  # ======================================================================= #
  @show_the_header = false
  set_round_to :default
  set_be_verbose
end

#return_size_sorted_hash(i = @hash) ⇒ Object

#

return_size_sorted_hash

#

895
896
897
898
899
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 895

def return_size_sorted_hash(i = @hash)
  _ = i.sort_by {|key, value| value.size }
  i = Hash[_]
  return i
end

#round_to?Boolean

#

round_to?

#

Returns:

  • (Boolean)

698
699
700
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 698

def round_to?
  @internal_hash[:round_to]
end

#runObject

#

run (run tag)

#

653
654
655
656
657
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 653

def run
  menu
  do_process_the_commandline_arguments_that_are_files
  do_save_the_file if save_the_file?
end

#sanitize_data(i) ⇒ Object

#

sanitize_data

#

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 662

def sanitize_data(i)
  if i.is_a? Array
    i.flatten!
    i.reject! {|entry| entry.start_with? '#' }
    i.reject! {|entry| entry.strip.empty? }
    if i.first and i.first.include? "\r"
      # =================================================================== #
      # Some FASTA files include "\r" line endings. We will check first
      # for the first entry to contain a \r, and if so, we assume the
      # whole FASTA file may have \r, which then will be removed.
      # =================================================================== #
      i.map! {|entry| entry.delete("\r") }
    end
  end
  # ========================================================================= #
  # === Run through SanitizeNucleotideSequence
  # ========================================================================= #
  if @internal_hash[:remove_numbers_from_input]
    i = Bioroebe::SanitizeNucleotideSequence[i]
  end
  i
end

#sanitize_the_descriptionObject

#

sanitize_the_description

This method will iterate over the description entry and sanitize it. In this context sanitizing means to add the “length” entry, and the “type” entry, such as in:

" # length=231; type=dna"
#

475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 475

def sanitize_the_description
  @data.map! {|line|
    if line.start_with?('>') and !line.include?('length=')
      length = 0
      if @hash.has_key? line.delete('>')
        length = @hash[line.delete('>')].size
      end
      line << " # length=#{length}; type=dna" # Currently hardcoded to DNA.
    end
    line
  }
end

#saveObject

#

save

This method will save our FASTA file.

#

1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1191

def save
  if @input_file.nil?
    erev "The generic file #{sfile('foobar.fasta')}#{rev} "\
         "will be used."
    set_input_file('foobar.fasta')
  end
  into = @input_file
  what = @data.join("\n")
  erev 'Storing into '+sfile(into)+rev+'.'
  write_what_into(what, into)
  return into
end

#save_into_a_fasta_file(be_verbose = be_verbose? ) ⇒ Object Also known as: do_save_the_file

#

save_into_a_fasta_file

#

1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1078

def save_into_a_fasta_file(
    be_verbose = be_verbose?
  )
  case be_verbose
  when :be_verbose
    be_verbose = true
  end
  if @data
    what = @data.join("\n")
    into = 'standard.fasta'
    erev 'Saving into '+sfile(into)+rev+'.' if be_verbose
    write_what_into(what, into)
    return File.absolute_path(into) # And return the file we saved into.
  else
    opnn; erev 'No @data variable exists.'
  end
end

#save_the_file?Boolean

#

save_the_file?

#

Returns:

  • (Boolean)

1026
1027
1028
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1026

def save_the_file?
  @internal_hash[:save_the_file]
end

#sequenceObject Also known as: fasta_sequence, sequence?, body?, body, naseq, nucleotide_sequence, return_sequence, content?

#

sequence

This method will return the sequence, without any newlines. It is also called the “body” of a FASTA file.

#

1173
1174
1175
1176
1177
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1173

def sequence
  _ = @hash.values.first
  _.chomp! if _ and _.end_with?(N)
  return no_newlines(_)
end

#sequence_objectObject

#

sequence_object

This method will return a Sequence object.

Usage example:

x = Bioroebe.parse_fasta 'ls_orchid.fasta'
y = x.sequence_object # y is now an instance of Bioroebe::Sequence
#

1311
1312
1313
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1311

def sequence_object
  ::Bioroebe::Sequence.new(main_sequence?)
end

#sequences?Boolean Also known as: sequences, values

#

sequences?

This method will obtain all found sequences.

#

Returns:

  • (Boolean)

808
809
810
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 808

def sequences?
  @hash.values
end

#set_be_verbose_and_report_the_sequenceObject

#

set_be_verbose_and_report_the_sequence

#

880
881
882
883
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 880

def set_be_verbose_and_report_the_sequence
  set_be_verbose
  @internal_hash[:report_the_sequence] = true
end

#set_data(i = @input_file) ⇒ Object Also known as: set_sequence

#

set_data

This is the setter-method towards @data. It is no longer allowed to invoke set_input_file() since as of 12.06.2020. This means that you have to invoke that method prior to calling this method.

#

846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 846

def set_data(i = @input_file)
  # ======================================================================= #
  # The next line attempts to ensure that even an Array can be used
  # as input to that method.
  # ======================================================================= #
  i = [i].flatten.compact.first.to_s.dup
  if File.exist? i.to_s # First try to read in from a file.
    if be_verbose?
      opnn; erev "Will read from the file `#{sfile(i)}#{rev}`."
    end
    i = File.readlines(i)
    if @is_a_genbank_file
      selected = i.select {|line|
        line.start_with?('       ') and # such as: "       61 atggggcctg caatggggcc tgcaatgggg cctgca\n"
        (line.strip =~ /\d+/)
      }.map {|inner_line|
        inner_line.strip.delete(' 0123456789').strip.upcase
      }
      i = ["> genbank file"]+selected
    end
  end
  if i.nil? or i.empty?
    i = DEFAULT_FASTA
    opnn; erev 'No input was provided. Thus a default FASTA '\
               'sequence will be used instead.'
  end
  i = sanitize_data(i)
  i = i.split(N) if i.is_a? String
  @data = i
end

#set_input_file(i = nil) ⇒ Object Also known as: set_input_files

#

set_input_file

This method will be used to keep track of the input-file, from which we will read the dataset.

#

985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 985

def set_input_file(i = nil)
  if i.nil?
    # ===================================================================== #
    # First, we try to find a .fasta or .fa file in the current
    # directory. If we can find it, we will use that instead.
    # ===================================================================== #
    unless Dir['*.{fa,fasta}'].empty?
      file = Dir['*.{fa,fasta}'].first
      if be_verbose?
        result = 'A '
        if file.end_with? '.fasta'
          result < 'FASTA '
        end
        result << 'file was found in this directory ('+sfile(file)+').'
        opnn; erev result
        opnn; erev 'We will use it.'
      end
      i = file
    end
    unless Dir['*.{fa,fasta}'].empty?
      file = Dir['*.{fa,fasta}'].first
      if be_verbose?
        opnn; erev "We have found a file in this "\
                   "directory (#{sfile(file)}#{rev})."
        opnn; erev 'We will use it.'
      end
      i = file
    end
  end
  if i and File.exist?(i)
    dataset = File.read(i)
    if dataset[0 .. ('LOCUS'.size - 1)] == 'LOCUS'
      @is_a_genbank_file = true
    end
  end
  @input_file = i
end

#set_round_to(i = :default) ⇒ Object

#

set_round_to

This will set to how many decimal numbers we will round to. This is mostly done for display-purposes, hence why the default is a fairly low value.

#

403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 403

def set_round_to(
    i = :default
  )
  case i
  # ======================================================================= #
  # === :default
  #
  # Since as of April 2021, the new default is 2, for rounding.
  # ======================================================================= #
  when :default
    i = DEFAULT_ROUND_TO
  end
  @internal_hash[:round_to] = i.to_i
end

#short_headers?Boolean

#

short_headers?

The short-headers are like the headers, but if a ' ' token is found then the line will be truncated towards that first ' '.

An example is:

sp|Q91FT8|234R_IIV6 Uncharacterized protein 234R OS=Invertebrate iridescent virus 6 OX=176652 GN=IIV6-234R PE=4 SV=1

This will be truncated towards

sp|Q91FT8|234R_IIV6

This could then be used to automatically rename FASTA files, for instance.

#

Returns:

  • (Boolean)

830
831
832
833
834
835
836
837
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 830

def short_headers?
  headers?.map {|entry|
    if entry.include? ' '
      entry = entry.split(' ').first
    end
    entry
  }
end

#show_helpObject

#

show_help (help tag)

This method will inform the user how this class may be used from the commandline.

Invocation example:

pfasta --help
#

371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 371

def show_help
  e
  eparse '  --size'
  eparse '  --also-show-the-sequence'
  eparse '  --header     # show the header as well (normally the '\
         'header is not shown)'
  eparse '  --limit=1000 # limit to show only the first 1000 '\
         'nucleotides; use'
  eparse '               # any number that you need here'
  eparse '  --one-line   # show the sequence on one line only, '\
         'e. g. all newlines'
  eparse '               # were removed'
  eparse '  --toprotein  # show the protein sequence as well '\
         '(assumes DNA or RNA'
  eparse '               # .fasta file)'
  e
end

#show_the_translated_protein_sequence?Boolean

#

show_the_translated_protein_sequence?

#

Returns:

  • (Boolean)

392
393
394
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 392

def show_the_translated_protein_sequence?
  @internal_hash[:show_the_translated_protein_sequence]
end

#simplify_headerObject

#

simplify_header

This method can be called to simplify the header. It will save into a .fasta file at once.

#

1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1124

def simplify_header
  _ = header?
  # ======================================================================= #
  # Next, simplify the header. We must start with checking for [] first,
  # because if there are any [] in the FASTA header then we can simplify
  # stuff at once.
  # ======================================================================= #
  if _.include?('[') and _.include?(']')
    _ = '> '+_.strip.scan(/\[.+\]/).flatten.first.delete('[]')+"\n"
  elsif _.include? ','
    _ = _[0 .. (_.index(',') - 1) ].strip
  end
  what = nil
  # ======================================================================= #
  # Next, designate where to store this file.
  # ======================================================================= #
  into = 'new_fasta_file.fasta'
  if overwrite_the_original_file?
    into = @input_file
  end
  if _.start_with? '>'
    what = _
  elsif _.include?('[') and _.include?(']') # For example: [Pan troglodytes]
    # ===================================================================== #
    # See rubular at:
    #
    #   https://rubular.com/r/aDjI0JwMOUlZzP
    #
    # ===================================================================== #
    what = "> "+_.scan(/\[(.+)\]/).flatten.first.to_s+"\n".dup 
  elsif _.include? 'Human'
    _scanned_result = _.scan(/(Human)/)
    what = "> "+$1.to_s.dup+"\n".dup
  else
    erev "Unsure what to do: #{steelblue(_)}"
  end
  if what and into
    what << raw_body?
    erev 'Storing into `'+sfile(into)+rev+'`.'
    write_what_into(what, into)
  end
end

#split_into_proper_sectionsObject

#

split_into_proper_sections

Split up into the fasta identifier, and the content.

#

1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1042

def split_into_proper_sections
  unless @data.to_s.include? '>'
    erev 'No ">" character was found in this dataset.'
    erev 'It is recommended to always have a > identifier '\
         'for the'
    erev 'FASTA format (such as in a .fasta or a .fa file).'
  end if be_verbose? # Ok, the input data includes >. We can proceed.
  @data.each { |line|
    # ===================================================================== #
    # === Handle the leading > FASTA identifier first
    # ===================================================================== #
    if line.start_with? '>' # leading identifier.
      @current_key = line[1..-1].chomp # Select all but the first character.
      @hash[@current_key] = ''.dup
    else
      line.delete!('_')
      unless @current_key
        @current_key = 'standard'
        @hash[@current_key] = ''.dup
      end
      # =================================================================== #
      # === Retain the newlines
      #
      # Here we may decide to get rid of newlines, but it is better to
      # NOT remove the newlines - that way we can simply save the
      # dataset again.
      # @hash[@current_key] << no_newlines(line)
      # =================================================================== #
      @hash[@current_key] << line
    end
  }
end

#type?Boolean

#

type?

#

Returns:

  • (Boolean)

1230
1231
1232
1233
1234
1235
1236
1237
1238
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 1230

def type?
  if is_the_sequence_a_polypeptide?
    :protein
  elsif is_this_sequence_a_polynucleotide_sequence?
    :dna_or_rna
  else
    :unknown
  end
end

#use_opn?Boolean

#

use_opn?

#

Returns:

  • (Boolean)

712
713
714
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 712

def use_opn?
  @use_opn
end

#we_may_exitObject

#

we_may_exit

#

498
499
500
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/parse_fasta.rb', line 498

def we_may_exit
  @may_we_exit = true
end