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
|
require 'rdiscount'
require_relative 'qmrf_report.rb'
require_relative 'task.rb'
require_relative 'helper.rb'
include OpenTox
PUBCHEM_CID_URI = PUBCHEM_URI.split("/")[0..-3].join("/")+"/compound/"
[
"api.rb",
"compound.rb",
"dataset.rb",
"endpoint.rb",
"feature.rb",
"model.rb",
"report.rb",
"substance.rb",
"swagger.rb",
"validation.rb"
].each{ |f| require_relative "./lib/#{f}" }
configure :production, :development do
STDOUT.sync = true
$logger = Logger.new(STDOUT)
$logger.level = Logger::DEBUG
enable :reloader
also_reload './helper.rb'
also_reload './qmrf_report.rb'
[
"api.rb",
"compound.rb",
"dataset.rb",
"endpoint.rb",
"feature.rb",
"model.rb",
"report.rb",
"substance.rb",
"swagger.rb",
"validation.rb"
].each{ |f| also_reload "./lib/#{f}" }
end
before do
$paths = [
"api",
"compound",
"dataset",
"endpoint",
"feature",
"model",
"report",
"substance",
"swagger",
"validation"]
if request.path =~ /predict/
@accept = request.env['HTTP_ACCEPT'].split(",").first
response['Content-Type'] = @accept
halt 400, "Mime type #{@accept} is not supported." unless @accept == "text/html" || "*/*"
@version = File.read("VERSION").chomp
else
@accept = request.env['HTTP_ACCEPT'].split(",").first
response['Content-Type'] = @accept
end
end
not_found do
redirect to('/predict')
end
error do
if request.path.split("/")[1] == "api" || $paths.include?(request.path.split("/")[2])
@accept = request.env['HTTP_ACCEPT']
response['Content-Type'] = @accept
@accept == "text/plain" ? request.env['sinatra.error'] : request.env['sinatra.error'].to_json
else
@error = request.env['sinatra.error']
haml :error
end
end
# https://github.com/britg/sinatra-cross_origin#responding-to-options
options "*" do
response.headers["Allow"] = "HEAD,GET,PUT,POST,DELETE,OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept"
200
end
get '/predict/?' do
if params[:tpid]
begin
Process.kill(9,params[:tpid].to_i) if !params[:tpid].blank?
rescue
nil
end
end
@models = OpenTox::Model::Validation.all
@endpoints = @models.collect{|m| m.endpoint}.sort.uniq
@models.count > 0 ? (haml :predict) : (haml :info)
end
get '/predict/modeldetails/:model' do
model = OpenTox::Model::Validation.find params[:model]
training_dataset = model.model.training_dataset
data_entries = training_dataset.data_entries
crossvalidations = model.crossvalidations
if model.classification?
crossvalidations.each do |cv|
File.open(File.join('public', "#{cv.id}.png"), 'w') do |file|
file.write(cv.probability_plot(format: "png"))
end unless File.exists? File.join('public', "#{cv.id}.png")
end
else
crossvalidations.each do |cv|
File.open(File.join('public', "#{cv.id}.png"), 'w') do |file|
file.write(cv.correlation_plot(format: "png"))
end unless File.exists? File.join('public', "#{cv.id}.png")
end
end
response['Content-Type'] = "text/html"
return haml :model_details, :layout=> false, :locals => {:model => model,
:crossvalidations => crossvalidations,
:training_dataset => training_dataset,
:data_entries => data_entries
}
end
get "/predict/report/:id/?" do
prediction_model = Model::Validation.find params[:id]
bad_request_error "model with id: '#{params[:id]}' not found." unless prediction_model
report = qmrf_report params[:id]
# output
t = Tempfile.new
t << report.to_xml
name = prediction_model.species.sub(/\s/,"-")+"-"+prediction_model.endpoint.downcase.sub(/\s/,"-")
send_file t.path, :filename => "QMRF_report_#{name.gsub!(/[^0-9A-Za-z]/, '_')}.xml", :type => "application/xml", :disposition => "attachment"
end
get '/predict/jme_help/?' do
File.read(File.join('views','jme_help.html'))
end
# download training dataset
get '/predict/dataset/:name' do
dataset = Dataset.find_by(:name=>params[:name])
csv = File.read dataset.source
name = params[:name] + ".csv"
t = Tempfile.new
t << csv
t.rewind
response['Content-Type'] = "text/csv"
send_file t.path, :filename => name, :type => "text/csv", :disposition => "attachment"
end
# download batch predicton file
get '/predict/batch/download/?' do
task = Task.find params[:tid]
dataset = Dataset.find task.dataset_id
name = dataset.name + ".csv"
t = Tempfile.new
# to_prediction_csv takes too much time; use task.csv instead which is the same
#t << dataset.to_prediction_csv
t << task.csv
t.rewind
response['Content-Type'] = "text/csv"
send_file t.path, :filename => "#{Time.now.strftime("%Y-%m-%d")}_lazar_batch_prediction_#{name}", :type => "text/csv", :disposition => "attachment"
end
post '/predict/?' do
# process batch prediction
unless params[:fileselect].blank?
if params[:fileselect][:filename] !~ /\.csv$/
bad_request_error "Wrong file extension for '#{params[:fileselect][:filename]}'. Please upload a CSV file."
end
@filename = params[:fileselect][:filename]
File.open('tmp/' + params[:fileselect][:filename], "w") do |f|
f.write(params[:fileselect][:tempfile].read)
end
uploadTask = Task.new
uploadTask.save
uploadDataset = Task.run do
t = uploadTask
t.update_percent(1)
puts "Processing '#{params[:fileselect][:filename]}'"
input = Dataset.from_csv_file File.join("tmp", params[:fileselect][:filename])
t[:dataset_id] = input.id
t.update_percent(100)
t.save
end
@upid = uploadTask.id
@compounds_size = 0 #@input.compounds.size
@models = params[:selection].keys
@tasks = []
@models.each{|m| t = Task.new; t.save; @tasks << t}
@predictions = {}
maintask = Task.run do
@models.each_with_index do |model_id,idx|
t = @tasks[idx]
t.update_percent(1)
prediction = {}
model = Model::Validation.find model_id
t.update_percent(10)
until uploadTask.dataset_id
sleep 1
uploadTask = Task.find @upid
end
@input = Dataset.find uploadTask.dataset_id
prediction_dataset = model.predict @input
t.update_percent(70)
t[:dataset_id] = prediction_dataset.id
t.update_percent(75)
prediction[model_id] = prediction_dataset.id.to_s
t.update_percent(80)
t[:predictions] = prediction
t.update_percent(90)
t[:csv] = prediction_dataset.to_prediction_csv
t.update_percent(100)
t.save
end
end
@pid = maintask.pid
return haml :batch
else
# single compound prediction
# validate identifier input
if !params[:identifier].blank?
@identifier = params[:identifier].strip
$logger.debug "input:#{@identifier}"
# get compound from SMILES
begin
@compound = Compound.from_smiles @identifier
rescue
@error = "'#{@identifier}' is not a valid SMILES string." unless @compound
return haml :error
end
@models = []
@predictions = []
params[:selection].keys.each do |model_id|
model = Model::Validation.find model_id
@models << model
prediction = model.predict(@compound)
@predictions << prediction
end
haml :prediction
end
end
end
get '/prediction/task/?' do
# returns task progress in percentage
if params[:turi]
task = Task.find(params[:turi].to_s)
response['Content-Type'] = "application/json"
if task.dataset_id
d = Dataset.find task.dataset_id
size = d.compounds.size
return JSON.pretty_generate(:percent => task.percent, :size => size)
else
return JSON.pretty_generate(:percent => task.percent)
end
# kills task process id
elsif params[:ktpid]
begin
Process.kill(9,params[:ktpid].to_i) if !params[:ktpid].blank?
rescue
nil
end
response['Content-Type'] = "application/json"
return JSON.pretty_generate(:ktpid => params[:ktpid])
# returns task details
elsif params[:predictions]
task = Task.find(params[:predictions])
pageSize = params[:pageSize].to_i - 1
pageNumber= params[:pageNumber].to_i - 1
csv = CSV.parse(task.csv)
header = csv.shift
string = "<td><table class=\"table table-bordered\">"
# find canonical smiles column
cansmi = 0
header.each_with_index do |h,idx|
cansmi = idx if h =~ /Canonical SMILES/
string += "<th class=\"fit\">#{h}</th>"
end
string += "</tr>"
string += "<tr>"
csv[pageNumber].each_with_index do |line,idx|
if idx == cansmi
c = Compound.from_smiles line
string += "<td class=\"fit\">#{line}</br>" \
"<a class=\"btn btn-link\" data-id=\"link\" " \
"data-remote=\"#{to("/prediction/#{c.id}/details")}\" data-toggle=\"modal\" " \
"href=#details>" \
"#{embedded_svg(c.svg, title: "click for details")}" \
"</td>"
else
string += "<td nowrap>#{line.numeric? && line.include?(".") ? line.to_f.signif(3) : (line.nil? ? line : line.gsub(" ","<br />"))}</td>"
end
end
string += "</tr>"
string += "</table></td>"
response['Content-Type'] = "application/json"
return JSON.pretty_generate(:prediction => [string])
end
end
# get individual compound details
get '/prediction/:neighbor/details/?' do
@compound = OpenTox::Compound.find params[:neighbor]
@smiles = @compound.smiles
begin
@names = @compound.names.nil? ? "No names for this compound available." : @compound.names
rescue
@names = "No names for this compound available."
end
@inchi = @compound.inchi
haml :details, :layout => false
end
get '/predict/license' do
@license = RDiscount.new(File.read("LICENSE.md")).to_html
haml :license, :layout => false
end
get '/predict/faq' do
@faq = RDiscount.new(File.read("FAQ.md")).to_html
haml :faq#, :layout => false
end
get '/predict/help' do
haml :help
end
get '/style.css' do
headers 'Content-Type' => 'text/css; charset=utf-8'
scss :style
end
# for swagger representation
get '/api/swagger-ui.css' do
headers 'Content-Type' => 'text/css; charset=utf-8'
scss :style
end
get '/IST_logo_s.png' do
redirect to('/images/IST_logo_s.png')
end
|