summaryrefslogtreecommitdiff
path: root/application.rb
blob: 6fc5936da476ce1d218f1cd7612ed29d66b61816 (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
include OpenTox

require 'rack/cors'

set :show_exceptions => false

# add CORS support for swagger
use Rack::Cors do |config|
  config.allow do |allow|
    allow.origins '*'
    allow.resource "/#{SERVICE}/*",
      :methods => [:head, :get, :post, :put, :delete, :options],
      :headers => :any,
      :max_age => 0
  end
end
before do
  @accept = request.env['HTTP_ACCEPT']
  response['Content-Type'] = @accept
end
 
# route to swagger API file
get "/api/api.json" do
  response['Content-Type'] = "application/json"
  api_file = File.join("api", "api.json")
  bad_request_error "API Documentation in Swagger JSON is not implemented.", uri("/#{SERVICE}/api") unless File.exists?(api_file)
  api_hash = JSON.parse(File.read(api_file))
  api_hash["host"] = request.env['HTTP_HOST']
  return api_hash.to_json
end


# Get a list of all prediction models
# @param [Header] Accept one of text/uri-list,
# @return [text/uri-list] list of all prediction models
get "/model/?" do
  models = OpenTox::Model::Prediction.all
  case @accept
  when "text/uri-list"
    uri_list = models.collect{|model| uri("/model/#{model.model_id}")}
    return uri_list.join("\n") + "\n"
  when "application/json"
    models = JSON.parse models.to_json
    models.each_index do |idx|
      models[idx][:URI] = uri("/model/#{models[idx]["model_id"]["$oid"]}")
      models[idx][:crossvalidation_uri] = uri("/crossvalidation/#{models[idx]["crossvalidation_id"]["$oid"]}") if models[idx]["crossvalidation_id"]
    end
    return models.to_json
  else
    bad_request_error "Mime type #{@accept} is not supported."
  end
end

get "/model/:id/?" do
  model = OpenTox::Model::Lazar.find params[:id]
  resource_not_found_error "Model with id: #{params[:id]} not found." unless model
  model[:URI] = uri("/model/#{model.id}")
  model[:neighbor_algorithm_parameters][:feature_dataset_uri] = uri("/dataset/#{model[:neighbor_algorithm_parameters][:feature_dataset_id]}") if model[:neighbor_algorithm_parameters][:feature_dataset_id]
  model[:training_dataset_uri] = uri("/dataset/#{model.training_dataset_id}") if model.training_dataset_id
  model[:prediction_feature_uri] = uri("/dataset/#{model.prediction_feature_id}") if model.prediction_feature_id
  return model.to_json
end



post "/model/:id/?" do
  identifier = params[:identifier].split(",")
  begin
    # get compound from SMILES
    compounds = identifier.collect{ |i| Compound.from_smiles i.strip }
  rescue
    @error_report = "Attention, '#{params[:identifier]}' is not a valid SMILES string."
    return @error_report
  end
  model = OpenTox::Model::Lazar.find params[:id]
  batch = {}
  compounds.each do |compound|
    prediction = model.predict(compound)
    batch[compound] = {:id => compound.id, :inchi => compound.inchi, :smiles => compound.smiles, :model => model, :prediction => prediction}
  end
  return batch.to_json
end

VALIDATION_TYPES = ["repeatedcrossvalidation", "leaveoneout", "crossvalidation", "regressioncrossvalidation"]

# Get a list of all validations 
# @param [Header] Accept one of text/uri-list, application/json
# @param [Path] Validationtype One of "repeatedcrossvalidation", "leaveoneout", "crossvalidation", "regressioncrossvalidation"
# @return [text/uri-list] list of all prediction models
get "/validation/:validationtype/?" do
  bad_request_error "There is no such validation type as: #{params[:validationtype]}" unless VALIDATION_TYPES.include? params[:validationtype]
  case params[:validationtype]
  when "repeatedcrossvalidation"
    validations = OpenTox::Validation::RepeatedCrossValidation.all
  when "leaveoneout"
    validations = OpenTox::Validation::LeaveOneOut.all
  when "crossvalidation"
    validations = OpenTox::Validation::CrossValidation.all
  when "regressioncrossvalidation"
    validations = OpenTox::Validation::RegressionCrossValidation.all
  end

  case @accept
  when "text/uri-list"
    uri_list = validations.collect{|validation| uri("/validation/#{params[:validationtype]}/#{validation.id}")}
    return uri_list.join("\n") + "\n"
  when "application/json"
    validations = JSON.parse validations.to_json
    validations.each_index do |idx|
      validations[idx][:URI] = uri("/validation/#{params[:validationtype]}/#{validations[idx]["$oid"]}")
      #models[idx][:crossvalidation_uri] = uri("/crossvalidation/#{models[idx]["crossvalidation_id"]["$oid"]}") if models[idx]["crossvalidation_id"]
    end
    return validations.to_json
  else
    bad_request_error "Mime type #{@accept} is not supported."
  end
end

get "/validation/:validationtype/:id/?" do
  bad_request_error "There is no such validation type as: #{params[:validationtype]}" unless VALIDATION_TYPES.include? params[:validationtype]
  case params[:validationtype]
  when "repeatedcrossvalidation"
    validation = OpenTox::Validation::RepeatedCrossValidation.find params[:id]
  when "leaveoneout"
    validation = OpenTox::Validation::LeaveOneOut.find params[:id]
  when "crossvalidation"
    validation = OpenTox::Validation::CrossValidation.find params[:id]
  when "regressioncrossvalidation"
    validation = OpenTox::Validation::RegressionCrossValidation.find params[:id]
  end

  resource_not_found_error "#{params[:validationtype]} with id: #{params[:id]} not found." unless validation
  #model[:URI] = uri("/model/#{model.id}")
  #model[:neighbor_algorithm_parameters][:feature_dataset_uri] = uri("/dataset/#{model[:neighbor_algorithm_parameters][:feature_dataset_id]}") if model[:neighbor_algorithm_parameters][:feature_dataset_id]
  #model[:training_dataset_uri] = uri("/dataset/#{model.training_dataset_id}") if model.training_dataset_id
  #model[:prediction_feature_uri] = uri("/dataset/#{model.prediction_feature_id}") if model.prediction_feature_id
  return validation.to_json
end

# Get a list of a single or all descriptors
# @param [Header] Accept one of text/plain, application/json
# @param [Path] Descriptor name (e.G.: Openbabel.HBA1)
# @return [text/plain, application/json] list of all prediction models
get "/compound/descriptor/?:descriptor?" do
  case @accept
  when "application/json"
    return "#{JSON.pretty_generate OpenTox::PhysChem::DESCRIPTORS} "  unless params[:descriptor]
    return {params[:descriptor] => OpenTox::PhysChem::DESCRIPTORS[params[:descriptor]]}.to_json
  else
    return OpenTox::PhysChem::DESCRIPTORS.collect{|k, v| "#{k}: #{v}\n"} unless params[:descriptor]
    return OpenTox::PhysChem::DESCRIPTORS[params[:descriptor]]
  end
end

post "/compound/descriptor/?" do
  bad_request_error "Missing Parameter " unless (params[:identifier] or params[:file]) and params[:descriptor]
  descriptor = params['descriptor'].split(',')
  if params[:file]
    data = OpenTox::Dataset.from_csv_file params[:file][:tempfile]
  else
    data = OpenTox::Compound.from_smiles params[:identifier]
  end
  d = Algorithm::Descriptor.physchem data, descriptor
  csv = d.to_csv
  csv = "SMILES,#{params[:descriptor]}\n#{params[:identifier]},#{csv}" if params[:identifier]
  case @accept
  when "application/csv"
    return csv
  when "application/json"
    lines = CSV.parse(csv)
    keys = lines.delete lines.first
    data = lines.collect{|values|Hash[keys.zip(values)]}
    return JSON.pretty_generate(data)
  end
end

get %r{/compound/(.+)} do |inchi|
  bad_request_error "Input parameter #{inchi} is not an InChI" unless inchi.match(/^InChI=/)
  compound = OpenTox::Compound.from_inchi URI.unescape(inchi)
  response['Content-Type'] = @accept
  case @accept
  when "application/json"
    return JSON.pretty_generate JSON.parse(compound.to_json)
  when "chemical/x-daylight-smiles"
    return compound.smiles
  when "chemical/x-inchi"
    return compound.inchi
  when "chemical/x-mdl-sdfile"
    return compound.sdf
  when "chemical/x-mdl-molfile"
  when "image/png"
    return compound.png
  when "image/svg+xml"
    return compound.svg
  when "text/plain"
    return "#{compound.names}\n"
  else
    return compound.inspect
  end
end