Module: Organism

Extended by:
Resource
Defined in:
lib/rbbt/sources/organism.rb

Defined Under Namespace

Classes: OrganismNotProcessedError

Constant Summary collapse

ARCHIVE_MONTH_INDEX =
{}

Class Method Summary collapse

Class Method Details

.allowed_biomart_archivesObject



65
66
67
68
69
# File 'lib/rbbt/sources/organism.rb', line 65

def self.allowed_biomart_archives
  Rbbt.etc.allowed_biomart_archives.exists? ? 
    Rbbt.etc.allowed_biomart_archives.list :
    nil
end

.attach_translations(org, tsv, target = nil, fields = nil, options = {}) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
# File 'lib/rbbt/sources/organism.rb', line 191

def self.attach_translations(org, tsv, target = nil, fields = nil, options = {})
  Log.high "Attaching Translations for #{ org.inspect }, target #{target.inspect}, fields #{fields.inspect}"
  options = Misc.add_defaults options, :persist => true, :case_insensitive => false

  options.merge! :key_field    => target unless target.nil?
  options.merge! :fields => fields unless fields.nil?

  index = identifiers(org).tsv options

  tsv.attach index, :fields => [:key], :persist_input => true
end

.chromosome_sizes(organism = Organism.default_code("Hsa")) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/rbbt/sources/organism.rb', line 335

def self.chromosome_sizes(organism = Organism.default_code("Hsa"))
  chromosome_sizes = {}

  Organism.chromosomes(organism).produce.tsv.each do |chr|
    file = Organism[organism]["chromosome_#{chr}"].produce.find
    chromosome = file.split("_").last.split(".").first
    size = if Open.gzip?(file) || Open.bgzip?(file)
             CMD.cmd("zcat '#{ file }' | wc -c ").read
           else
             File.size(file)
           end
    chromosome_sizes[chromosome] = size.to_i
  end

  chromosome_sizes
end

.compare_archives(a1, a2) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rbbt/sources/organism.rb', line 16

def self.compare_archives(a1, a2)
  a1 = a1.partition("/").last if a1 and a1.include? "/"
  a2 = a2.partition("/").last if a2 and a2.include? "/"
  return 0 if a1 == a2
  return -1 if a1 and a2.nil?
  return 1 if a1.nil? and a2

  m1,y1 = a1.match(/(...)(\d+)/).values_at 1, 2
  m2,y2 = a2.match(/(...)(\d+)/).values_at 1, 2

  y1 = y1.to_f
  y2 = y2.to_f

  ycmp = y1 <=> y2
  return ycmp unless ycmp == 0

  ARCHIVE_MONTH_INDEX[m1] <=> ARCHIVE_MONTH_INDEX[m2]
end

.default_code(organism = "Hsa") ⇒ Object



35
36
37
38
# File 'lib/rbbt/sources/organism.rb', line 35

def self.default_code(organism = "Hsa")
  latest = Rbbt.etc.allowed_biomart_archives.list.sort{|a,b| compare_archives(a, b)}.last
  organism.split("/").first << "/" << latest
end

.entrez_taxid_organism(taxid) ⇒ Object



275
276
277
278
279
280
281
282
283
# File 'lib/rbbt/sources/organism.rb', line 275

def self.entrez_taxid_organism(taxid)
  all_organisms = Organism.installable_organisms

  all_organisms.each do |organism|
    return organism if Organism.entrez_taxids(organism).read.split("\n").include? taxid.to_s
  end

  raise "No organism identified for taxid #{taxid}. Supported organism are: #{all_organisms * ", "}"
end

.gene_list_bases(genes, organism = nil) ⇒ Object



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/rbbt/sources/organism.rb', line 285

def self.gene_list_bases(genes, organism = nil)
  if genes.respond_to? :orgnanism
    organism = genes.organism if organism.nil?
    genes = genes.clean_annotations
  end

  organism ||= "Hsa"

  @@gene_start_end ||= {}
  gene_start_end = @@gene_start_end[organism] ||= Organism.gene_positions(organism).tsv(:persist => true, :key_field => "Ensembl Gene ID", :fields => ["Gene Start", "Gene End"], :type => :list, :cast => :to_i, :unnamed => true)

  ranges = genes.collect{|gene| 
    start, eend = gene_start_end[gene]
    if start.nil? or eend.nil?
      Log.low "Gene #{ gene } does not have range" 
      next 
    end
    (start..eend) 
  }.compact
  Misc.total_length(ranges)
end

.gene_list_exon_bases(genes, organism = nil) ⇒ Object



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/rbbt/sources/organism.rb', line 307

def self.gene_list_exon_bases(genes, organism = nil)
  if genes.respond_to? :orgnanism
    organism = genes.organism if organism.nil?
    genes = genes.clean_annotations
  end

  organism ||= "Hsa"

  @@gene_exons_tsv ||= {}
  gene_exons = @@gene_exons_tsv[organism] ||= Organism.exons(organism).tsv(:persist => true, :key_field => "Ensembl Gene ID", :fields => ["Ensembl Exon ID"], :type => :flat, :merge => true, :unnamed => true)

  @@exon_range_tsv ||= {}
  exon_ranges = @@exon_range_tsv[organism] ||= Organism.exons(organism).tsv(:persist => true, :fields => ["Exon Chr Start", "Exon Chr End"], :type => :list, :cast => :to_i, :unnamed => true)

  exons = gene_exons.values_at(*genes).compact.flatten.uniq

  exon_ranges = exons.collect{|exon|
    if not exon_ranges.include? exon
      Log.low "Exon #{ exon } does not have range" 
      next 
    end
    pos = exon_ranges[exon]
    (pos.first..pos.last)
  }.compact
  
  Misc.total_length(exon_ranges)
end

.GRC_build(organism, with_release = false) ⇒ Object



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
137
138
139
140
# File 'lib/rbbt/sources/organism.rb', line 103

def self.GRC_build(organism, with_release = false)
  require 'rbbt/sources/ensembl_ftp'
  return organism if organism =~ /^GRC$/

  if organism == "hg19" || organism == "b37"
    return "GRCh37"
  elsif organism == "hg38"
    return "GRCh38"
  end

  return self.GRC_build(default_code(organism)) unless organism =~ /\//

  species, date = organism.split("/")

  build = case species
          when "Hsa"
            date = organism.split("/")[1] 

            release = Ensembl.releases[date]

            release_number = release.sub(/.*-/,'').to_i
            if release_number <= 54 
              'GRCh36'
            elsif release_number <= 75
              'GRCh37'
            else
              'GRCh38'
            end
          when "Mmu"
            "GRCm38"
          when "Rno"
            "Rnor_6.0"
          else
            raise "Only organism 'Hsa' (Homo sapiens) and Mmu (Mus musculus) supported" 
          end

  (release_number && with_release) ? build + "." + release_number.to_s : build
end

.guess_id(org, values) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/rbbt/sources/organism.rb', line 229

def self.guess_id(org, values)
  field_matches = TSV.field_match_counts(Organism.identifiers(org).produce, values)
  best = nil
  best_count = 0
  field_matches.each do |field,count|
    if count >  best_count
      best = field
      best_count = count
    end
  end
  [best, best_count]
end

.hg_build(organism) ⇒ Object



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
# File 'lib/rbbt/sources/organism.rb', line 71

def self.hg_build(organism)
  require 'rbbt/sources/ensembl_ftp'
  organism = organism.strip 
  return organism if organism =~ /^hg\d\d$/

  return organism unless organism =~ /\//

  species, date = organism.split("/")

  case species
  when "Hsa"
    date = organism.split("/")[1] 

    release = Ensembl.releases[date]

    release_number = release.sub(/.*-/,'').to_i
    if release_number <= 54 
      'hg18'
    elsif release_number <= 75
      'hg19'
    else
      'hg38'
    end
  when "Mmu"
    "mm10"
  when "Rno"
    "rn6"
  else
    raise "Only organism 'Hsa' (Homo sapiens), 'Rno' (Rattus norvegicus), and Mmu (Mus musculus) supported" 
  end
end

.installable_organismsObject



61
62
63
# File 'lib/rbbt/sources/organism.rb', line 61

def self.installable_organisms
  self.installed_organisms
end

.installed_organismsObject



50
51
52
53
# File 'lib/rbbt/sources/organism.rb', line 50

def self.installed_organisms
  Rbbt.share.install.Organism.find.glob('???').collect{|f| File.basename(f) } + 
  Rbbt.share.install.Organism.find.glob('*.rake').collect{|f| File.basename(f).sub(/\.rake/, '') }
end

.known_ids(name) ⇒ Object



271
272
273
# File 'lib/rbbt/sources/organism.rb', line 271

def self.known_ids(name)
  TSV::Parser.new(Organism.identifiers(name).open).all_fields
end

.liftOver(positions, source, target) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/rbbt/sources/organism.rb', line 150

def self.liftOver(positions, source, target)

  source_hg = hg_build(source)
  target_hg = hg_build(target)

  map_url = "http://hgdownload.cse.ucsc.edu/goldenPath/#{source_hg}/liftOver/#{source_hg}To#{target_hg.sub('h', 'H')}.over.chain.gz" 

  positions_bed = positions.collect{|position| 
    chr, pos = position.split(":").values_at(0,1)
    ["chr" << chr, pos.to_i-1, pos, position] * "\t"
  } * "\n" + "\n"

  new_positions = {}

  TmpFile.with_file(positions_bed) do |source_bed|
    TmpFile.with_file do |unmapped_file|
      TmpFile.with_file do |map_file|


        Open.write(map_file, Open.read(map_url))
        new_mutations = TmpFile.with_file do |target_bed|
          CMD.cmd_log(:liftOver, "'#{source_bed}' '#{map_file}' '#{target_bed}' '#{unmapped_file}'")
          Open.read(target_bed) do |line|
            chr, position_alt, position, name = line.chomp.split("\t")
            chr.sub! /chr/, ''

            old_chr, old_position, *rest = name.split(":")
            new_positions[name] = ([chr, position].concat rest) * ":"
          end
        end
      end
    end
  end

  positions.collect do |position|
    new_positions[position]
  end
end

.make_organism(name, long = false) ⇒ Object



250
251
252
253
254
255
256
257
# File 'lib/rbbt/sources/organism.rb', line 250

def self.make_organism(name, long = false)
  first, _, second = name.partition(/[ _]/)
  if long
    first[0].upcase + second.downcase.gsub(/[^a-z]/,'')
  else
    first[0].upcase + second[0..1].downcase
  end
end

.normalize(org, list, target = nil, fields = nil, options = {}) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/rbbt/sources/organism.rb', line 203

def self.normalize(org, list, target = nil, fields = nil, options = {})
  return [] if list.nil? or list.empty?
  options = Misc.add_defaults options, :persist => true, :case_insensitive => true, :double => false
  double = Misc.process_options options, :double


  options.merge! :target => target unless target.nil?
  options.merge! :fields => fields unless fields.nil?

  index = identifiers(org).index options

  if Array === list
    if double
      index.values_at *list
    else
      index.values_at(*list).collect{|e| Misc.first e}
    end
  else
    if double
      index[list]
    else
      index[list].first
    end
  end
end

.organism(name) ⇒ Object



259
260
261
262
263
# File 'lib/rbbt/sources/organism.rb', line 259

def self.organism(name)
  installable_organisms.select{|organism|
    organism == name or Organism.scientific_name(organism) =~ /#{ name }/i
  }.first
end

.organism_code(name) ⇒ Object



265
266
267
268
269
# File 'lib/rbbt/sources/organism.rb', line 265

def self.organism_code(name)
  organisms.select{|organism|
    organism == name or Organism.scientific_name(organism) =~ /#{ name }/i
  }.first
end

.organism_codes(organism = nil) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/rbbt/sources/organism.rb', line 40

def self.organism_codes(organism = nil)
  if organism
    Rbbt.etc.allowed_biomart_archives.list.collect{|build| [organism, build] * "/" }
  else
    Rbbt.etc.organisms.list.collect{|organism|
      organism =~ /\// ? organism : Rbbt.etc.allowed_biomart_archives.list.collect{|build| [organism, build] * "/" } + [organism]
    }.flatten.compact.uniq 
  end
end

.organism_for_build(build) ⇒ Object



142
143
144
145
146
147
148
# File 'lib/rbbt/sources/organism.rb', line 142

def self.organism_for_build(build)
  build = build.sub('_noalt', '')

  build_organism = Rbbt.etc.build_organism.tsv :type => :single

  build_organism[build]
end

.organismsObject



242
243
244
# File 'lib/rbbt/sources/organism.rb', line 242

def self.organisms
  Dir.glob(File.join(Organism.root.find, '*')).collect{|f| File.basename(f)}
end

.prepared_organismsObject



55
56
57
58
59
# File 'lib/rbbt/sources/organism.rb', line 55

def self.prepared_organisms
  Rbbt.share.organisms.glob_all("???/???????/{identifiers,chromosome_1,scientific_name}").collect{|f| 
    [File.basename(File.dirname(File.dirname(f))), File.basename(File.dirname(f))] * "/"
  }.uniq
end

.rake_organism_helperObject



12
13
14
# File 'lib/rbbt/sources/organism.rb', line 12

def self.rake_organism_helper
  Rbbt.share.install.Organism["organism_helpers.rb"].find
end

.scientific_name(organism) ⇒ Object



246
247
248
# File 'lib/rbbt/sources/organism.rb', line 246

def self.scientific_name(organism)
  Organism[organism].scientific_name.read.strip
end