Module: OpenTox::Algorithm

Includes:
OpenTox
Included in:
Dataset, FeatureSelection, Fminer, Generic, Lazar, Substructure, Model::Lazar
Defined in:
lib/algorithm.rb,
lib/utils.rb

Overview

Wrapper for OpenTox Algorithms

Defined Under Namespace

Modules: Dataset, FeatureSelection, Neighbors, Similarity, Substructure Classes: BBRC, Fminer, Generic, LAST, Lazar, StructuralClustering

Instance Attribute Summary

Attributes included from OpenTox

#metadata, #uri

Class Method Summary collapse

Instance Method Summary collapse

Methods included from OpenTox

#add_metadata, all, #delete, #initialize, #load_metadata, sign_in, text_to_html

Class Method Details

.effect(occurrences, db_instances) ⇒ Object

Effect calculation for classification

Parameters:

  • Array (Array)

    of occurrences per class in the form of Enumerables.

  • Array (Array)

    of database instance counts per class.



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/utils.rb', line 214

def self.effect(occurrences, db_instances)
  max=0
  max_value=0
  nr_o = self.sum_size(occurrences)
  nr_db = db_instances.to_scale.sum

  occurrences.each_with_index { |o,i| # fminer outputs occurrences sorted reverse by activity.
    actual = o.size.to_f/nr_o
    expected = db_instances[i].to_f/nr_db
    if actual > expected
      if ((actual - expected) / actual) > max_value
       max_value = (actual - expected) / actual # 'Schleppzeiger'
        max = i
      end
    end
  }
  max
end

.gauss(x, sigma = 0.3) ⇒ Float

Gauss kernel

Returns:

  • (Float)


158
159
160
161
# File 'lib/utils.rb', line 158

def self.gauss(x, sigma = 0.3) 
  d = 1.0 - x.to_f
  Math.exp(-(d*d)/(2*sigma*sigma))
end

.get_pc_descriptors(params) ⇒ Object

Calculates PC descriptors via Ambit – DO NOT OVERLOAD Ambit. @param Required keys: :compounds, :pc_type @return Ambit result uri, piecewise (1st: base, 2nd: SMILES, 3rd+: features



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
# File 'lib/utils.rb', line 33

def self.get_pc_descriptors(params)

  begin

    ambit_ds_service_uri = "http://apps.ideaconsult.net:8080/ambit2/dataset/"
    ambit_mopac_model_uri = "http://apps.ideaconsult.net:8080/ambit2/model/69632"
    descs = YAML::load_file( File.join(ENV['HOME'], ".opentox", "config", "ambit_descriptors.yaml") )
    descs_uris = []
    params[:pc_type] = "electronic,cpsa" if params[:pc_type].nil? # rescue missing pc_type
    types = params[:pc_type].split(",")
    descs.each { |uri, cat_name| 
      if types.include? cat_name[:category]
        descs_uris << uri
      end
    }
    if descs_uris.size == 0
      raise "Error! Empty set of descriptors. Did you supply one of [geometrical, topological, electronic, constitutional, hybrid, cpsa] ?"
    end
    #LOGGER.debug "Ambit descriptor URIs: #{descs_uris.join(", ")}"

    begin
      # Create SMI
      smiles_array = []; smiles_to_inchi = {}
      params[:compounds].each do |n|
        cmpd = OpenTox::Compound.new(n)
        smiles_string = cmpd.to_smiles
        smiles_to_inchi[smiles_string] = URI.encode_www_form_component(cmpd.to_inchi)
        smiles_array << smiles_string
      end
      smi_file = Tempfile.open(['pc_ambit', '.csv'])
      pc_descriptors = nil

      # Create Ambit dataset
      smi_file.puts( "SMILES\n" )
      smi_file.puts( smiles_array.join("\n") )
      smi_file.flush
      ambit_ds_uri = OpenTox::RestClientWrapper.post(ambit_ds_service_uri, {:file => File.new(smi_file.path)}, {:content_type => "multipart/form-data", :accept => "text/uri-list"} )
    rescue Exception => e
      LOGGER.debug "#{e.class}: #{e.message}"
      LOGGER.debug "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
    ensure
      smi_file.close! if smi_file
    end
    ambit_smiles_uri = OpenTox::RestClientWrapper.get(ambit_ds_uri + "/features", {:accept=> "text/uri-list"} ).chomp

    # Calculate 3D for CPSA
    if types.include? "cpsa"
      ambit_ds_mopac_uri = OpenTox::RestClientWrapper.post(ambit_mopac_model_uri, {:dataset_uri => ambit_ds_uri}, {:accept => "text/uri-list"} ) 
      LOGGER.debug "MOPAC dataset: #{ambit_ds_mopac_uri }"
    end

    # Get Ambit results
    ambit_result_uri = [] # 1st pos: base uri, then features
    ambit_result_uri << ambit_ds_uri + "?"
    ambit_result_uri << ("feature_uris[]=" + URI.encode_www_form_component(ambit_smiles_uri) + "&")
    descs_uris.each_with_index do |uri, i|
      algorithm = Algorithm::Generic.new(uri)
      result_uri = algorithm.run({:dataset_uri => ambit_ds_uri})
      ambit_result_uri << result_uri.split("?")[1] + "&"
      LOGGER.debug "Ambit (#{descs_uris.size}): #{i+1}"
    end
    #LOGGER.debug "Ambit result: #{ambit_result_uri.join('')}"
    [ ambit_result_uri, smiles_to_inchi ]

  rescue Exception => e
    LOGGER.debug "#{e.class}: #{e.message}"
    LOGGER.debug "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
  end
end

.isnull_or_singular?(array) ⇒ Boolean

For symbolic features

Parameters:

  • Array (Array)

    to test, must indicate non-occurrence with 0.

Returns:

  • (Boolean)

    Whether the feature is singular or non-occurring or present everywhere.



167
168
169
170
171
172
# File 'lib/utils.rb', line 167

def self.isnull_or_singular?(array)
  nr_zeroes = array.count(0)
  return (nr_zeroes == array.size) ||    # remove non-occurring feature
         (nr_zeroes == array.size-1) ||  # remove singular feature
         (nr_zeroes == 0)                # also remove feature present everywhere
end

.load_ds_csv(ambit_result_uri, smiles_to_inchi, subjectid = nil) ⇒ Object

Load dataset via CSV @param Ambit result uri, piecewise (1st: base, 2nd: SMILES, 3rd+: features @return dataset uri



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
# File 'lib/utils.rb', line 107

def self.load_ds_csv(ambit_result_uri, smiles_to_inchi, subjectid=nil)
  
  master=nil
  (1...ambit_result_uri.size).collect { |idx|
    curr_uri = ambit_result_uri[0] + ambit_result_uri[idx]
    LOGGER.debug "Requesting #{curr_uri}"
    csv_data = CSV.parse( OpenTox::RestClientWrapper.get(curr_uri, {:accept => "text/csv", :subjectid => subjectid}) )
    if csv_data[0] && csv_data[0].size>1
      if master.nil? # This is the smiles entry
        (1...csv_data.size).each{ |idx| csv_data[idx][1] = smiles_to_inchi[csv_data[idx][1]] }
        master = csv_data
        next
      else
        index_uri = csv_data[0].index("SMILES")
        csv_data.map {|i| i.delete_at(index_uri)} if index_uri #Removes additional SMILES information
        
        nr_cols = (csv_data[0].size)-1
        LOGGER.debug "Merging #{nr_cols} new columns"
        master.each {|row| nr_cols.times { row.push(nil) }  } # Adds empty columns to all rows
        csv_data.each do |row|
          temp = master.assoc(row[0]) # Finds the appropriate line in master
          ((-1*nr_cols)..-1).collect.each { |idx|
            temp[idx] = row[nr_cols+idx+1] if temp # Updates columns if line is found
          }
        end
      end
    end
  }

  index_uri = master[0].index("Compound")
  master.map {|i| i.delete_at(index_uri)}
  master[0].each {|cell| cell.chomp!(" ")}
  master[0][0] = "Compound" #"SMILES" 
  index_smi = master[0].index("SMILES")
  master.map {|i| i.delete_at(index_smi)} if index_smi
  #master[0][0] = "SMILES" 
   
  #LOGGER.debug "-------- AM: Writing to dumpfile"
  #File.open("/tmp/test.csv", 'w') {|f| f.write( master.collect {|r| r.join(",")}.join("\n") ) }
 
  parser = OpenTox::Parser::Spreadsheets.new
  ds = OpenTox::Dataset.new(nil,subjectid)
  ds.save(subjectid)
  parser.dataset = ds
  ds = parser.load_csv(master.collect{|r| r.join(",")}.join("\n"))
  ds.save(subjectid)
end

.min_frequency(training_dataset, per_mil) ⇒ Object

Minimum Frequency return [Integer] min-frequency

Parameters:

  • per-mil (Integer)

    value



204
205
206
207
208
# File 'lib/utils.rb', line 204

def self.min_frequency(training_dataset,per_mil)
  minfreq = per_mil * training_dataset.compounds.size.to_f / 1000.0 # AM sugg. 8-10 per mil for BBRC, 50 per mil for LAST
  minfreq = 2 unless minfreq > 2
  Integer (minfreq)
end

.numeric?(value) ⇒ Boolean

Numeric value test @param value

Returns:

  • (Boolean)

    Whether value is a number



178
179
180
# File 'lib/utils.rb', line 178

def self.numeric?(value)
  true if Float(value) rescue false
end

.pc_descriptors(params) ⇒ Object

Calculate physico-chemical descriptors. @param Required keys: :dataset_uri, :pc_type @return dataset uri



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/utils.rb', line 14

def self.pc_descriptors(params)

  begin
    ds = OpenTox::Dataset.find(params[:dataset_uri])
    compounds = ds.compounds.collect
    ambit_result_uri, smiles_to_inchi = get_pc_descriptors( { :compounds => compounds, :pc_type => params[:pc_type] } )
    #ambit_result_uri = ["http://apps.ideaconsult.net:8080/ambit2/dataset/987103?" ,"feature_uris[]=http%3A%2F%2Fapps.ideaconsult.net%3A8080%2Fambit2%2Ffeature%2F4276789&", "feature_uris[]=http%3A%2F%2Fapps.ideaconsult.net%3A8080%2Fambit2%2Fmodel%2F16%2Fpredicted"] # for testing
    LOGGER.debug "Ambit result uri for #{params.inspect}: '#{ambit_result_uri.to_yaml}'"
    load_ds_csv(ambit_result_uri, smiles_to_inchi)
  rescue Exception => e
    LOGGER.debug "#{e.class}: #{e.message}"
    LOGGER.debug "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
  end

end

.sum_size(array) ⇒ Integer

Sum of an array for Arrays.

Parameters:

  • Array (Array)

    with values

Returns:

  • (Integer)

    Sum of size of values



194
195
196
197
198
# File 'lib/utils.rb', line 194

def self.sum_size(array)
  sum=0
  array.each { |e| sum += e.size }
  return sum
end

.zero_variance?(array) ⇒ Boolean

For symbolic features

Parameters:

  • Array (Array)

    to test, must indicate non-occurrence with 0.

Returns:

  • (Boolean)

    Whether the feature has variance zero.



186
187
188
# File 'lib/utils.rb', line 186

def self.zero_variance?(array)
  return array.uniq.size == 1
end

Instance Method Details

#run(params = nil, waiting_task = nil) ⇒ String

Execute algorithm with parameters, consult OpenTox API and webservice documentation for acceptable parameters

Parameters:

  • params (optional, Hash) (defaults to: nil)

    Algorithm parameters

  • waiting_task (optional, OpenTox::Task) (defaults to: nil)

    (can be a OpenTox::Subtask as well), progress is updated accordingly

Returns:

  • (String)

    URI of new resource (dataset, model, …)



22
23
24
25
# File 'lib/algorithm.rb', line 22

def run(params=nil, waiting_task=nil)
  LOGGER.info "Running algorithm '"+@uri.to_s+"' with params: "+params.inspect
  RestClientWrapper.post(@uri, params, {:accept => 'text/uri-list'}, waiting_task).to_s
end

#to_rdfxmlapplication/rdf+xml

Get OWL-DL representation in RDF/XML format

Returns:

  • (application/rdf+xml)

    RDF/XML representation



29
30
31
32
33
# File 'lib/algorithm.rb', line 29

def to_rdfxml
  s = Serializer::Owl.new
  s.add_algorithm(@uri,@metadata)
  s.to_rdfxml
end