summaryrefslogtreecommitdiff
path: root/lib/compound.rb
blob: c8dd98c240866a16e112d0a3ddc7e6dfa8ad084a (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
# 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 PhysChem::DESCRIPTORS} "  unless params[:descriptor]
    return {params[:descriptor] => PhysChem::DESCRIPTORS[params[:descriptor]]}.to_json
  else
    return PhysChem::DESCRIPTORS.collect{|k, v| "#{k}: #{v}\n"} unless params[:descriptor]
    return PhysChem::DESCRIPTORS[params[:descriptor]]
  end
end

post "/compound/descriptor/?" do
  bad_request_error "Missing Parameter " unless params[:identifier] && params[:descriptor]
  descriptor = params['descriptor'].split(',')
  compound = Compound.from_smiles params[:identifier]
  d = compound.physchem 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 = 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