summaryrefslogtreecommitdiff
path: root/lib/dataset.rb
blob: 84dce654f7602f2212a13a1308cbf4bfaf49c5e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
102
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
141
142
143
144
145
146
147
148
149
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
module OpenTox
  
  # Ruby wrapper for OpenTox Dataset Webservices (http://opentox.org/dev/apis/api-1.2/dataset).
  # TODO: fix API Doc
  class Dataset 

    include OpenTox

    attr_reader :features, :compounds, :data_entries, :metadata

    # Create dataset with optional URI. Does not load data into the dataset - you will need to execute one of the load_* methods to pull data from a service or to insert it from other representations.
    # @example Create an empty dataset
    #   dataset = OpenTox::Dataset.new
    # @example Create an empty dataset with URI
    #   dataset = OpenTox::Dataset.new("http:://webservices.in-silico/ch/dataset/1")
    # @param [optional, String] uri Dataset URI
    # @return [OpenTox::Dataset] Dataset object
    def initialize(uri=nil,subjectid=nil)
      super uri, subjectid
      @features = {}
      @compounds = []
      @data_entries = {}
    end

    # Create an empty dataset and save it at the dataset service (assigns URI to dataset)
    # @example Create new dataset and save it to obtain a URI 
    #   dataset = OpenTox::Dataset.create
    # @param [optional, String] uri Dataset URI
    # @return [OpenTox::Dataset] Dataset object
    def self.create(uri=CONFIG[:services]["opentox-dataset"], subjectid=nil)
      dataset = Dataset.new(nil,subjectid)
      dataset.save
      dataset
    end
    
    # Find a dataset and load all data. This can be time consuming, use Dataset.new together with one of the load_* methods for a fine grained control over data loading.
    # @param [String] uri Dataset URI
    # @return [OpenTox::Dataset] Dataset object with all data
    def self.find(uri, subjectid=nil)
      return nil unless uri
      dataset = Dataset.new(uri, subjectid)
      dataset.load_metadata
      dataset
    end

    # Create dataset from CSV file (format specification: http://toxcreate.org/help)
    # - loads data_entries, compounds, features
    # - sets metadata (warnings) for parser errors
    # - you will have to set remaining metadata manually
    # @param [String] file CSV file path
    # @return [OpenTox::Dataset] Dataset object with CSV data
    def self.create_from_csv_file(file, subjectid=nil) 
      dataset = Dataset.create(CONFIG[:services]["opentox-dataset"], subjectid)
      #RestClientWrapper.post(dataset.uri,File.read(file), {:content_type => "text/csv", :subjectid => @subjectid}) 
      RestClientWrapper.post(dataset.uri,{:file => File.new(file)},{:accept => "text/uri-list", :subjectid => subjectid})#, {:content_type => "text/csv", :subjectid => @subjectid}) 
      dataset.load_metadata
      dataset
    end
    
    # replaces find as exist check, takes not as long, does NOT raise an un-authorized exception
    # @param [String] uri Dataset URI
    # @return [Boolean] true if dataset exists and user has get rights, false else 
    def self.exist?(uri, subjectid=nil)
      return false unless uri
      dataset = Dataset.new(uri, subjectid)
      begin
        dataset.load_metadata.size > 0
      rescue
        false
      end
    end

    # Get all datasets from a service
    # @param [optional,String] uri URI of the dataset service, defaults to service specified in configuration
    # @return [Array] Array of dataset object without data (use one of the load_* methods to pull data from the server)
    def self.all(uri=CONFIG[:services]["opentox-dataset"], subjectid=nil)
      RestClientWrapper.get(uri,{:accept => "text/uri-list",:subjectid => subjectid}).to_s.each_line.collect{|u| Dataset.new(u.chomp, subjectid)}
    end

    # Load YAML representation into the dataset
    # @param [String] yaml YAML representation of the dataset
    # @return [OpenTox::Dataset] Dataset object with YAML data
    def store_yaml(yaml)
      RestClientWrapper.post(@uri,yaml, {:content_type => "application/x-yaml", :subjectid => @subjectid}) 
    end

    def store_rdfxml(rdfxml)
      RestClientWrapper.post(@uri, rdfxml, {:content_type => "application/rdf+xml", :subjectid => @subjectid}) 
    end

    # Load RDF/XML representation from a file
    # @param [String] file File with RDF/XML representation of the dataset
    # @return [OpenTox::Dataset] Dataset object with RDF/XML data
    def store_rdfxml_file(file)
      #RestClientWrapper.post(@uri, :file => File.new(file))#, {:content_type => "application/rdf+xml", :subjectid => @subjectid}) 
      RestClientWrapper.post(@uri, File.read(file), {:content_type => "application/rdf+xml", :subjectid => @subjectid}) 
    end

    # Load CSV string (format specification: http://toxcreate.org/help)
    # - loads data_entries, compounds, features
    # - sets metadata (warnings) for parser errors
    # - you will have to set remaining metadata manually
    # @param [String] csv CSV representation of the dataset
    # @return [OpenTox::Dataset] Dataset object with CSV data
    def store_csv(csv) 
      RestClientWrapper.post(@uri, csv, {:content_type => "text/csv", :subjectid => @subjectid}) 
    end

    # Load Spreadsheet book (created with roo gem http://roo.rubyforge.org/, excel format specification: http://toxcreate.org/help)
    # - loads data_entries, compounds, features
    # - sets metadata (warnings) for parser errors
    # - you will have to set remaining metadata manually
    # @param [Excel] book Excel workbook object (created with roo gem)
    # @return [OpenTox::Dataset] Dataset object with Excel data
    def store_spreadsheet_file(file)
      RestClientWrapper.post(@uri, :file => File.new(file))#, {:content_type => "application/vnd.ms-excel", :subjectid => @subjectid}) 
    end
    
    # Load and return only metadata of a Dataset object
    # @return [Hash] Metadata of the dataset
    def load_metadata
      if (CONFIG[:yaml_hosts].include?(URI.parse(@uri).host))
        @metadata = YAML.load(RestClientWrapper.get(File.join(@uri,"metadata"), {:accept => "application/x-yaml", :subjectid => @subjectid}))
      else
        add_metadata Parser::Owl::Dataset.new(@uri, @subjectid).load_metadata
      end
      self.uri = @uri if @uri # keep uri
      @metadata
    end

    # Load all data (metadata, data_entries, compounds and features) from URI
    def load_all
      if (CONFIG[:yaml_hosts].include?(URI.parse(@uri).host))
        copy YAML.load(RestClientWrapper.get(@uri, {:accept => "application/x-yaml", :subjectid => @subjectid}))
      else
        parser = Parser::Owl::Dataset.new(@uri, @subjectid)
        copy parser.load_uri
      end
    end

    # Load and return only compound URIs from the dataset service
    # @return [Array]  Compound URIs in the dataset
    def load_compounds
      RestClientWrapper.get(File.join(uri,"compounds"),{:accept=> "text/uri-list", :subjectid => @subjectid}).to_s.each_line do |compound_uri|
        @compounds << compound_uri.chomp
      end
      @compounds.uniq!
    end

    # Load and return only features from the dataset service
    # @return [Hash]  Features of the dataset
    def load_features
      if (CONFIG[:yaml_hosts].include?(URI.parse(@uri).host))
        @features = YAML.load(RestClientWrapper.get(File.join(@uri,"features"), {:accept => "application/x-yaml", :subjectid => @subjectid}))
      else
        parser = Parser::Owl::Dataset.new(@uri, @subjectid)
        @features = parser.load_features
      end
      @features
    end

    # returns the accept_values of a feature, i.e. the classification domain / all possible feature values 
    # @param [String] feature the URI of the feature
    # @return [Array] return array with strings, nil if value is not set (e.g. when feature is numeric)
    def accept_values(feature)
      load_features
      accept_values = features[feature][OT.acceptValue]
      accept_values.sort if accept_values
      accept_values
    end

    # Detect feature type(s) in the dataset
    # @return [String] `classification", "regression", "mixed" or unknown`
    def feature_type
      load_features
      feature_types = @features.collect{|f,metadata| metadata[RDF.type]}.flatten.uniq
      if feature_types.include?(OT.NominalFeature)
        "classification"
      elsif feature_types.include?(OT.NumericFeature)
        "regression"
      else
        "unknown"
      end
    end

    # Get Spreadsheet representation
    # @return [Spreadsheet::Workbook] Workbook which can be written with the spreadsheet gem (data_entries only, metadata will will be discarded))
    def to_spreadsheet
      Spreadsheet::Workbook.new(RestClientWrapper.get(@uri, {:accept => "application/vnd.ms-excel", :subjectid => @subjectid}))
    end

    # Get Excel representation (alias for to_spreadsheet)
    # @return [Spreadsheet::Workbook] Workbook which can be written with the spreadsheet gem (data_entries only, metadata will will be discarded))
    def to_xls
      to_spreadsheet
    end

    # Get CSV string representation (data_entries only, metadata will be discarded)
    # @return [String] CSV representation
    def to_csv
      RestClientWrapper.get(@uri, {:accept => "text/csv", :subjectid => @subjectid})
    end

    # Get OWL-DL in ntriples format
    # @return [String] N-Triples representation
    def to_ntriples
      RestClientWrapper.get(@uri, {:accept => "application/rdf+xml", :subjectid => @subjectid})
    end

    # Get OWL-DL in RDF/XML format
    # @return [String] RDF/XML representation
    def to_rdfxml
      RestClientWrapper.get(@uri, {:accept => "application/rdf+xml", :subjectid => @subjectid})
    end

    # Get name (DC.title) of a feature
    # @param [String] feature Feature URI
    # @return [String] Feture title
    def feature_name(feature)
      load_features
      @features[feature][DC.title]
    end

    def title
      load_metadata
      @metadata[DC.title]
    end

    # Insert a statement (compound_uri,feature_uri,value)
    # @example Insert a statement (compound_uri,feature_uri,value)
    #   dataset.add "http://webservices.in-silico.ch/compound/InChI=1S/C6Cl6/c7-1-2(8)4(10)6(12)5(11)3(1)9", "http://webservices.in-silico.ch/dataset/1/feature/hamster_carcinogenicity", true
    # @param [String] compound Compound URI
    # @param [String] feature Compound URI
    # @param [Boolean,Float] value Feature value
    def add (compound,feature,value)
      @compounds << compound unless @compounds.include? compound
      @features[feature] = {}  unless @features[feature]
      @data_entries[compound] = {} unless @data_entries[compound]
      @data_entries[compound][feature] = [] unless @data_entries[compound][feature]
      @data_entries[compound][feature] << value if value!=nil
    end

    # Add a feature
    # @param [String] feature Feature URI
    # @param [Hash] metadata Hash with feature metadata
    def add_feature(feature,metadata={})
      @features[feature] = metadata
    end

    # Add/modify metadata for a feature
    # @param [String] feature Feature URI
    # @param [Hash] metadata Hash with feature metadata
    def add_feature_metadata(feature,metadata)
      metadata.each { |k,v| @features[feature][k] = v }
    end
    
    # Add a new compound
    # @param [String] compound Compound URI
    def add_compound (compound)
      @compounds << compound unless @compounds.include? compound
    end
    
    # Creates a new dataset, by splitting the current dataset, i.e. using only a subset of compounds and features
    # @param [Array] compounds List of compound URIs
    # @param [Array] features List of feature URIs
    # @param [Hash] metadata Hash containing the metadata for the new dataset
    # @param [String] subjectid
    # @return [OpenTox::Dataset] newly created dataset, already saved
    def split( compounds, features, metadata)
      LOGGER.debug "split dataset using "+compounds.size.to_s+"/"+@compounds.size.to_s+" compounds"
      raise "no new compounds selected" unless compounds and compounds.size>0
      dataset = OpenTox::Dataset.create(CONFIG[:services]["opentox-dataset"],@subjectid)
      if features.size==0
        compounds.each{ |c| dataset.add_compound(c) }
      else
        compounds.each do |c|
          features.each do |f|
            if @data_entries[c]==nil or @data_entries[c][f]==nil
              dataset.add(c,f,nil)
            else
              @data_entries[c][f].each do |v|
                dataset.add(c,f,v)
              end
            end
          end
        end
      end
      # set feature metadata in new dataset accordingly (including accept values)      
      features.each do |f|
        self.features[f].each do |k,v|
          dataset.features[f][k] = v
        end
      end
      dataset.add_metadata(metadata)
      dataset.save
      dataset
    end

    # Save dataset at the dataset service 
    # - creates a new dataset if uri is not set
    # - overwrites dataset if uri exists
    # @return [String] Dataset URI
    def save
      @compounds.uniq!
      # create dataset if uri is empty
      self.uri = RestClientWrapper.post(CONFIG[:services]["opentox-dataset"],{:subjectid => @subjectid}).to_s.chomp unless @uri
      if (CONFIG[:yaml_hosts].include?(URI.parse(@uri).host))
        RestClientWrapper.post(@uri,self.to_yaml,{:content_type =>  "application/x-yaml", :subjectid => @subjectid})
      else
        s = Serializer::Owl.new
        s.add_dataset(self)
        RestClientWrapper.post(@uri, s.to_rdfxml,{:content_type => "application/rdf+xml" , :subjectid => @subjectid})
      end
      @uri
    end

    # Delete dataset at the dataset service
    def delete
      RestClientWrapper.delete(@uri, :subjectid => @subjectid)
    end

    private
    # Copy a dataset (rewrites URI)
    def copy(dataset)
      @metadata = dataset.metadata
      @data_entries = dataset.data_entries
      @compounds = dataset.compounds
      @features = dataset.features
      if @uri
        self.uri = @uri 
      else
        @uri = dataset.metadata[XSD.anyURI]
      end
    end
  end

  # Class with special methods for lazar prediction datasets
  class LazarPrediction < Dataset

    # Find a prediction dataset and load all data. 
    # @param [String] uri Prediction dataset URI
    # @return [OpenTox::Dataset] Prediction dataset object with all data
    def self.find(uri, subjectid=nil)
      prediction = LazarPrediction.new(uri, subjectid)
      prediction.load_all
      prediction
    end

    def value(compound)
      @data_entries[compound.uri].collect{|f,v| v.first if f.match(/value/)}.compact.first
    end

    def confidence(compound)
      @data_entries[compound.uri].collect{|f,v| v.first if f.match(/confidence/)}.compact.first
    end

    def descriptors(compound)
      @data_entries[compound.uri].collect{|f,v| @features[f] if f.match(/descriptor/)}.compact if @data_entries[compound.uri]
    end

    def measured_activities(compound)
      source = @metadata[OT.hasSource]
      @data_entries[compound.uri].collect{|f,v| v if f.match(/#{source}/)}.compact.flatten
    end

    def neighbors(compound)
      @data_entries[compound.uri].collect{|f,v| @features[f] if f.match(/neighbor/)}.compact
    end

  end
end