Class: Bio::Phylip::DistanceMatrix

Inherits:
Object
  • Object
show all
Defined in:
lib/bio/appl/phylip/distance_matrix.rb

Overview

This is a parser class for phylip distance matrix data created by dnadist, protdist, or restdist commands.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ DistanceMatrix

creates a new distance matrix object



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
# File 'lib/bio/appl/phylip/distance_matrix.rb', line 27

def initialize(str)
  data = str.strip.split(/(?:\r\n|\r|\n)/)
  @otus = data.shift.to_s.strip.to_i
  prev = nil
  data.collect! do |x|
    if /\A +/ =~ x and prev then
      prev.concat x.strip.split(/\s+/)
      nil
    else
      prev = x.strip.split(/\s+/)
      prev
    end
  end
  data.compact!
  if data.size != @otus then
    raise "inconsistent data (OTUs=#{@otus} but #{data.size} rows)"
  end
  @otu_names = data.collect { |x| x.shift }
  mat = data.collect do |x|
    if x.size != @otus then
      raise "inconsistent data (OTUs=#{@otus} but #{x.size} columns)"
    end
    x.collect { |y| y.to_f }
  end
  @matrix = Matrix.rows(mat, false)
  @original_matrix = Matrix.rows(data, false)
end

Instance Attribute Details

#matrixObject (readonly)

distance matrix (returns Ruby’s Matrix object)



56
57
58
# File 'lib/bio/appl/phylip/distance_matrix.rb', line 56

def matrix
  @matrix
end

#original_matrixObject (readonly)

matrix contains values as original strings. Use it when you doubt precision of floating-point numbers.



60
61
62
# File 'lib/bio/appl/phylip/distance_matrix.rb', line 60

def original_matrix
  @original_matrix
end

#otu_namesObject (readonly)

names of OTUs



66
67
68
# File 'lib/bio/appl/phylip/distance_matrix.rb', line 66

def otu_names
  @otu_names
end

#otusObject (readonly)

number of OTUs



63
64
65
# File 'lib/bio/appl/phylip/distance_matrix.rb', line 63

def otus
  @otus
end

Class Method Details

.generate(matrix, otu_names = nil, options = {}) ⇒ Object

Generates a new phylip distance matrix formatted text as a string.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/bio/appl/phylip/distance_matrix.rb', line 69

def self.generate(matrix, otu_names = nil, options = {})
  if matrix.row_size != matrix.column_size then
    raise "must be a square matrix"
  end
  otus = matrix.row_size
  names = (0...otus).collect do |i|
    name = ((otu_names and otu_names[i]) or "OTU#{i.to_s}")
    name
  end
  data = (0...otus).collect do |i|
    x = (0...otus).collect { |j|  sprintf("%9.6f", matrix[i, j]) }
    x.unshift(sprintf("%-10s", names[i])[0, 10])

    str = x[0, 7].join(' ') + "\n"
    7.step(otus + 1, 7) do |k|
      str << ' ' + x[k, 7].join(' ') + "\n"
    end
    str
  end
  sprintf("%5d\n", otus) + data.join('')
end