summaryrefslogtreecommitdiff
path: root/compound.rb
blob: 7ed4589b50cb16625c716e952311d67253e248a7 (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
require "openbabel"
module OpenTox

  # Perform OpenBabel conversions locally in order to prevent net overhead
	class Compound 

    attr_writer :smiles, :inchi

    # Create a compound from smiles string
    # @example
    #   compound = OpenTox::Compound.from_smiles("c1ccccc1")
    # @param [String] smiles Smiles string
    # @return [OpenTox::Compound] Compound
    def self.from_smiles smiles
			inchi = obconversion(smiles,'smi','inchi')
      compound = Compound.new(File.join service_uri, inchi)
      compound.inchi = inchi
      compound.smiles = smiles
      compound
    end

    # Create a compound from inchi string
    # @param [String] smiles InChI string
    # @return [OpenTox::Compound] Compound
    def self.from_inchi inchi
      compound = Compound.new(File.join service_uri, inchi)
      compound.inchi = inchi
      compound
    end

    # Create a compound from sdf string
    # @param [String] smiles SDF string
    # @return [OpenTox::Compound] Compound
    def self.from_sdf sdf
			inchi = obconversion(sdf,'sdf','inchi')
      compound = Compound.new(File.join service_uri, inchi)
      compound.inchi = inchi
      compound
    end

    private
    
    # Convert identifier from OpenBabel input_format to OpenBabel output_format
    def self.obconversion(identifier,input_format,output_format)
      obconversion = OpenBabel::OBConversion.new
      obmol = OpenBabel::OBMol.new
      obconversion.set_in_and_out_formats input_format, output_format
      obconversion.read_string obmol, identifier
      case output_format
      when /smi|can|inchi/
        obconversion.write_string(obmol).gsub(/\s/,'').chomp
      else
        obconversion.write_string(obmol)
      end
    end
  end

end