Module: Indicateable

Extended by:
ActiveSupport::Concern
Included in:
Product
Defined in:
app/models/concerns/indicateable.rb

Constant Summary collapse

DEPRECATED =
[
  ['Entry date', 'entry_date'],
  ['Entry reason', 'entry_reason'],
  ['Exit reason', 'exit_reason'],
  ['Father race code', 'father_race_code'],
  ['Birth date', 'birth_date'],
  ['End of life witness', 'end_of_life_witness'],
  ['Entry reason', 'entry_reason'],
  ['Father country code', 'father_country_code'],
  ['First calving date', 'first_calving_date'],
  ['Birth farm number', 'birth_farm_number'],
  ['Country code', 'country_code'],
  ['Exit date', 'exit_date'],
  ['Father identification number', 'father_identification_number'],
  ['Mother country code', 'mother_country_code'],
  ['Mother identification number', 'mother_identification_number'],
  ['Mother race code', 'mother_race_code'],
  ['Origin country code', 'origin_country_code'],
  ['Origin identification number', 'origin_identification_number']
].freeze

Instance Method Summary collapse

Instance Method Details

#add_and_read(operand, options = {}) ⇒ Object


196
197
198
# File 'app/models/concerns/indicateable.rb', line 196

def add_and_read(operand, options = {})
  compute_and_read(operand, options.merge(operation: :add))
end

#add_to_readings(indicator, value, options = {}) ⇒ Object

Substract a value to a list of indicator data


238
239
240
# File 'app/models/concerns/indicateable.rb', line 238

def add_to_readings(indicator, value, options = {})
  operate_on_readings(indicator, value, options.merge(operation: :add))
end

#compute_and_read(operand, options = {}) ⇒ Object

Substract a value to a list of indicator data


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
# File 'app/models/concerns/indicateable.rb', line 201

def compute_and_read(operand, options = {})
  read_at = options[:at] || Time.zone.now
  taken_at = options[:taken_at] || read_at - 0.000001
  operation = options[:operation] || :add
  whole_indicators_list.each do |indicator_name|
    operand_value = operand.send(indicator_name)
    unless operand_value
      raise StandardError, "No given #{indicator_name} value"
    end
    indicator = Nomen::Indicator.find(indicator_name)
    # Perform operation
    value = get(indicator, at: taken_at)
    value = Charta.new_geometry(value) if indicator.datatype == :shape
    if operation == :add
      value += operand_value
    elsif operation == :substract
      value -= operand_value
    else
      raise StandardError, "Unknown operation: #{operation.inspect}"
    end
    # Read new value
    reading = readings.find_or_initialize_by(
      indicator_name: indicator_name,
      read_at: read_at,
      originator: options[:originator]
    )
    reading.value = value
    reading.save!
  end
end

#copy_readings_of!(other, options = {}) ⇒ Object

Copy individual indicators of the other at given times


182
183
184
185
186
187
188
189
190
# File 'app/models/concerns/indicateable.rb', line 182

def copy_readings_of!(other, options = {})
  options[:at] ||= Time.zone.now
  options[:taken_at] ||= options[:at] - 0.000001
  (other.individual_indicators_list - frozen_indicators_list).each do |indicator_name|
    if reading = other.reading(indicator_name, at: options[:taken_at])
      read!(indicator_name, reading.value, at: options[:at], originator: options[:originator])
    end
  end
end

#density(numerator, denominator, options = {}) ⇒ Object


149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'app/models/concerns/indicateable.rb', line 149

def density(numerator, denominator, options = {})
  # Check indicator
  unless numerator.is_a?(Nomen::Item) || numerator = Nomen::Indicator[numerator]
    raise ArgumentError, "Unknown indicator #{numerator.inspect}. Expecting one of them: #{Nomen::Indicator.all.sort.to_sentence}."
  end
  unless denominator.is_a?(Nomen::Item) || denominator = Nomen::Indicator[denominator]
    raise ArgumentError, "Unknown indicator #{denominator.inspect}. Expecting one of them: #{Nomen::Indicator.all.sort.to_sentence}."
  end

  # Find dimension and unit
  numerator_dimension   = Nomen::Dimension.find_by(symbol: numerator.symbol)
  denominator_dimension = Nomen::Dimension.find_by(symbol: denominator.symbol)
  unless dimension = Nomen::Dimension.find_by(symbol: "#{numerator_dimension.symbol}/#{denominator_dimension.symbol}")
    raise "No dimension found for: #{numerator.symbol}/#{denominator.symbol}"
  end
  unless unit = Nomen::Unit.find_by(dimension: dimension)
    raise "No unit found for: #{dimension.inspect}"
  end

  # Compute calculation
  (get(numerator, options).to_d(numerator_dimension.symbol) /
   get(denominator, options).to_d(denominator_dimension.symbol)).in(unit)
end

#first_reading(indicator_name) ⇒ Object


71
72
73
74
75
# File 'app/models/concerns/indicateable.rb', line 71

def first_reading(indicator_name)
  candidates = readings.where(indicator_name: indicator_name).order(:read_at)
  return candidates.first if candidates.any?
  nil
end

#get(indicator, *args) ⇒ Object

Get indicator value if option :at specify at which moment if option :interpolate is true, it returns the interpolated value


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
# File 'app/models/concerns/indicateable.rb', line 80

def get(indicator, *args)
  unless indicator.is_a?(Nomen::Item) || indicator = Nomen::Indicator[indicator]
    raise ArgumentError, "Unknown indicator #{indicator.inspect}. Expecting one of them: #{Nomen::Indicator.all.sort.to_sentence}."
  end
  options = args.extract_options!
  cast_or_time = args.shift || options[:cast] || options[:at] || Time.zone.now
  value = nil
  if cast_or_time.is_a?(Time) || cast_or_time.is_a?(DateTime)
    # Find value
    if options[:interpolate]
      if %i[measure decimal integer].include?(indicator.datatype)
        raise NotImplementedError, 'Interpolation is not available for now'
      end
      raise StandardError, "Can not use :interpolate option with #{indicator.datatype.inspect} datatype"
    elsif reading = self.reading(indicator.name, at: cast_or_time)
      value = reading.value
    elsif !options[:default].is_a?(FalseClass)
      value = case indicator.datatype
              when :measure then 0.0.in(indicator.unit)
              when :decimal then 0.0
              when :integer then 0
      end
    end
    # Adjust value
    if value && indicator.gathering && !options[:gathering].is_a?(FalseClass)
      if indicator.gathering == :proportional_to_population
        value *= send(:population, at: cast_or_time)
      end
    end
  elsif cast_or_time.is_a?(InterventionProductParameter)
    indicator_name = indicator.name
    if cast_or_time.product && cast_or_time.product.whole_indicators_list.include?(indicator_name.to_sym)
      value = cast_or_time.send(indicator_name)
    elsif cast_or_time.parameter.new?
      unless variant = cast_or_time.variant || cast_or_time.parameter.variant(cast_or_time.intervention)
        raise StandardError, "Need variant to know how to read it (#{cast_or_time.intervention.procedure_name}##{cast_or_time.reference_name})"
      end
      if variant.frozen_indicators.include?(indicator)
        value = variant.get(indicator)
      else
        raise StandardError, "Cannot find a frozen indicator #{indicator.name} for variant"
      end
    elsif reading = self.reading(indicator_name, at: cast_or_time.intervention.started_at)
      value = reading.value
    else
      raise 'What ?'
    end
    # Adjust value
    if value && indicator.gathering && !options[:gathering].is_a?(FalseClass)
      if indicator.gathering == :proportional_to_population
        value *= cast_or_time.population
      end
    end
  else
    raise "Cannot support #{cast_or_time.inspect} parameter"
  end
  value
end

#get!(indicator, *args) ⇒ Object


139
140
141
142
143
144
145
146
147
# File 'app/models/concerns/indicateable.rb', line 139

def get!(indicator, *args)
  unless indicator.is_a?(Nomen::Item) || indicator = Nomen::Indicator[indicator]
    raise ArgumentError, "Unknown indicator #{indicator.inspect}. Expecting one of them: #{Nomen::Indicator.all.sort.to_sentence}."
  end
  unless value = get(indicator, *args)
    raise "Cannot get value of #{indicator.name} for product ##{id}"
  end
  value
end

#mark!(indicator, options = {}) ⇒ Object

Register a value at the current value


36
37
38
39
# File 'app/models/concerns/indicateable.rb', line 36

def mark!(indicator, options = {})
  marked_at = options[:marked_at] ||= Time.zone.now
  read!(indicator, get!(indicator, at: marked_at), at: marked_at)
end

#operate_on_readings(indicator, value, options = {}) ⇒ Object


242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'app/models/concerns/indicateable.rb', line 242

def operate_on_readings(indicator, value, options = {})
  unless indicator.is_a?(Nomen::Item) || indicator = Nomen::Indicator[indicator]
    raise ArgumentError, "Unknown indicator #{indicator.inspect}. Expecting one of them: #{Nomen::Indicator.all.sort.to_sentence}."
  end
  data = readings.where(indicator_name: indicator.name)
  operation = options.delete(:operation)
  data = data.where('read_at <= ?', options[:before]) if options[:before]
  data = data.where('read_at >= ?', options[:after]) if options[:after]
  if operation == :add
    expr = (indicator.datatype == :shape ? 'ST_Union(VALUE, ?)' : 'VALUE + ?')
  elsif operation == :substract
    expr = (indicator.datatype == :shape ? 'ST_Difference(VALUE, ?)' : 'VALUE - ?')
  else
    raise StandardError, "Unknown operation: #{operation.inspect}"
  end
  data.update_all(["VALUE = #{expr}".gsub('VALUE', "#{indicator.datatype}_value"), value])
end

#read!(indicator, value, options = {}) ⇒ Object

Measure a product for a given indicator

Raises:

  • (ArgumentError)

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/models/concerns/indicateable.rb', line 42

def read!(indicator, value, options = {})
  unless indicator.present? && (indicator.is_a?(Nomen::Item) || (indicator = Nomen::Indicator.find(indicator)))
    raise ArgumentError, "Unknown indicator #{indicator.inspect}. Expecting one of them: #{Nomen::Indicator.all.sort.to_sentence}."
  end
  raise ArgumentError, 'Value must be given' if value.nil?
  unless options[:force]
    if frozen_indicators.include?(indicator)
      raise ArgumentError, "A frozen indicator (#{indicator.name}) cannot be read"
    end
  end
  options[:at] = Time.new(1, 1, 1, 0, 0, 0, '+00:00') if options[:at] == :origin
  options[:at] = Time.zone.now unless options.key?(:at)
  unless reading = readings.find_by(indicator_name: indicator.name, read_at: options[:at])
    reading = readings.build(indicator_name: indicator.name, read_at: options[:at], originator: options[:originator])
  end
  reading.value = value
  reading.save!
  reading
end

#read_whole_indicators_from!(source, options = {}) ⇒ Object

Read only whole indicators and store it with given options


174
175
176
177
178
179
# File 'app/models/concerns/indicateable.rb', line 174

def read_whole_indicators_from!(source, options = {})
  whole_indicators_list.each do |indicator|
    value = source.send(indicator)
    read!(indicator, value, options) if value
  end
end

#reading(indicator, options = {}) ⇒ Object

Return the indicator reading


63
64
65
66
67
68
69
# File 'app/models/concerns/indicateable.rb', line 63

def reading(indicator, options = {})
  unless indicator.is_a?(Nomen::Item) || indicator = Nomen::Indicator[indicator]
    raise ArgumentError, "Unknown indicator #{indicator.inspect}. Expecting one of them: #{Nomen::Indicator.all.sort.to_sentence}."
  end
  read_at = options[:at] || Time.zone.now
  readings.where(indicator_name: indicator.name).where('read_at <= ?', read_at).order(read_at: :desc).first
end

#substract_and_read(operand, options = {}) ⇒ Object


192
193
194
# File 'app/models/concerns/indicateable.rb', line 192

def substract_and_read(operand, options = {})
  compute_and_read(operand, options.merge(operation: :substract))
end

#substract_to_readings(indicator, value, options = {}) ⇒ Object

Substract a value to a list of indicator data


233
234
235
# File 'app/models/concerns/indicateable.rb', line 233

def substract_to_readings(indicator, value, options = {})
  operate_on_readings(indicator, value, options.merge(operation: :substract))
end