いよいよ、とりあえずの目標である多様性指数の計算をさせます。ここのページで紹介するのは多様性指数 H' (Shannon's index) の計算だけです。でも、計算式を変えたり少し工夫すれば、他の多様性指数や2地点間の類似度指数なども簡単に計算することができるはずです。
module Prep def prep(data = Calc.new) #引数が無ければ、Calcオブジェクトを作る file_in = open ("data.txt","r") #読み込みモードでファイルを開く while line = file_in.gets #1行読み込んで、lineに代入 line.chomp! #改行文字を除去 plot, species, abundance = line.split(/,/) #「,」で分割 list = List.new(plot,species,abundance) #インスタンス作成 data.add(leleve) #dataにleleveを追加 file_in.close #開いたファイルを閉じる end return data #dataを返す end module_function :prep #prepメソッドを公開p144 end
class List attr_accessor :plot, :species, :abundance def initialize(plot="new_plot", species="new_species", abundance=0) @plot = plot @species = species @abundance = abundance end end class Calc def initialize() #初期化 @list = Array.new #@listというインスタンスを作成 end def add(list) #list @list.push(list) end def diversity_h #h'(底はe)をハッシュで返す。キーはplot、値はabundance。 h_hash = Hash.new(0) #H'の計算結果を入れるハッシュ。キーはplot pi_hash = Hash.new(0) #piを入れるハッシュ。キーはplot+species abundance_hash = Hash.new(0) #abundanceを入れるハッシュ。キーはplot+species sum_hash = Hash.new(0) #piの合計を入れるハッシュ。キーはplot @list.each{|list| #それぞれの@listについて sum_hash[list.plot] += list.abundance plot_species = list.plot + " " + list.species #plotとspeciesを結合 abundance_hash[plot_species] += list.abundance #ハッシュのキーにする } abundance_hash.each_key{|pl_sp| #それぞれのplot+speciesのキーについて plot, species = pl_sp.split(/\s/) #plotとspeciesを分割 pi = abundance_hash[pl_sp] / sum_hash[plot] #pi=abundance/sum pi_hash = {pl_sp=>pi} #plotとspeciesがキー、piが値のハッシュ h_hash[plot] -= pi_hash[pl_sp] * Math::log(pi_hash[pl_sp]) # } return h_hash end end
解析するデータ
の形式は今までのページと同じ形式です。ただ、あまりにデータ数が少ないと、プログラムのありがたみが無いので、ちょっと多めのデータにしました。例によって、Rubyのプログラムのあるフォルダに「data.txt」という名前で保存してください。