Class: AbstractFeature

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

Direct Known Subclasses

AggregateFeature, Feature

Constant Summary collapse

FEATURE_TYPES =
%w(polygon point line)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#make_valid=(value) ⇒ Object

Sets the attribute make_valid

Parameters:

  • value

    the value to set the attribute make_valid to.



12
13
14
# File 'app/models/abstract_feature.rb', line 12

def make_valid=(value)
  @make_valid = value
end

Class Method Details

.area_in_square_meters(geom = 'geom_lowres') ⇒ Object



99
100
101
102
# File 'app/models/abstract_feature.rb', line 99

def self.area_in_square_meters(geom = 'geom_lowres')
  current_scope = all.polygons
  unscoped { SpatialFeatures::Utils.select_db_value(select("ST_Area(ST_Union(#{geom}))").from(current_scope, :features)).to_f }
end

.boundsObject



250
251
252
253
# File 'app/models/abstract_feature.rb', line 250

def self.bounds
  values = pluck('MAX(north) AS north, MAX(east) AS east, MIN(south) AS south, MIN(west) AS west').first
  [:north, :east, :south, :west].zip(values).to_h.with_indifferent_access.transform_values!(&:to_f) if values&.compact.present?
end

.cache_derivatives(options = {}) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'app/models/abstract_feature.rb', line 147

def self.cache_derivatives(options = {})
  update_all <<-SQL.squish
    geom         = ST_Transform(geog::geometry, #{detect_srid('geom')})
  SQL

  invalid('geom').update_all <<-SQL.squish
    geom         = ST_Buffer(geom, 0)
  SQL

  update_all <<-SQL.squish
    geom_lowres  = ST_SimplifyPreserveTopology(geom, #{options.fetch(:lowres_simplification, lowres_simplification)})
  SQL

  invalid('geom_lowres').update_all <<-SQL.squish
    geom_lowres  = ST_Buffer(geom_lowres, 0)
  SQL
end

.cache_keyObject



21
22
23
# File 'app/models/abstract_feature.rb', line 21

def self.cache_key
  collection_cache_key
end

.collection_cache_key(collection = all) ⇒ Object

for Rails >= 5 ActiveRecord collections we override the collection_cache_key to prevent Rails doing its default query on ‘updated_at`



27
28
29
# File 'app/models/abstract_feature.rb', line 27

def self.collection_cache_key(collection = all, *)
  "#{collection.maximum(:id)}-#{collection.count}"
end

.geojson(lowres: false, precision: 6, properties: true, srid: 4326, centroids: false, features_only: false, include_record_identifiers: false) ⇒ Object

default srid is 4326 so output is Google Maps compatible



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

def self.geojson(lowres: false, precision: 6, properties: true, srid: 4326, centroids: false, features_only: false, include_record_identifiers: false) # default srid is 4326 so output is Google Maps compatible
  if centroids
    column = 'centroid'
  elsif lowres
    column = "ST_Transform(geom_lowres, #{srid})"
  else
    column = 'geog'
  end

  properties_sql = []

  if include_record_identifiers
    properties_sql << "hstore(ARRAY['feature_name', name::varchar, 'feature_id', id::varchar, 'spatial_model_type', spatial_model_type::varchar, 'spatial_model_id', spatial_model_id::varchar])"
  end

  if properties
    properties_sql << "metadata"
  end

  if properties.is_a?(Hash)
    properties_sql << <<~SQL
      hstore(ARRAY[#{properties.flatten.map {|e| "'#{e.to_s}'" }.join(',')}])
    SQL
  end

  properties_sql = <<~SQL if properties_sql.present?
    , 'properties', hstore_to_json(#{properties_sql.join(' || ')})
  SQL

  sql = <<~SQL
    json_agg(
      json_build_object(
        'type', 'Feature',
        'geometry', ST_AsGeoJSON(#{column}, #{precision})::json
        #{properties_sql}
      )
    )
  SQL

  sql = <<~SQL unless features_only
    json_build_object(
      'type', 'FeatureCollection',
      'features', #{sql}
    )
  SQL
  SpatialFeatures::Utils.select_db_value(all.select(sql))
end

.intersecting(other) ⇒ Object



114
115
116
# File 'app/models/abstract_feature.rb', line 114

def self.intersecting(other)
  join_other_features(other).where('ST_Intersects(features.geom_lowres, other_features.geom_lowres)').distinct
end

.invalid(column = 'geog::geometry') ⇒ Object



122
123
124
# File 'app/models/abstract_feature.rb', line 122

def self.invalid(column = 'geog::geometry')
  select("features.*, ST_IsValidReason(#{column}) AS invalid_geometry_message").where.not("ST_IsValid(#{column})")
end

.linesObject



47
48
49
# File 'app/models/abstract_feature.rb', line 47

def self.lines
  where(:feature_type => 'line')
end

.metadata_keysObject



39
40
41
# File 'app/models/abstract_feature.rb', line 39

def self.
  unscope(:select, :order, :includes).distinct.pluck('skeys(metadata)')
end

.mvt(*args, **kwargs) ⇒ Object



165
166
167
168
169
170
171
172
173
174
# File 'app/models/abstract_feature.rb', line 165

def self.mvt(*args, **kwargs)
  select_sql = mvt_sql(*args, **kwargs)

  # Result is a hex string representing the desired binary output so we need to convert it to binary
  result = SpatialFeatures::Utils.select_db_value(select_sql)
  result.remove!(/^\\x/)
  result = [result].pack('H*')

  return result
end

.mvt_sql(tile_x, tile_y, zoom, properties: true, centroids: false, metadata: {}, scope: nil) ⇒ Object



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

def self.mvt_sql(tile_x, tile_y, zoom, properties: true, centroids: false, metadata: {}, scope: nil)
  if centroids
    column = 'ST_Transform(centroid::geometry, 3857)' # MVT works in SRID 3857
  else
    column = 'tilegeom'
  end

  subquery = select(:id)
              .select("ST_AsMVTGeom(#{column}, ST_TileEnvelope(#{zoom}, #{tile_x}, #{tile_y}), extent => 4096, buffer => 64) AS geom")
              .where("#{column} && ST_TileEnvelope(#{zoom}, #{tile_x}, #{tile_y}, margin => (64.0 / 4096))")
              .order(:id)

  # Merge additional scopes in to allow joins and other columns to be included in the feature output
  subquery = subquery.merge(scope) unless scope.nil?

  # Add metadata
  .each do |column, value|
    subquery = subquery.select("#{value} AS #{column}")
  end

  select_sql = <<~SQL
    SELECT ST_AsMVT(mvtgeom.*, 'default', 4096, 'geom', 'id') AS mvt
    FROM (#{subquery.to_sql}) mvtgeom
  SQL
end

.pointsObject



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

def self.points
  where(:feature_type => 'point')
end

.polygonsObject



43
44
45
# File 'app/models/abstract_feature.rb', line 43

def self.polygons
  where(:feature_type => 'polygon')
end

.total_intersection_area_in_square_meters(other_features, geom = 'geom_lowres') ⇒ Object



104
105
106
107
108
109
110
111
112
# File 'app/models/abstract_feature.rb', line 104

def self.total_intersection_area_in_square_meters(other_features, geom = 'geom_lowres')
  scope = unscope(:select).select("ST_Union(#{geom}) AS geom").polygons
  other_scope = other_features.polygons

  query = base_class.unscoped.select('ST_Area(ST_Intersection(ST_Union(features.geom), ST_Union(other_features.geom)))')
                  .from(scope, "features")
                  .joins("INNER JOIN (#{other_scope.to_sql}) AS other_features ON ST_Intersects(features.geom, other_features.geom)")
  return SpatialFeatures::Utils.select_db_value(query).to_f
end

.validObject



126
127
128
# File 'app/models/abstract_feature.rb', line 126

def self.valid
  where('ST_IsValid(geog::geometry)')
end

.with_metadata(k, v) ⇒ Object



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

def self.(k, v)
  if k.present? && v.present?
    where('metadata->? = ?', k, v)
  else
    all
  end
end

.within_distance(other, distance_in_meters) ⇒ Object



118
119
120
# File 'app/models/abstract_feature.rb', line 118

def self.within_distance(other, distance_in_meters)
  join_other_features(other).where('ST_DWithin(features.geom_lowres, other_features.geom_lowres, ?)', distance_in_meters).distinct
end

.within_distance_of_line(points, distance_in_meters, geom = 'geom_lowres') ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'app/models/abstract_feature.rb', line 67

def self.within_distance_of_line(points, distance_in_meters, geom = 'geom_lowres')
  point_sql =
    case geom.to_s
    when 'geog' then ':points'
    else "ST_Transform(ST_SetSRID(:points::geometry, 4326), #{detect_srid(geom)})"
    end

  binds = { :points => "LINESTRING(#{points.map {|coords| coords.join(' ') }.join(', ')})" }

  within_distance_of_sql(point_sql, distance_in_meters, geom, **binds)
end

.within_distance_of_point(lat, lng, distance_in_meters, geom = 'geom_lowres') ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'app/models/abstract_feature.rb', line 55

def self.within_distance_of_point(lat, lng, distance_in_meters, geom = 'geom_lowres')
  point_sql =
    case geom.to_s
    when 'geog' then 'ST_Point(:lng, :lat)'
    else "ST_Transform(ST_SetSRID(ST_Point(:lng, :lat), 4326), #{detect_srid(geom)})"
    end

  binds = { :lng => lng.to_d, :lat => lat.to_d }

  within_distance_of_sql(point_sql, distance_in_meters, geom, **binds)
end

.within_distance_of_polygon(points, distance_in_meters, geom = 'geom_lowres') ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
# File 'app/models/abstract_feature.rb', line 79

def self.within_distance_of_polygon(points, distance_in_meters, geom = 'geom_lowres')
  point_sql =
    case geom.to_s
    when 'geog' then "ST_Polygon(:points::geometry)"
    else "ST_Transform(ST_Polygon(:points::geometry, 4326), #{detect_srid(geom)})"
    end

  binds = { :points => "LINESTRING(#{points.map {|coords| coords.join(' ') }.join(', ')})" }

  within_distance_of_sql(point_sql, distance_in_meters, geom, **binds)
end

.within_distance_of_sql(geometry_sql, distance_in_meters, features_column = 'geom_lowres', **binds) ⇒ Object



91
92
93
94
95
96
97
# File 'app/models/abstract_feature.rb', line 91

def self.within_distance_of_sql(geometry_sql, distance_in_meters, features_column = 'geom_lowres', **binds)
  if distance_in_meters.to_f > 0
    where("ST_DWithin(features.#{features_column}, #{geometry_sql}, :distance)", **binds, :distance => distance_in_meters)
  else
    where("ST_Intersects(features.#{features_column}, #{geometry_sql})", **binds)
  end
end

.without_caching_derivatives(&block) ⇒ Object



139
140
141
142
143
144
145
# File 'app/models/abstract_feature.rb', line 139

def self.without_caching_derivatives(&block)
  old = automatically_cache_derivatives
  self.automatically_cache_derivatives = false
  block.call
ensure
  self.automatically_cache_derivatives = old
end

Instance Method Details

#boundsObject



255
256
257
# File 'app/models/abstract_feature.rb', line 255

def bounds
  slice(:north, :east, :south, :west).with_indifferent_access.transform_values!(&:to_f)
end

#cache_derivatives(*args) ⇒ Object



259
260
261
# File 'app/models/abstract_feature.rb', line 259

def cache_derivatives(*args)
  self.class.default_scoped.where(:id => self.id).cache_derivatives(*args)
end

#envelope(buffer_in_meters = 0) ⇒ Object



130
131
132
133
134
135
136
137
# File 'app/models/abstract_feature.rb', line 130

def envelope(buffer_in_meters = 0)
  envelope_json = JSON.parse(self.class.select("ST_AsGeoJSON(ST_Envelope(ST_Buffer(features.geog, #{buffer_in_meters})::geometry)) AS result").where(:id => id).first.result)
  envelope_json = envelope_json["coordinates"].first

  raise "Can't calculate envelope for Feature #{self.id}" if envelope_json.blank?

  return envelope_json.values_at(0,2)
end

#geojson(*args) ⇒ Object



268
269
270
# File 'app/models/abstract_feature.rb', line 268

def geojson(*args)
  self.class.where(id: id).geojson(*args)
end

#kml(options = {}) ⇒ Object



263
264
265
266
# File 'app/models/abstract_feature.rb', line 263

def kml(options = {})
  column = options[:lowres] ? 'geom_lowres' : 'geog'
  return SpatialFeatures::Utils.select_db_value(self.class.where(:id => id).select("ST_AsKML(#{column}, 6)"))
end

#make_valid?Boolean

Returns:

  • (Boolean)


272
273
274
# File 'app/models/abstract_feature.rb', line 272

def make_valid?
  @make_valid
end