2011-09-14 3 views
0

파일 (genbank)에서 정보를 추출하는 루비 스크립트가 있는데이 데이터를 데이터베이스에로드하고 싶습니다.activerecord를 사용하여 데이터베이스에 데이터를로드하는 방법

require 'rubygems' 
require 'bio' 
require 'snp_db_models' 
establish_connection 

snp_positions_file = File.open("snp_position.txt") 
outfile = File.open("output.txt", "w") 
genome_sequence = Bio::FlatFile.open(Bio::EMBL, "ref.embl").next_entry 

snp_positions = Array.new 
snp_positions_file.gets # header line 
while line = snp_positions_file.gets 
    snp_details = line.chomp.split("\t") 
    snp_seq = snp_details[1] 
    snp_positions << snp_details[1].to_i 
end 


mean_snp_per_base = snp_positions.size/genome_sequence.sequence_length.to_f 
puts "Mean snps per base: #{mean_snp_per_base}" 

#outfile = File.open("/Volumes/DataRAID/Projects/GAS/fastq_files/bowtie_results/snp_annotation/genes_with_higher_snps.tsv", "w") 
outfile.puts("CDS start\tCDS end\tStrand\tGene\tLocus_tag\tnote\tsnp_ID\ttranslation_seq\tProduct\tNo_of_snps_per_gene\tsnp_rate_vs_mean") 

genome_sequence.features do |feature| 
    if feature.feature !~ /gene/i && feature.feature !~ /source/i 
    start_pos = feature.locations.locations.first.from 
    end_pos = feature.locations.locations.first.to 

    number_of_snps_in_gene = (snp_positions & (start_pos..end_pos).to_a).size # intersect finds number of times snp occurs within cds location 
    mean_snp_per_base_in_gene = number_of_snps_in_gene.to_f/(end_pos - start_pos) 

    outfile.print "#{start_pos}\t" 
    outfile.print "#{end_pos}\t" 
    if feature.locations.locations.first.strand == 1 
     outfile.print "forward\t" 
    else 
     outfile.print "reverse\t" 
    end 

    qualifiers = feature.to_hash 

    ["gene", "locus_tag", "note", "snp_id", "translation", "product"].each do |qualifier| 
     if qualifiers.has_key?(qualifier) # if there is gene and product in the file 
     # puts "#{qualifier}: #{qualifiers[qualifier]}" 

     outfile.print "#{qualifiers[qualifier].join(",")}\t" 
     else 
     outfile.print " \t" 
     end 
    end 

    outfile.print "#{number_of_snps_in_gene}\t" 
    outfile.print "%.2f" % (mean_snp_per_base_in_gene/mean_snp_per_base) 
    outfile.puts 
end 
end 
outfile.close 

가 어떻게 데이터베이스에 outfile.txt의 데이터를로드 할 수

require 'active_record' 
def establish_connection(db_location= "protein.db.sqlite3") 
    ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3", 
    :database => db_location, 
    :pool => 5, 
    :timeout => 5000 
) 
end 

이 데이터를 출력 내 스크립트입니다 : 내가 모델과 스키마와 연결 스크립트를 만들었습니다. 마샬 덤프 같은 것을해야합니까? 사전

마크

+0

댓글에 따라 Ruby로 태그가 지정되었습니다. –

답변

0

에서

감사합니다 당신이 할 수있는 레이크 작업을 작성할 수 있습니다. lib/tasks에 저장하고 .rake 확장자를 지정하십시오.

desc "rake task to load data into db" 
task :load_data_db => :environment do 
    ... 
end 

레일 환경이로드되었으므로 모든 Rails 모델/컨트롤러 에서처럼 모델에 직접 액세스 할 수 있습니다. 물론 레이크 작업을 실행할 때 정의 된 환경 변수에 따라 데이터베이스에 연결됩니다.

+0

웹 응용 프로그램을 만들지 않았으므로 lib/tasks가 없습니다. 필자는 activerecord를 사용하여 데이터베이스를 만들었으므로이 데이터를이 데이터에 덤프하려고합니다. – Mark

+0

이 질문은 'Ruby'아래에 'ruby on rails'로 태그되어서는 안됩니다. @ 무례의 접근 방식을 대신 보아라. –

0

단순한 스크립트에서 모델을 알 수 없습니다.

레일스 애플리케이션에서 사용하는 경우 최소한을 정의해야합니다.

class Foo << ActiveRecord:Base 

end 

그렇지 않으면 레일스 컨텍스트에서 레일스 응용 프로그램 세부 정보를 알고있는 레이크 작업을 사용하십시오.

+1

감사합니다.하지만이 방법으로 데이터베이스에 데이터를 덤프 할 수 있습니까? – Mark

+0

db의 열과 테이블을 생성하는 데 필요한 데이터의 각 모델 + 필요한 마이그레이션에 대한 모델을 만들어야합니다. 이 작업이 완료되면 ActiveRecord 구문을 사용하십시오. 'Foo.create (: bar => "value", : baz => 123)' – apneadiving

+0

모델을 생성하고 테이블 등을 생성했습니다. hundereds 라인 및 9 열 파일. 이걸 자동으로 덤프하고 싶습니다. 내가 outfile의 모든 라인을 읽고 그것을 덤프하거나 마샬 덤프 (marshal dump) 같은 것을 사용하는 스크립트를 작성합니까? – Mark