Class: Bioroebe::ParseFasta

Inherits:
CommandlineApplication show all
Defined in:
lib/bioroebe/fasta_and_fastq/parse_fasta/run.rb,
lib/bioroebe/fasta_and_fastq/parse_fasta/menu.rb,
lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb,
lib/bioroebe/fasta_and_fastq/parse_fasta/reset.rb,
lib/bioroebe/fasta_and_fastq/parse_fasta/report.rb,
lib/bioroebe/fasta_and_fastq/parse_fasta/constants.rb,
lib/bioroebe/fasta_and_fastq/parse_fasta/initialize.rb

Overview

Bioroebe::ParseFasta

Constant Summary collapse

NAMESPACE =
#

NAMESPACE

#
inspect
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

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, #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, #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, #is_on_roebe?, #is_palindrome?, #main_encoding?, #mkdir, #move_file, #mv, #no_file_exists_at, #no_newlines, #project_yaml_directory?, #rds, #register_sigint, #return_pwd, #write_what_into

Constructor Details

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

#

initialize

#


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

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[]

#


738
739
740
741
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 738

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.

#


731
732
733
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 731

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

#add_length_information_to_the_headerObject

#

add_length_information_to_the_header

#


615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 615

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().

#


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/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 238

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)


404
405
406
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 404

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)


211
212
213
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 211

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)


307
308
309
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 307

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

#


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/misc.rb', line 94

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.

#


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

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

#


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

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
#


432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 432

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)


164
165
166
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 164

def entries?
  @data
end

#first_key?Boolean

#

first_key?

Obtain the very first entry.

#

Returns:

  • (Boolean)


468
469
470
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 468

def first_key?
  headers?.first
end

#first_valueObject

#

first_value

This will return the first entry of the Fasta files.

#


272
273
274
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 272

def first_value
  sequences?.first
end

#gc_content?Boolean Also known as: gc_content

#

gc_content?

#

Returns:

  • (Boolean)


812
813
814
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 812

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

#hash?Boolean

#

hash?

#

Returns:

  • (Boolean)


315
316
317
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 315

def hash?
  @hash
end

#header?Boolean

#

header?

This variant will always return the first entry.

#

Returns:

  • (Boolean)


477
478
479
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 477

def header?
  headers?.first.to_s
end

#headers?Boolean

#

headers?

#

Returns:

  • (Boolean)


459
460
461
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 459

def headers?
  @hash.keys
end

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

#

is_polynucleotide?

#

Returns:

  • (Boolean)


290
291
292
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 290

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)


765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 765

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)


297
298
299
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 297

def is_this_sequence_a_polynucleotide_sequence?
  !is_protein?
end

#main_sequence?Boolean

#

main_sequence?

This will always return the first entry.

#

Returns:

  • (Boolean)


805
806
807
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 805

def main_sequence?
  @hash.values.first
end
#

menu (menu tag)

#


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

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)


450
451
452
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 450

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

#nucleotides_or_aminoacids?Boolean

#

nucleotides_or_aminoacids?

#

Returns:

  • (Boolean)


279
280
281
282
283
284
285
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 279

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

#opnnObject

#

opnn

#


221
222
223
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 221

def opnn
  super(NAMESPACE) if use_opn?
end

#output_resultsObject

#

output_results

#


178
179
180
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 178

def output_results
  pp @hash
end

#overwrite_the_original_file?Boolean

#

overwrite_the_original_file?

#

Returns:

  • (Boolean)


549
550
551
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 549

def overwrite_the_original_file?
  @internal_hash[:overwrite_the_original_file]
end

#raw_body?Boolean

#

raw_body?

#

Returns:

  • (Boolean)


484
485
486
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 484

def raw_body?
  @hash.values.first
end

#report_how_many_elements_we_have_foundObject

#

report_how_many_elements_we_have_found

#


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

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

#


130
131
132
133
134
135
136
137
138
139
140
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/report.rb', line 130

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

#


145
146
147
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/report.rb', line 145

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

#


68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/report.rb', line 68

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)


152
153
154
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/report.rb', line 152

def report_the_sequence?
  @internal_hash[:report_the_sequence]
end

#resetObject

#

reset (reset tag)

#


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

def reset
  super()
  # ======================================================================= #
  # === @namespace
  # ======================================================================= #
  @namespace = 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

#


411
412
413
414
415
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 411

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

#runObject

#

run (run tag)

#


14
15
16
17
18
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/run.rb', line 14

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

#


185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 185

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"
#


148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 148

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.

#


707
708
709
710
711
712
713
714
715
716
717
718
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 707

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

#


594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 594

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)


542
543
544
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 542

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.

#


689
690
691
692
693
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 689

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
#


827
828
829
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 827

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)


324
325
326
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 324

def sequences?
  @hash.values
end

#set_be_verbose_and_report_the_sequenceObject

#

set_be_verbose_and_report_the_sequence

#


396
397
398
399
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 396

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.

#


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

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.

#


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

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.

#


76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 76

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
  @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)


346
347
348
349
350
351
352
353
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 346

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
#


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 44

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)


65
66
67
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 65

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.

#


640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 640

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.

#


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

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)


746
747
748
749
750
751
752
753
754
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 746

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)


228
229
230
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 228

def use_opn?
  @use_opn
end

#we_may_exitObject

#

we_may_exit

#


171
172
173
# File 'lib/bioroebe/fasta_and_fastq/parse_fasta/misc.rb', line 171

def we_may_exit
  @may_we_exit = true
end