我有一个简单的类来模拟DNA字符串中的随机突变。它将随机(A C G T)字符引入随机位置。我想介绍一种指定变异率的方法。
有没有办法可以指定如何:
这是我当前的实现,仅处理随机更改。
class DNA
attr_accessor :number_of_mutations
attr_accessor :seq
NUCLEOTIDES = ['A','C','T','G']
#random positions
def random_pos
(1..seq.length).to_a.sample(number_of_mutations)
end
#pick a random nucleotide
def random_nucleotide
NUCLEOTIDES.sample
end
#generate a random seq
def random_seq
(1..number_of_mutations).map{NUCLEOTIDES[rand(NUCLEOTIDES.length)]}
end
def mutate
#pick a random position
positions = random_pos
#pick a random nucleotide
nucleotides = random_seq
#insert the random nucleotide at the random position in the seq
positions.zip(nucleotides).map do |pos,nuc|
seq[pos] = nuc.downcase
end
seq
end
end
d = DNA.new
d.number_of_mutations = 1
d.seq = "AAAAAA"
puts d.mutate #will introduce a single random DNA base at a random location
答案 0 :(得分:0)
首先,您应该实现一个以指定的速率返回正结果的函数。它可能是这样的:
# ==Function will return true with rate probability
def positive?(rate = 0.001)
rand((1/rate).round) == 0
end
或更复杂。
你可以用指定的速率实现突变机制。它可以是Mutators类的实例
class Mutator
attr_reader :mutate_way, :probability
def initialize(options = {})
@mutate_way = options[:mutate_way]
@probability = options[:probability]
end
def try_mutate
do_mutation if positive? @probability
end
def do_mutation
# your implementation based on @mutate_way
# link it with DNA
end
end
您可以定义许多突变,例如
mutations = [
Mutator.new(:mutate_way => ['A', 'G'], :probability => 100),
Mutator.new(:mutate_way => ['C', 'T'], :probability => 100),
Mutator.new(:mutate_way => ['A', 'T'], :probability => 1000),
Mutator.new(:mutate_way => ['C', 'G'], :probability => 1000)
]
并开始突变
d.number_of_mutations.times do
mutations.each.map(&:try_mutate)
end
PS。代码示例可能有一些错误,这只是示例。