Class: RasterVariable

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/raster_variable.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.long_description(raster_variables) ⇒ Object



428
429
430
431
432
# File 'app/models/raster_variable.rb', line 428

def self.long_description(raster_variables)
  str = []
  raster_variables.each{ |rv| str << rv.long_description }
  str.join("\n")
end

Instance Method Details

#_raster_dataset_id_Object



61
62
63
# File 'app/models/raster_variable.rb', line 61

def _raster_dataset_id_
  raster_datasets.count > 0 ? raster_datasets.first.id : nil
end

#_raster_dataset_idsObject



66
67
68
# File 'app/models/raster_variable.rb', line 66

def _raster_dataset_ids
  raster_dataset_ids
end

#api_attributesObject



26
27
28
# File 'app/models/raster_variable.rb', line 26

def api_attributes
  "TODO"
end

#availability_by_countryObject



31
32
33
34
35
36
37
38
# File 'app/models/raster_variable.rb', line 31

def availability_by_country
  _availability_by_country = {}
  TerrapopSample.select('DISTINCT countries.full_name', :year).joins(:country).where.not(year: nil).order('countries.full_name', :year).each do |terrapop_sample|
    _availability_by_country[terrapop_sample.full_name] ||= []
    _availability_by_country[terrapop_sample.full_name] << terrapop_sample.year
  end
  _availability_by_country
end

#build_raster_value_from_row(r) ⇒ Object

, geog_instance)



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'app/models/raster_variable.rb', line 81

def build_raster_value_from_row(r) #, geog_instance)
  raise "Cannot build raster values without geog_instance, but it is nil." if r.geog_instance.nil?
  #result = RasterValue.new(r['sample_geog_level_id'],
  #  r['raster_variable_id'], r['raster_operation_name'],
  #  r['geog_instance_id'], r['geog_instance_label'], r['geog_instance_code'],
  #  r['raster_mnemonic'], r['raster_area'],
  #  r['summary_value'], geog_instance)
  #trsc.sample_geog_level_id   = r['sample_geog_level_id'].to_i
  #trsc.raster_variable_id     = r['raster_variable_id'].to_i
  #trsc.raster_operation_name  = r['raster_operation_name']
  #trsc.geog_instance_id       = r['geog_instance_id'].to_i
  #trsc.geog_instance_label    = r['geog_instance_label']
  #trsc.geog_instance_code     = r['geog_instance_code'].to_f
  #trsc.raster_mnemonic        = r['raster_mnemonic']
  #trsc.boundary_area          = r['boundary_area'].to_f
  #trsc.raster_area            = r['raster_area'].to_f
  #trsc.summary_value          = r['summary_value'].to_f
  #trsc.has_area_reference     = has_area_reference
  result = RasterValue.new(r)
end

#build_raster_values(level, raster_operation, raster_dataset) ⇒ Object



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
# File 'app/models/raster_variable.rb', line 113

def build_raster_values(level, raster_operation, raster_dataset)
  # We'll also want to get the geog_instances for the results, so get those first,
  # and put them in a hash so we can quickly find them later.
  result_geog_instances = level.geog_instances
  operation = raster_operation.opcode
  
  raise "The level #{level.to_s} must have at least one geog_instance." if result_geog_instances.empty?

  geog_instance_lookup = Hash.new
  result_geog_instances.each{ |e| geog_instance_lookup[e.id] = e }

  unless raster_datasets.include? raster_dataset
    $stderr.puts "**** Ignoring out-of-universe RasterDataset[#{raster_dataset.inspect}] for RasterVariable[#{mnemonic}] ****"
    return []
  end

  # call select * from terrapop_raster_summary(level.id, this.id, operation);
  # or select (terrapop_raster_summary(level.id, this.id, operation)).*
  # where level is the sample_geog_level.id, this.id is the raster_variable_id of this raster, and operation is one of
  # min, max, mean, sum, count, or mode.
  # Should return collection of results that look something like this:
  #
  # sample_geog_level_id | raster_variable_id | raster_operation_name | geog_instance_label | geog_instance_code | raster_mnemonic  |  boundary_area   | summary_value
  # ---------------------+--------------------+-----------------------+---------------------+--------------------+------------------+------------------+---------------
  #                    2 |                333 | max                   | Rondônia            |                 11 | coffee_yield_max | 237581357173.494 |        0.8789
  #                    2 |                333 | max                   | Acre                |                 12 | coffee_yield_max | 152576633081.708 |        0.9766
  #                    2 |                333 | max                   | Amazonas            |                 13 | coffee_yield_max | 1577624256765.11 |        1.1621

  #sample_geog_lvl_id bigint, raster_var_id bigint, raster_op_name varchar(32)

  band = raster_dataset.raster_band_index.to_i
  band = 1 if band <= 0

  terrapop_raster_summary_caches = TerrapopRasterSummaryCache.where({:sample_geog_level_id => level.id, :raster_variable_id => id, :raster_operation_name => operation, band_index: band})

  has_area_reference = !area_reference.nil?

  if terrapop_raster_summary_caches.count == 0

    stored_proc_call =
      case raster_data_type.code
      when 'binary'
        # RETURNS TABLE(geog_instance_id bigint, geog_instance_label character varying, pixel_count bigint, binary_area double precision, percent_area double precision, total_area double precision)
        "SELECT * FROM terrapop_reclassify_categorical_raster_to_binary_summariz_v4(#{level.id}, #{id}, #{band})"

      when 'categorical'
        # RETURNS TABLE(geog_instance_id bigint, geog_instance_label character varying, num_class bigint, mod_class double precision, total_area double precision)
        "SELECT * FROM terrapop_categorical_raster_v1( #{level.id}, #{id}, #{band} )"

      when 'contin'
        raise "AreaReference nil: '#{mnemonic}' - should not be nil" if area_reference.nil?

        # RETURNS TABLE (geog_instance_id bigint, geog_instance_label character varying, min double precision, max double precision, mean double precision, count bigint, stddev double precision, total_area double precision)

        "SELECT * FROM terrapop_continuous_summarization0(#{level.id}, #{id})"

      when 'cont_ext_arearef'

        # RETURNS TABLE (geog_instance_id bigint, geog_instance_label character varying, count bigint, total_area double precision, mean double precision, stddev double precision, min double precision, max double precision)

        "SELECT * FROM terrapop_continuous_summarization_without_arearef(#{level.id}, #{id}, #{band})"

      else
        raise "Raster without area_reference has been detected: RasterVariable[#{id}]" unless has_area_reference

        if mnemonic.match(/YLD$/)
          # RETURNS TABLE (geog_instance_id bigint, geog_instance_label character varying, min double precision, max double precision, mean double precision, count bigint)
          "SELECT * FROM terrapop_gli_yield_areal_summarization_v2(#{level.id}, #{id})"
        elsif mnemonic.match(/HAR$/)
          # RETURNS TABLE (geog_instance_id bigint, geog_instance_label character varying, percent_area double precision, harvest_area double precision)
          "SELECT * FROM terrapop_gli_harvest_areal_summarization_v2(#{level.id}, #{id})"
        else
          # RETURNS TABLE(geog_instance_id bigint, geog_instance_label character varying, binary_area double precision, total_area double precision, percent_area double precision)
          "SELECT * FROM terrapop_glc_binary_summarization_v7(#{level.id}, #{id})"
        end
      end

    $stderr.puts "===[RASTERVARIABLE INFO]       ===> #{mnemonic} | #{level.internal_code} [#{level.id}] | operation: #{operation} | band: #{band}"
    $stderr.puts "===[RASTER SUMMARIZATION QUERY]===> #{stored_proc_call}"

    result = ActiveRecord::Base.connection.execute(stored_proc_call)

    all_columns = ['min', 'max', 'mean', 'count', 'num_class', 'mod_class', 'binary_area', 'percent_area', 'total_area', 'harvest_area']

    if result.count > 0
      terrapop_raster_summary_caches = []

      seen = false

      result.each do |r|

        geog_instance_id =
          if r.has_key? 'geog_instance_id'
            r['geog_instance_id']
          elsif r.has_key? 'geog_instance'
            r['geog_instance']
          else
            -1
          end

        column_overlap = all_columns & r.keys
        columns_n_operations = {}

        # this is some fanciness of taking an array of hashes and squashing it down to just a hash; originally, each array element is just a single key/value pair
        column_overlap = column_overlap.map{|field| {field => get_operation(field)}}.reduce Hash.new, :merge

        unless seen
          $stderr.puts "==[COLUMNs, OPs, BAND] => [#{column_overlap.inspect}, '#{band}']=="
          seen = true
        end

        column_overlap.each do |column, op|

          unless op.nil?

            cnt = TerrapopRasterSummaryCache.where(raster_dataset_id: raster_dataset.id, geog_instance_id: geog_instance_id.to_i, sample_geog_level_id: level.id, raster_variable_id: id, raster_operation_name: op, band_index: band).count

            if cnt == 0

              trsc = TerrapopRasterSummaryCache.new

              val = get_value(r, op).to_f
              
              if op.match(/percent/)
                val *= 100
              end

              trsc.sample_geog_level_id   = (r.has_key?('sample_geog_level_id')  ? r['sample_geog_level_id'].to_i : level.id)
              trsc.raster_variable_id     = id
              trsc.raster_operation_name  = (r.has_key?('raster_operation_name') ? r['raster_operation_name']     : op)
              trsc.geog_instance_id       = geog_instance_id
              trsc.geog_instance_label    = r['geog_instance_label']
              trsc.geog_instance_code     = (r.has_key?('geog_instance_code')    ? r['geog_instance_code'].to_f   : -1.0)
              trsc.raster_mnemonic        = RequestRasterVariable.mnemonic(self, raster_operation, raster_dataset, level) #mnemonic + "_" + op + "_" + band.to_s
              trsc.boundary_area          = (r.has_key?('boundary_area')         ? r['boundary_area'].to_f        : -1.0)
              trsc.raster_area            = (r.has_key?('raster_area')           ? r['raster_area'].to_f          : (r.has_key?('total_area') ? r['total_area'].to_f : -1.0))
              trsc.summary_value          = val
              trsc.has_area_reference     = has_area_reference
              trsc.band_index             = band
              trsc.raster_dataset_id      = raster_dataset.id

              trsc.save

            end
          else
            $stderr.puts "**** get_operation('#{column}'), raster_data_type.code[#{raster_data_type.code}] passed thru without operation and returned nil; result had the fields: #{r.keys.join(", ")} ****"
          end
        end

      end

      ### UNCOMMENT WHEN RE-ENABLING CACHING
      terrapop_raster_summary_caches = TerrapopRasterSummaryCache.where(raster_dataset_id: raster_dataset.id, sample_geog_level_id: level.id, raster_variable_id: id, raster_operation_name: operation, band_index: band)
    end
  end

  output = terrapop_raster_summary_caches.map do |r|
    # build_raster_value_from_row(r, geog_instance_lookup[r.geog_instance_id.to_i])
    # build_raster_value_from_row(r)
    RasterValue.new(r)
  end
  output
end

#child_countObject



46
47
48
# File 'app/models/raster_variable.rb', line 46

def child_count
  1
end

#get_base_categorical_stats(sample_geog_level) ⇒ Object



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'app/models/raster_variable.rb', line 373

def get_base_categorical_stats(sample_geog_level)
  sql = "select label, terrapop_sample_id, code, ST_ValueCount(rast) as category_count from (
      select label, code, terrapop_sample_id, st_union(rast) as rast from (
        SELECT sgl.terrapop_sample_id as terrapop_sample_id, gi.label as label, gi.code as code, ST_Clip(them_rasters.rast, bound.geog::geometry) as rast
        FROM sample_geog_levels sgl
        inner join geog_instances gi on sgl.id = gi.sample_geog_level_id
        inner join boundaries bound on bound.geog_instance_id = gi.id
        inner join rasters AS them_rasters on ST_Intersects(them_rasters.rast, bound.geog::geometry)
        where sgl.id = #{sample_geog_level.id} AND them_rasters.raster_variable_id = #{id}
      ) base
      group by label, code, terrapop_sample_id
    ) unioned
    order by code"
  ActiveRecord::Base.connection.execute(sql)
end

#get_categorical_statistics(sample_geog_level) ⇒ Object



390
391
392
393
394
# File 'app/models/raster_variable.rb', line 390

def get_categorical_statistics(sample_geog_level)
  get_base_categorical_stats(sample_geog_level).map{ |result|
    result['category_count'].scan(/\(([0-9]+),([0-9]+)\)/).collect{ |category, count| {category => count} }
  }.flatten.inject(:merge)
end

#get_operation(column_name) ⇒ Object



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
# File 'app/models/raster_variable.rb', line 278

def get_operation(column_name)
  case column_name
  when 'mod_class'
    'mode'
  when 'num_class'
    'num_classes'
  when 'min'
    'min'
  when 'max'
    'max'
  when 'mean'
    'mean'
  when 'count'
    'count'
  when 'binary_area'
    'binary_area'
  when 'total_area'
    if raster_data_type.code == 'cont_ext_arearef'
      'total_area_ref'
    elsif raster_data_type.code == 'binary'
      'total_area_bin'
    elsif raster_data_type.code == 'cont_ext_areaprop' or raster_data_type.code == 'contin'
      'total_area_areal'
    end
  when 'harvest_area'
    'total_area_areal'
  when 'percent_area'
    if raster_data_type.code == 'binary'
      'percent_area_bin'
    elsif raster_data_type.code == 'cont_ext_areaprop'
      'percent_area_areal'
    end
  else
    raise "ERR: unable to find operation for '#{column_name}'"
  end
end

#get_statistics(sample_geog_level) ⇒ Object



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'app/models/raster_variable.rb', line 397

def get_statistics(sample_geog_level)
  sample_precision = TerrapopConfiguration["application"]["environments"][Rails.env]["raster_sample_precision"]
  sql = "SELECT label, terrapop_sample_id, code, (statistics).* FROM (
          select label, terrapop_sample_id, code, _ST_SummaryStats(rast, 1, true, #{sample_precision}) as statistics from (
            select label, code, terrapop_sample_id, st_union(rast) as rast from (
              SELECT sgl.terrapop_sample_id as terrapop_sample_id, gi.label as label, gi.code as code, ST_Clip(them_rasters.rast, bound.geog::geometry) as rast
              FROM sample_geog_levels sgl
              inner join geog_instances gi on sgl.id = gi.sample_geog_level_id
              inner join boundaries bound on bound.geog_instance_id = gi.id
              inner join rasters AS them_rasters on ST_Intersects(them_rasters.rast, bound.geog::geometry)
              where sgl.id = 1 AND them_rasters.raster_variable_id = 145
            ) base
            group by label, code, terrapop_sample_id
          ) unioned
          order by code
        ) as block"
  results = ActiveRecord::Base.connection.execute(sql)
  results.first
end

#get_value(raster_summary_row, operation) ⇒ Object



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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'app/models/raster_variable.rb', line 316

def get_value(raster_summary_row, operation)
  # min double precision, max double precision, mean double precision, count double precision,stddev double precision, total_area double precision
  case operation
  when 'mode'
    raster_summary_row['mod_class']
  when 'num_classes'
    raster_summary_row['num_class']
  when 'min'
    raster_summary_row['min']
  when 'max'
    raster_summary_row['max']
  when 'mean'
    raster_summary_row['mean']
  when 'count'
    raster_summary_row['count']
  when 'total_area_areal'
    if raster_summary_row.has_key? 'binary_area'
      raster_summary_row['binary_area']
    elsif raster_summary_row.has_key? 'total_area'
      raster_summary_row['total_area']
    elsif raster_summary_row.has_key? 'harvest_area'
      raster_summary_row['harvest_area']
    end
  when 'total_area_ref'
    raster_summary_row['total_area']
  when 'total_area'
    if raster_summary_row.has_key? 'total_area'
      raster_summary_row['total_area']
    elsif raster_summary_row.has_key? 'harvest_area'
      raster_summary_row['harvest_area']
    end
  when 'percent_area_bin'
    if raster_summary_row.has_key? 'percent_area'
      raster_summary_row['percent_area']
    end
  when 'percent_area_areal'
    if raster_summary_row.has_key? 'percent'
      raster_summary_row['percent']
    elsif raster_summary_row.has_key? 'percent_area'
      raster_summary_row['percent_area']
    end
  when 'percent_area'
    if raster_summary_row.has_key? 'percent'
      raster_summary_row['percent']
    elsif raster_summary_row.has_key? 'percent_area'
      raster_summary_row['percent_area']
    end
  when 'total_area_bin'
    raster_summary_row['binary_area']
  when 'binary_area'
    raster_summary_row['binary_area']
  else
    raise "Unknown/Unsupported raster operation - '#{operation}'"
  end
end

#in_cart_count(mnemonics) ⇒ Object



51
52
53
# File 'app/models/raster_variable.rb', line 51

def in_cart_count(mnemonics)
  0
end

#long_descriptionObject



435
436
437
# File 'app/models/raster_variable.rb', line 435

def long_description
  mnemonic + "\t" + label + "\t(" + units.to_s + ")\t" + raster_datasets.first.raster_dataset_group.label
end

#raster_dataset_mnemonicsObject



71
72
73
# File 'app/models/raster_variable.rb', line 71

def raster_dataset_mnemonics
  raster_datasets.pluck(:mnemonic)
end

#raster_datasets_countObject



56
57
58
# File 'app/models/raster_variable.rb', line 56

def raster_datasets_count
  raster_datasets.count
end

#raster_group_mnemonicObject



76
77
78
# File 'app/models/raster_variable.rb', line 76

def raster_group_mnemonic
  raster_groups.pluck(:mnemonic).first
end

#reclass_strObject



418
419
420
421
422
423
424
425
# File 'app/models/raster_variable.rb', line 418

def reclass_str
  buckets = {}
  self.raster_variable_classifications.each do |rvc|
    buckets[rvc.grouping] ||= []
    buckets[rvc.grouping] << rvc.mosaic_raster_variable
  end
  buckets
end

#setup_raster_metadata(xml) ⇒ Object



103
104
105
106
107
108
109
110
# File 'app/models/raster_variable.rb', line 103

def (xml)
  if self.
    self.. = xml
  else
    self.(original_metadata: xml)
  end
  .save
end

#table_typeObject



41
42
43
# File 'app/models/raster_variable.rb', line 41

def table_type
  self.class.to_s
end