Class: GitFit::Elevation::Train::Collector

Inherits:
Object
  • Object
show all
Defined in:
lib/git_fit/elevation/train/collector.rb

Constant Summary collapse

SPACINGS =
[2000, 1236, 764, 472, 292, 181].freeze
BUDGET =
2.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sources: nil) ⇒ Collector

Returns a new instance of Collector.



13
14
15
16
# File 'lib/git_fit/elevation/train/collector.rb', line 13

def initialize(sources: nil)
  @sources = sources
  @samples = []
end

Instance Attribute Details

#samplesObject (readonly)

Returns the value of attribute samples.



18
19
20
# File 'lib/git_fit/elevation/train/collector.rb', line 18

def samples
  @samples
end

Instance Method Details

#all_adaptersObject



45
46
47
# File 'lib/git_fit/elevation/train/collector.rb', line 45

def all_adapters
  Sync::Base.adapters
end

#count_samplesObject



20
21
22
23
24
25
26
# File 'lib/git_fit/elevation/train/collector.rb', line 20

def count_samples
  total = 0
  each_source_sample do |_sample|
    total += 1
  end
  total
end

#each_sampleObject



28
29
30
31
32
33
34
# File 'lib/git_fit/elevation/train/collector.rb', line 28

def each_sample
  each_source_sample do |sample|
    result = evaluate_sample(sample)
    @samples << result if result
    yield result
  end
end

#each_source_sample(&block) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/git_fit/elevation/train/collector.rb', line 36

def each_source_sample(&block)
  adapters = @sources ? resolve_sources(@sources) : all_adapters
  adapters.each do |adapter|
    adapter.training_samples.each(&block)
  rescue StandardError => e
    warn "Collector: #{adapter.name} failed: #{e.message}"
  end
end

#elevation_gain(alts) ⇒ Object



137
138
139
140
141
142
143
144
# File 'lib/git_fit/elevation/train/collector.rb', line 137

def elevation_gain(alts)
  total = 0.0
  (1...alts.size).each do |i|
    diff = alts[i] - alts[i - 1]
    total += diff if diff > 0
  end
  total
end

#evaluate_sample(sample) ⇒ Object



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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/git_fit/elevation/train/collector.rb', line 55

def evaluate_sample(sample)
  altitudes = sample[:altitudes]
  distances = sample[:distances]
  locations = sample[:locations]
  source = sample[:source]
  id = sample[:id]

  return nil if altitudes.size < 2
  return nil if distances.empty? || distances.last < 1000

  cache_before = DemCache.load_batch(locations)
  dem = TerrainCoeff.elevations_for(locations)
  return nil if dem.empty? || dem.compact.size < 2

  cache_hit = !cache_before.empty? && cache_before.values.all? { |v| !v.nil? }

  truth_min = dem.compact.min
  truth_max = dem.compact.max
  sm = smooth(altitudes)

  best = nil
  (2.0..3.0).step(0.1).each do |h|
    h = h.round(2)
    segs = segments(sm, h)
    chosen = nil
    SPACINGS.each do |sp|
      sel = sample_indices(sm, segs, distances, sp)
      lmin, lmax, npts = layered_estimate(dem, sel)
      err = [(lmin - truth_min).abs, (lmax - truth_max).abs].max
      if err <= BUDGET
        chosen = { h: h, spacing: sp, err: err, npts: npts }
        break
      end
    end
    unless chosen
      sel = sample_indices(sm, segs, distances, SPACINGS.last)
      lmin, lmax, npts = layered_estimate(dem, sel)
      err = [(lmin - truth_min).abs, (lmax - truth_max).abs].max
      chosen = { h: h, spacing: SPACINGS.last, err: err, npts: npts }
    end
    best = chosen if best.nil? || chosen[:npts] < best[:npts]
  end

  return nil unless best

  f = features(altitudes, distances, locations)
  {
    id: id,
    source: source,
    truth_min: truth_min,
    truth_max: truth_max,
    h_opt: best[:h],
    spacing_opt: best[:spacing],
    err: best[:err].round(2),
    npts: best[:npts],
    gain_per_km: f[:gain_per_km],
    range_per_km: f[:range_per_km],
    seg_density: f[:seg_density],
    cache_hit: cache_hit,
  }
end

#features(altitudes, distances, _locations) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/git_fit/elevation/train/collector.rb', line 117

def features(altitudes, distances, _locations)
  return nil if altitudes.empty? || distances.empty?

  dm = distances.last
  km = [dm / 1000.0, 1e-6].max
  gain = elevation_gain(altitudes)
  range = altitudes.empty? ? 0.0 : (altitudes.max - altitudes.min)
  gain_per_km = gain / km
  range_per_km = range / km
  seg_density = segments(smooth(altitudes), 2.5).size / km

  {
    gain_per_km: gain_per_km,
    range_per_km: range_per_km,
    seg_density: seg_density,
    distance_m: dm,
    npts: altitudes.size,
  }
end

#layered_estimate(dem, sel) ⇒ Object



239
240
241
242
243
# File 'lib/git_fit/elevation/train/collector.rb', line 239

def layered_estimate(dem, sel)
  vals = sel.map { |i| dem[i] }.compact
  return [nil, nil, 0] if vals.empty?
  [vals.min, vals.max, vals.size]
end

#moving_avg(vals, window) ⇒ Object



159
160
161
162
163
164
165
166
# File 'lib/git_fit/elevation/train/collector.rb', line 159

def moving_avg(vals, window)
  half = window / 2
  (0...vals.size).map do |i|
    lo = [0, i - half].max
    hi = [vals.size - 1, i + half].min
    vals[lo..hi].sum.to_f / (hi - lo + 1)
  end
end

#moving_median(vals, window) ⇒ Object



150
151
152
153
154
155
156
157
# File 'lib/git_fit/elevation/train/collector.rb', line 150

def moving_median(vals, window)
  half = window / 2
  (0...vals.size).map do |i|
    lo = [0, i - half].max
    hi = [vals.size - 1, i + half].min
    vals[lo..hi].sort[(hi - lo) / 2]
  end
end

#resolve_sources(names) ⇒ Object



49
50
51
52
53
# File 'lib/git_fit/elevation/train/collector.rb', line 49

def resolve_sources(names)
  names.map do |name|
    Sync::Base.adapters.find { |a| a.config_key == name.to_s }
  end.compact
end

#sample_indices(smooth, segs, dist, spacing) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/git_fit/elevation/train/collector.rb', line 215

def sample_indices(smooth, segs, dist, spacing)
  sel = Set.new
  segs.each do |a, b|
    sel << a
    sel << b
    next if b - a < 2

    d0 = dist[a].to_f
    d1 = dist[b].to_f
    len = d1 - d0
    seg_range = smooth[a..b].max - smooth[a..b].min
    next unless len > 500 && seg_range < 3.0

    k = 1
    while d0 + k * spacing < d1
      target = d0 + k * spacing
      idx = a + ((b - a) * (target - d0) / len).round
      sel << idx
      k += 1
    end
  end
  sel.to_a.sort
end

#segments(smooth, threshold, min_len: 20) ⇒ Object



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
# File 'lib/git_fit/elevation/train/collector.rb', line 168

def segments(smooth, threshold, min_len: 20)
  n = smooth.size
  return [[0, n - 1]] if n < 2

  segs = []
  seg_start = 0
  ext_val = smooth[0]
  ext_idx = 0
  rising = nil
  (1...n).each do |i|
    v = smooth[i]
    if rising.nil?
      if v > ext_val
        ext_val = v
        ext_idx = i
        rising = true
      elsif v < ext_val
        ext_val = v
        ext_idx = i
        rising = false
      end
    elsif rising
      if v > ext_val
        ext_val = v
        ext_idx = i
      elsif ext_val - v >= threshold
        segs << [seg_start, ext_idx] if ext_idx - seg_start >= min_len
        seg_start = ext_idx if ext_idx - seg_start >= min_len
        rising = false
        ext_val = v
        ext_idx = i
      end
    elsif v < ext_val
      ext_val = v
      ext_idx = i
    elsif v - ext_val >= threshold
      segs << [seg_start, ext_idx] if ext_idx - seg_start >= min_len
      seg_start = ext_idx if ext_idx - seg_start >= min_len
      rising = true
      ext_val = v
      ext_idx = i
    end
  end
  segs << [seg_start, n - 1] if n - 1 - seg_start >= min_len
  segs.empty? ? [[0, n - 1]] : segs
end

#smooth(vals) ⇒ Object



146
147
148
# File 'lib/git_fit/elevation/train/collector.rb', line 146

def smooth(vals)
  moving_avg(moving_median(vals, 9), 9)
end