wukong 3.0.0.pre2 → 3.0.0.pre3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (146) hide show
  1. data/Gemfile +13 -0
  2. data/README.md +182 -6
  3. data/bin/wu-local +13 -5
  4. data/bin/wu-server +1 -1
  5. data/examples/Gemfile +2 -1
  6. data/examples/basic/string_reverser.rb +23 -0
  7. data/examples/{tiny_count.rb → basic/tiny_count.rb} +0 -0
  8. data/examples/{word_count → basic/word_count}/accumulator.rb +0 -0
  9. data/examples/{word_count → basic/word_count}/tokenizer.rb +0 -0
  10. data/examples/{word_count → basic/word_count}/word_count.rb +0 -0
  11. data/examples/deploy_pack/Gemfile +7 -0
  12. data/examples/deploy_pack/README.md +6 -0
  13. data/examples/{text/latinize_text.rb → deploy_pack/a/b/c/.gitkeep} +0 -0
  14. data/examples/deploy_pack/app/processors/string_reverser.rb +5 -0
  15. data/examples/deploy_pack/config/environment.rb +1 -0
  16. data/examples/{dataflow → dsl/dataflow}/fibonacci_series.rb +0 -0
  17. data/examples/dsl/dataflow/scraper_macro_flow.rb +28 -0
  18. data/examples/{dataflow → dsl/dataflow}/simple.rb +0 -0
  19. data/examples/{dataflow → dsl/dataflow}/telegram.rb +0 -0
  20. data/examples/{workflow → dsl/workflow}/cherry_pie.dot +0 -0
  21. data/examples/{workflow → dsl/workflow}/cherry_pie.md +0 -0
  22. data/examples/{workflow → dsl/workflow}/cherry_pie.png +0 -0
  23. data/examples/{workflow → dsl/workflow}/cherry_pie.rb +0 -0
  24. data/examples/empty/.gitkeep +0 -0
  25. data/examples/graph/implied_geolocation/README.md +63 -0
  26. data/examples/graph/{minimum_spanning_tree.rb → minimum_spanning_tree/airfares_graphviz.rb} +0 -0
  27. data/examples/munging/airline_flights/indexable.rb +75 -0
  28. data/examples/munging/airline_flights/indexable_spec.rb +90 -0
  29. data/examples/munging/geo/geonames_models.rb +29 -0
  30. data/examples/munging/wikipedia/dbpedia/dbpedia_common.rb +1 -0
  31. data/examples/munging/wikipedia/dbpedia/extract_links-cruft.rb +66 -0
  32. data/examples/munging/wikipedia/dbpedia/extract_links.rb +213 -146
  33. data/examples/rake_helper.rb +12 -0
  34. data/examples/ruby_project/Gemfile +7 -0
  35. data/examples/ruby_project/README.md +6 -0
  36. data/examples/ruby_project/a/b/c/.gitkeep +0 -0
  37. data/examples/serverlogs/geo_ip_mapping/munge_geolite.rb +82 -0
  38. data/examples/serverlogs/models/logline.rb +102 -0
  39. data/examples/{dataflow/parse_apache_logs.rb → serverlogs/parser/apache_parser_widget.rb} +0 -0
  40. data/examples/serverlogs/visit_paths/common.rb +4 -0
  41. data/examples/serverlogs/visit_paths/page_counts.pig +48 -0
  42. data/examples/serverlogs/visit_paths/serverlogs-01-parse-script.rb +11 -0
  43. data/examples/serverlogs/visit_paths/serverlogs-02-histograms-full.rb +31 -0
  44. data/examples/serverlogs/visit_paths/serverlogs-02-histograms-mapper.rb +12 -0
  45. data/examples/serverlogs/visit_paths/serverlogs-03-breadcrumbs-full.rb +67 -0
  46. data/examples/serverlogs/visit_paths/serverlogs-04-page_page_edges-full.rb +38 -0
  47. data/examples/text/{pig_latin.rb → pig_latin/pig_latinizer.rb} +0 -0
  48. data/examples/{dataflow/pig_latinizer.rb → text/pig_latin/pig_latinizer_widget.rb} +0 -0
  49. data/lib/hanuman/graph.rb +6 -1
  50. data/lib/wu/geo.rb +4 -0
  51. data/lib/wu/geo/geo_grids.numbers +0 -0
  52. data/lib/wu/geo/geolocated.rb +331 -0
  53. data/lib/wu/geo/quadtile.rb +69 -0
  54. data/{examples → lib/wu}/graph/union_find.rb +0 -0
  55. data/lib/wu/model/reconcilable.rb +63 -0
  56. data/{examples/munging/wikipedia/utils/munging_utils.rb → lib/wu/munging.rb} +7 -4
  57. data/lib/wu/social/models/twitter.rb +31 -0
  58. data/{examples/models/wikipedia.rb → lib/wu/wikipedia/models.rb} +0 -0
  59. data/lib/wukong.rb +9 -4
  60. data/lib/wukong/boot.rb +10 -1
  61. data/lib/wukong/driver.rb +65 -71
  62. data/lib/wukong/logger.rb +93 -0
  63. data/lib/wukong/processor.rb +38 -29
  64. data/lib/wukong/runner.rb +144 -0
  65. data/lib/wukong/server.rb +119 -0
  66. data/lib/wukong/spec_helpers.rb +1 -0
  67. data/lib/wukong/spec_helpers/integration_driver.rb +22 -9
  68. data/lib/wukong/spec_helpers/integration_driver_matchers.rb +26 -4
  69. data/lib/wukong/spec_helpers/processor_helpers.rb +4 -10
  70. data/lib/wukong/spec_helpers/shared_examples.rb +12 -13
  71. data/lib/wukong/version.rb +1 -1
  72. data/lib/wukong/widget/processors.rb +13 -0
  73. data/lib/wukong/widget/serializers.rb +55 -65
  74. data/lib/wukong/widgets.rb +0 -2
  75. data/spec/hanuman/graph_spec.rb +14 -0
  76. data/spec/spec_helper.rb +4 -30
  77. data/spec/support/{wukong_test_helpers.rb → example_test_helpers.rb} +29 -2
  78. data/spec/support/integration_helper.rb +38 -0
  79. data/spec/support/model_test_helpers.rb +115 -0
  80. data/spec/wu/geo/geolocated_spec.rb +247 -0
  81. data/spec/wu/model/reconcilable_spec.rb +152 -0
  82. data/spec/wukong/widget/processors_spec.rb +0 -1
  83. data/spec/wukong/widget/serializers_spec.rb +88 -62
  84. data/spec/wukong/wu_local_spec.rb +125 -0
  85. data/wukong.gemspec +3 -16
  86. metadata +72 -266
  87. data/examples/dataflow/apache_log_line.rb +0 -100
  88. data/examples/jabberwocky.txt +0 -36
  89. data/examples/munging/Gemfile +0 -8
  90. data/examples/munging/airline_flights/airline.rb +0 -57
  91. data/examples/munging/airline_flights/airport.rb +0 -211
  92. data/examples/munging/airline_flights/flight.rb +0 -156
  93. data/examples/munging/airline_flights/models.rb +0 -4
  94. data/examples/munging/airline_flights/parse.rb +0 -26
  95. data/examples/munging/airline_flights/route.rb +0 -35
  96. data/examples/munging/airline_flights/timezone_fixup.rb +0 -62
  97. data/examples/munging/airports/40_wbans.txt +0 -40
  98. data/examples/munging/airports/filter_weather_reports.rb +0 -37
  99. data/examples/munging/airports/join.pig +0 -31
  100. data/examples/munging/airports/to_tsv.rb +0 -33
  101. data/examples/munging/airports/usa_wbans.pig +0 -19
  102. data/examples/munging/airports/usa_wbans.txt +0 -2157
  103. data/examples/munging/airports/wbans.pig +0 -19
  104. data/examples/munging/airports/wbans.txt +0 -2310
  105. data/examples/munging/rake_helper.rb +0 -62
  106. data/examples/munging/weather/.gitignore +0 -1
  107. data/examples/munging/weather/Gemfile +0 -4
  108. data/examples/munging/weather/Rakefile +0 -28
  109. data/examples/munging/weather/extract_ish.rb +0 -13
  110. data/examples/munging/weather/models/weather.rb +0 -119
  111. data/examples/munging/weather/utils/noaa_downloader.rb +0 -46
  112. data/examples/munging/wikipedia/README.md +0 -34
  113. data/examples/munging/wikipedia/Rakefile +0 -193
  114. data/examples/munging/wikipedia/n1_subuniverse/n1_nodes.pig +0 -18
  115. data/examples/munging/wikipedia/page_metadata/extract_page_metadata.rb +0 -21
  116. data/examples/munging/wikipedia/page_metadata/extract_page_metadata.rb.old +0 -27
  117. data/examples/munging/wikipedia/pagelinks/augment_pagelinks.pig +0 -29
  118. data/examples/munging/wikipedia/pagelinks/extract_pagelinks.rb +0 -14
  119. data/examples/munging/wikipedia/pagelinks/extract_pagelinks.rb.old +0 -25
  120. data/examples/munging/wikipedia/pagelinks/undirect_pagelinks.pig +0 -29
  121. data/examples/munging/wikipedia/pageviews/augment_pageviews.pig +0 -32
  122. data/examples/munging/wikipedia/pageviews/extract_pageviews.rb +0 -85
  123. data/examples/munging/wikipedia/pig_style_guide.md +0 -25
  124. data/examples/munging/wikipedia/redirects/redirects_page_metadata.pig +0 -19
  125. data/examples/munging/wikipedia/subuniverse/sub_articles.pig +0 -23
  126. data/examples/munging/wikipedia/subuniverse/sub_page_metadata.pig +0 -24
  127. data/examples/munging/wikipedia/subuniverse/sub_pagelinks_from.pig +0 -22
  128. data/examples/munging/wikipedia/subuniverse/sub_pagelinks_into.pig +0 -22
  129. data/examples/munging/wikipedia/subuniverse/sub_pagelinks_within.pig +0 -26
  130. data/examples/munging/wikipedia/subuniverse/sub_pageviews.pig +0 -29
  131. data/examples/munging/wikipedia/subuniverse/sub_undirected_pagelinks_within.pig +0 -24
  132. data/examples/munging/wikipedia/utils/get_namespaces.rb +0 -86
  133. data/examples/munging/wikipedia/utils/namespaces.json +0 -1
  134. data/examples/string_reverser.rb +0 -26
  135. data/examples/twitter/locations.rb +0 -29
  136. data/examples/twitter/models.rb +0 -24
  137. data/examples/twitter/pt1-fiddle.pig +0 -8
  138. data/examples/twitter/pt2-simple_parse.pig +0 -31
  139. data/examples/twitter/pt2-simple_parse.rb +0 -18
  140. data/examples/twitter/pt3-join_on_zips.pig +0 -39
  141. data/examples/twitter/pt4-strong_links.rb +0 -20
  142. data/examples/twitter/pt5-lnglat_and_strong_links.pig +0 -16
  143. data/examples/twitter/states.tsv +0 -50
  144. data/examples/workflow/package_gem.rb +0 -55
  145. data/lib/wukong/widget/sink.rb +0 -16
  146. data/lib/wukong/widget/source.rb +0 -14
data/lib/hanuman/graph.rb CHANGED
@@ -31,10 +31,15 @@ module Hanuman
31
31
 
32
32
  def build(options = {})
33
33
  attrs = serialize
34
- stages = attrs.delete(:stages).inject({}){ |hsh, (name, builder)| hsh[name] = builder.build(options) ; hsh }
34
+ stages = attrs.delete(:stages).inject({}){ |hsh, (name, builder)| hsh[name] = builder.build(stage_specific_options(name, options)) ; hsh }
35
35
  for_class.receive attrs.merge(stages: stages)
36
36
  end
37
37
 
38
+ def stage_specific_options(stage, options)
39
+ scope = options.delete(stage) || {}
40
+ options.merge(scope)
41
+ end
42
+
38
43
  def namespace() Hanuman::Graph ; end
39
44
 
40
45
  def handle_dsl_arguments_for(stage, *args, &blk)
data/lib/wu/geo.rb ADDED
@@ -0,0 +1,4 @@
1
+
2
+ require 'gorillib/data_munging'
3
+ require_relative 'geo/geolocated'
4
+ require_relative 'geo/quadtile'
Binary file
@@ -0,0 +1,331 @@
1
+ require 'gorillib/numeric/clamp'
2
+
3
+ Numeric.class_eval do
4
+ def to_radians() self.to_f * Math::PI / 180.0 ; end
5
+ def to_degrees() self.to_f * 180.0 / Math::PI ; end
6
+ end
7
+
8
+ module Wukong
9
+ #
10
+ # reference: [Bing Maps Tile System](http://msdn.microsoft.com/en-us/library/bb259689.aspx)
11
+ #
12
+ module Geolocated
13
+ module_function # call methods as eg Wukong::Geolocated.tile_xy_to_quadkey or, if included in class, on self as private methods
14
+
15
+ # field :longitude, type: Float, description: "Longitude (X) of a point, in decimal degrees"
16
+ # field :latitude, type: Float, description: "Latitude (Y) of a point, in decimal degrees"
17
+ # field :zoom_level, type: Integer, description: "Zoom level of tile to fetch. An integer between 0 (world) and 16 or so"
18
+ # field :quadkey, type: String, description: "Quadkey of tile, eg 002313012"
19
+ # field :tile_x, type: Integer, description: "Tile X index, an integer between 0 and 2^zoom_level - 1"
20
+ # field :tile_y, type: Integer, description: "Tile Y index, an integer between 0 and 2^zoom_level - 1"
21
+
22
+ module ByCoordinates
23
+ extend Gorillib::Concern
24
+
25
+ # The quadkey is a string of 2-bit tile selectors for a quadtile
26
+ #
27
+ # @example
28
+ # infochimps_hq = Geo::Place.receive("Infochimps HQ", -97.759003, 30.273884)
29
+ # infochimps_hq.quadkey(8) # => "02313012"
30
+ #
31
+ # Interesting quadkey properties:
32
+ #
33
+ # * The quadkey length is its zoom level
34
+ #
35
+ # * To zoom out (lower zoom level, larger quadtile), just truncate the
36
+ # quadkey: austin at ZL=8 has quadkey "02313012"; at ZL=3, "023"
37
+ #
38
+ # * Nearby points typically have "nearby" quadkeys: up to the smallest
39
+ # tile that contains both, their quadkeys will have a common prefix.
40
+ # If you sort your records by quadkey,
41
+ # - Nearby points are nearby-ish on disk. (hello, HBase/Cassandra
42
+ # database owners!) This allows efficient lookup and caching of
43
+ # "popular" regions or repeated queries in an area.
44
+ # - the tiles covering a region can be covered by a limited, enumerable
45
+ # set of range scans. For map-reduce programmers, this leads to very
46
+ # efficient reducers
47
+ #
48
+ # * The quadkey is the bit-interleaved combination of its tile ids:
49
+ #
50
+ # tile_x 58 binary 0 0 1 1 1 0 1 0
51
+ # tile_y 105 binary 0 1 1 0 1 0 0 1
52
+ # interleaved binary 00 10 11 01 11 00 01 10
53
+ # quadkey 0 2 3 1 3 0 1 2 # "02313012"
54
+ #
55
+ def quadkey(zl) ; Wukong::Geolocated.tile_xy_zl_to_quadkey( tile_x(zl), tile_y(zl), zl) ; end
56
+
57
+ # the packed quadkey is the integer formed by interleaving the bits of tile_x with tile_y:
58
+ #
59
+ # tile_x 58 binary 0 0 1 1 1 0 1 0
60
+ # tile_y 105 binary 0 1 1 0 1 0 0 1
61
+ # interleaved binary 00 10 11 01 11 00 01 10
62
+ # quadkey 0 2 3 1 3 0 1 2 # "02313012"
63
+ #
64
+ # (see `quadkey` for more.)
65
+ #
66
+ # At zoom level 15, the packed quadkey is a 30-bit unsigned integer --
67
+ # meaning you can store it in a pig `int`; for languages with an `unsigned
68
+ # int` type, you can go to zoom level 16 before you have to use a
69
+ # less-efficient type. Zoom level 15 has a resolution of about one tile
70
+ # per kilometer (about 1.25 km/tile near the equator; 0.75 km/tile at
71
+ # London's latitude). It takes 1 billion tiles to tile the world at that
72
+ # scale. Ruby's integer type goes up to 60 bits, enough for any practical
73
+ # zoom level.
74
+ #
75
+ def packed_qk ; Wukong::Geolocated.tile_xy_zl_to_packed_qk(tile_x(zl), tile_y(zl), zl) ; end
76
+
77
+ # @return [Float] x index of the tile this object lies on at given zoom level
78
+ def tile_xf(zl) ; Wukong::Geolocated.lng_zl_to_tile_xf(longitude, zl) ; end
79
+ # @return [Float] y index of the tile this object lies on at given zoom level
80
+ def tile_yf(zl) ; Wukong::Geolocated.lat_zl_to_tile_yf(latitude, zl) ; end
81
+ # @return [Integer] x index of the tile this object lies on at given zoom level
82
+ def tile_x(zl) ; tile_xf(zl).floor ; end
83
+ # @return [Integer] y index of the tile this object lies on at given zoom level
84
+ def tile_y(zl) ; tile_yf(zl).floor ; end
85
+
86
+ # @return [Float] tile coordinates `(x,y)` for this object at given zoom level
87
+ def tile_xy(zl) ; [tile_x(xl), tile_y(zl)] ; end
88
+
89
+ # @returns [Array<Numeric, Numeric>] a `[longitude, latitude]` pair representing object as a point.
90
+ def lng_lat ; [longitude, latitude] ; end
91
+
92
+ # @returns [left, btm, right, top]
93
+ def bbox_for_radius(radius) ; Wukong::Geolocated.lng_lat_rad_to_bbox(longitude, latitude, radius) ; end
94
+ end
95
+
96
+ EARTH_RADIUS = 6371000 # meters
97
+ MIN_LONGITUDE = -180
98
+ MAX_LONGITUDE = 180
99
+ MIN_LATITUDE = -85.05112878
100
+ MAX_LATITUDE = 85.05112878
101
+ ALLOWED_LONGITUDE = (MIN_LONGITUDE..MAX_LONGITUDE)
102
+ ALLOWED_LATITUDE = (MIN_LATITUDE..MAX_LATITUDE)
103
+ TILE_PIXEL_SIZE = 256
104
+
105
+ # Width or height in number of tiles
106
+ def map_tile_size(zl)
107
+ 1 << zl
108
+ end
109
+
110
+ #
111
+ # Tile coordinates
112
+ #
113
+
114
+ # Convert longitude in degrees to _floating-point_ tile x,y coordinates at given zoom level
115
+ def lng_zl_to_tile_xf(longitude, zl)
116
+ raise ArgumentError, "longitude must be within bounds ((#{longitude}) vs #{ALLOWED_LONGITUDE})" unless (ALLOWED_LONGITUDE.include?(longitude))
117
+ xx = (longitude.to_f + 180.0) / 360.0
118
+ (map_tile_size(zl) * xx)
119
+ end
120
+
121
+ # Convert latitude in degrees to _floating-point_ tile x,y coordinates at given zoom level
122
+ def lat_zl_to_tile_yf(latitude, zl)
123
+ raise ArgumentError, "latitude must be within bounds ((#{latitude}) vs #{ALLOWED_LATITUDE})" unless (ALLOWED_LATITUDE.include?(latitude))
124
+ sin_lat = Math.sin(latitude.to_radians)
125
+ yy = Math.log((1 + sin_lat) / (1 - sin_lat)) / (4 * Math::PI)
126
+ (map_tile_size(zl) * (0.5 - yy))
127
+ end
128
+
129
+ # Convert latitude in degrees to integer tile x,y coordinates at given zoom level
130
+ def lng_lat_zl_to_tile_xy(longitude, latitude, zl)
131
+ [lng_zl_to_tile_xf(longitude, zl).floor, lat_zl_to_tile_yf(latitude, zl).floor]
132
+ end
133
+
134
+ # Convert from tile_x, tile_y, zoom level to longitude and latitude in
135
+ # degrees (slight loss of precision).
136
+ #
137
+ # Tile coordinates may be floats or integer; they must lie within map range.
138
+ def tile_xy_zl_to_lng_lat(tile_x, tile_y, zl)
139
+ tile_size = map_tile_size(zl)
140
+ raise ArgumentError, "tile index must be within bounds ((#{tile_x},#{tile_y}) vs #{tile_size})" unless ((0..(tile_size-1)).include?(tile_x)) && ((0..(tile_size-1)).include?(tile_x))
141
+ xx = (tile_x.to_f / tile_size)
142
+ yy = 0.5 - (tile_y.to_f / tile_size)
143
+ lng = 360.0 * xx - 180.0
144
+ lat = 90 - 360 * Math.atan(Math.exp(-yy * 2 * Math::PI)) / Math::PI
145
+ [lng, lat]
146
+ end
147
+
148
+ #
149
+ # Quadkey coordinates
150
+ #
151
+
152
+ # converts from even/odd state of tile x and tile y to quadkey. NOTE: bit order means y, x
153
+ BIT_TO_QUADKEY = { [false, false] => "0", [false, true] => "1", [true, false] => "2", [true, true] => "3", }
154
+ # converts from quadkey char to bits. NOTE: bit order means y, x
155
+ QUADKEY_TO_BIT = { "0" => [0,0], "1" => [0,1], "2" => [1,0], "3" => [1,1]}
156
+
157
+ # Convert from tile x,y into a quadkey at a specified zoom level
158
+ def tile_xy_zl_to_quadkey(tile_x, tile_y, zl)
159
+ quadkey_chars = []
160
+ tx = tile_x.to_i
161
+ ty = tile_y.to_i
162
+ zl.times do
163
+ quadkey_chars.push BIT_TO_QUADKEY[[ty.odd?, tx.odd?]] # bit order y,x
164
+ tx >>= 1 ; ty >>= 1
165
+ end
166
+ quadkey_chars.join.reverse
167
+ end
168
+
169
+ # Convert a quadkey into tile x,y coordinates and level
170
+ def quadkey_to_tile_xy_zl(quadkey)
171
+ raise ArgumentError, "Quadkey must contain only the characters 0, 1, 2 or 3: #{quadkey}!" unless quadkey =~ /\A[0-3]*\z/
172
+ zl = quadkey.to_s.length
173
+ tx = 0 ; ty = 0
174
+ quadkey.chars.each do |char|
175
+ ybit, xbit = QUADKEY_TO_BIT[char] # bit order y, x
176
+ tx = (tx << 1) + xbit
177
+ ty = (ty << 1) + ybit
178
+ end
179
+ [tx, ty, zl]
180
+ end
181
+
182
+ # Convert from tile x,y into a packed quadkey at a specified zoom level
183
+ def tile_xy_zl_to_packed_qk(tile_x, tile_y, zl)
184
+ # don't optimize unless you're sure your way is faster; string ops are
185
+ # faster than you think and loops are slower than you think
186
+ quadkey_str = tile_xy_zl_to_quadkey(tile_x, tile_y, zl)
187
+ quadkey_str.to_i(4)
188
+ end
189
+
190
+ # Convert a packed quadkey (integer) into tile x,y coordinates and level
191
+ def packed_qk_zl_to_tile_xy(packed_qk, zl=16)
192
+ # don't "optimize" this without testing... string operations are faster than you think in ruby
193
+ raise ArgumentError, "Quadkey must be an integer in range of the zoom level: #{packed_qk}, #{zl}" unless packed_qk.is_a?(Fixnum) && (packed_qk < 2 ** (zl*2))
194
+ quadkey_rhs = packed_qk.to_s(4)
195
+ quadkey = ("0" * (zl - quadkey_rhs.length)) << quadkey_rhs
196
+ quadkey_to_tile_xy_zl(quadkey)
197
+ end
198
+
199
+ # Convert a lat/lng and zoom level into a quadkey
200
+ def lng_lat_zl_to_quadkey(longitude, latitude, zl)
201
+ tile_x, tile_y = lng_lat_zl_to_tile_xy(longitude, latitude, zl)
202
+ tile_xy_zl_to_quadkey(tile_x, tile_y, zl)
203
+ end
204
+
205
+ #
206
+ # Bounding box coordinates
207
+ #
208
+
209
+ # Convert a quadkey into a bounding box using adjacent tile
210
+ def quadkey_to_bbox(quadkey)
211
+ tile_x, tile_y, zl = quadkey_to_tile_xy_zl(quadkey)
212
+ # bottom right of me is top left of my southeast neighbor
213
+ left, top = tile_xy_zl_to_lng_lat(tile_x, tile_y, zl)
214
+ right, btm = tile_xy_zl_to_lng_lat(tile_x + 1, tile_y + 1, zl)
215
+ [left, btm, right, top]
216
+ end
217
+
218
+ # Retuns the smallest quadkey containing both of corners of the given bounding box
219
+ def quadkey_containing_bbox(left, btm, right, top)
220
+ qk_tl = lng_lat_zl_to_quadkey(left, top, 23)
221
+ qk_2 = lng_lat_zl_to_quadkey(right, btm, 23)
222
+ # the containing qk is the longest one that both agree on
223
+ containing_key = ""
224
+ qk_tl.chars.zip(qk_2.chars).each do |char_tl, char_2|
225
+ break if char_tl != char_2
226
+ containing_key << char_tl
227
+ end
228
+ containing_key
229
+ end
230
+
231
+ # Returns a bounding box containing the circle created by the lat/lng and radius
232
+ def lng_lat_rad_to_bbox(longitude, latitude, radius)
233
+ left, _ = point_east( longitude, latitude, -radius)
234
+ _, btm = point_north(longitude, latitude, -radius)
235
+ right, _ = point_east( longitude, latitude, radius)
236
+ _, top = point_north(longitude, latitude, radius)
237
+ [left, btm, right, top]
238
+ end
239
+
240
+ # Returns the centroid of a bounding box
241
+ #
242
+ # @param [Array<Float, Float>] left_btm Longitude, Latitude of SW point
243
+ # @param [Array<Float, Float>] right_top Longitude, Latitude of NE point
244
+ #
245
+ # @return [Array<Float, Float>] Longitude, Latitude of centroid
246
+ def bbox_centroid(left_btm, right_top)
247
+ haversine_midpoint(*left_btm, *right_top)
248
+ end
249
+
250
+ # Return the haversine distance in meters between two points
251
+ def haversine_distance(left, btm, right, top)
252
+ delta_lng = (right - left).abs.to_radians
253
+ delta_lat = (top - btm ).abs.to_radians
254
+ btm_rad = btm.to_radians
255
+ top_rad = top.to_radians
256
+
257
+ aa = (Math.sin(delta_lat / 2.0))**2 + Math.cos(top_rad) * Math.cos(btm_rad) * (Math.sin(delta_lng / 2.0))**2
258
+ cc = 2.0 * Math.atan2(Math.sqrt(aa), Math.sqrt(1.0 - aa))
259
+ cc * EARTH_RADIUS
260
+ end
261
+
262
+ # Return the haversine midpoint in meters between two points
263
+ def haversine_midpoint(left, btm, right, top)
264
+ cos_btm = Math.cos(btm.to_radians)
265
+ cos_top = Math.cos(top.to_radians)
266
+ bearing_x = cos_btm * Math.cos((right - left).to_radians)
267
+ bearing_y = cos_btm * Math.sin((right - left).to_radians)
268
+ mid_lat = Math.atan2(
269
+ (Math.sin(top.to_radians) + Math.sin(btm.to_radians)),
270
+ (Math.sqrt((cos_top + bearing_x)**2 + bearing_y**2)))
271
+ mid_lng = left.to_radians + Math.atan2(bearing_y, (cos_top + bearing_x))
272
+ [mid_lng.to_degrees, mid_lat.to_degrees]
273
+ end
274
+
275
+ # From a given point, calculate the point directly north a specified distance
276
+ def point_north(longitude, latitude, distance)
277
+ north_lat = (latitude.to_radians + (distance.to_f / EARTH_RADIUS)).to_degrees
278
+ [longitude, north_lat]
279
+ end
280
+
281
+ # From a given point, calculate the change in degrees directly east a given distance
282
+ def point_east(longitude, latitude, distance)
283
+ radius = EARTH_RADIUS * Math.sin(((Math::PI / 2.0) - latitude.to_radians.abs))
284
+ east_lng = (longitude.to_radians + (distance.to_f / radius)).to_degrees
285
+ [east_lng, latitude]
286
+ end
287
+
288
+ #
289
+ # Pixel coordinates
290
+ #
291
+ # Use with a standard (256x256 pixel) grid-based tileserver
292
+ #
293
+
294
+ # Width or height of grid bitmap in pixels at given zoom level
295
+ def map_pixel_size(zl)
296
+ TILE_PIXEL_SIZE * map_tile_size(zl)
297
+ end
298
+
299
+ # Return pixel resolution in meters per pixel at a specified latitude and zoom level
300
+ def pixel_resolution(latitude, zl)
301
+ lat = latitude.clamp(MIN_LATITUDE, MAX_LATITUDE)
302
+ Math.cos(lat.to_radians) * 2 * Math::PI * EARTH_RADIUS / map_pixel_size(zl).to_f
303
+ end
304
+
305
+ # Map scale at a specified latitude, zoom level, & screen resolution in dpi
306
+ def map_scale_for_dpi(latitude, zl, screen_dpi)
307
+ pixel_resolution(latitude, zl) * screen_dpi / 0.0254
308
+ end
309
+
310
+ # Convert from x,y pixel pair into tile x,y coordinates
311
+ def pixel_xy_to_tile_xy(pixel_x, pixel_y)
312
+ [pixel_x / TILE_PIXEL_SIZE, pixel_y / TILE_PIXEL_SIZE]
313
+ end
314
+
315
+ # Convert from x,y tile pair into pixel x,y coordinates (top left corner)
316
+ def tile_xy_to_pixel_xy(tile_x, tile_y)
317
+ [tile_x * TILE_PIXEL_SIZE, tile_y * TILE_PIXEL_SIZE]
318
+ end
319
+
320
+ def pixel_xy_zl_to_lng_lat(pixel_x, pixel_y, zl)
321
+ tile_xy_zl_to_lng_lat(pixel_x.to_f / TILE_PIXEL_SIZE, pixel_y.to_f / TILE_PIXEL_SIZE, zl)
322
+ end
323
+
324
+ def lng_lat_zl_to_pixel_xy(lng, lat, zl)
325
+ pixel_x = lng_zl_to_tile_xf(lng, zl)
326
+ pixel_y = lat_zl_to_tile_yf(lat, zl)
327
+ [(pixel_x * TILE_PIXEL_SIZE + 0.5).floor, (pixel_y * TILE_PIXEL_SIZE + 0.5).floor]
328
+ end
329
+
330
+ end
331
+ end
@@ -0,0 +1,69 @@
1
+ module Wukong
2
+ module Geo
3
+ class Quadtile
4
+ include Gorillib::Model
5
+ #
6
+ field :tile_x, Integer, position: 0, doc: "Tile X index, an integer between 0 and 2^zoom_level - 1"
7
+ field :tile_y, Integer, position: 1, doc: "Tile Y index, an integer between 0 and 2^zoom_level - 1"
8
+ field :zl, Integer, position: 2, doc: "Zoom level of tile to fetch. 0 is the world; 16 is about a kilometer."
9
+ field :slug, String, default: 'tile', doc: "Name, prefixed on saved tiles"
10
+
11
+ def quadkey ; Wukong::Geolocated.tile_xy_zl_to_quadkey( tile_x, tile_y, zl) ; end
12
+ def packed_qk ; Wukong::Geolocated.tile_xy_zl_to_packed_qk(tile_x, tile_y, zl) ; end
13
+
14
+ # Base of URL for map tile server; anything X/Y/Z.png-addressable works,
15
+ # eg `http://b.tile.openstreetmap.org`. Defaults to 'http://b.tile.stamen.com/toner-lite'`.
16
+ class_attribute :tileserver_url_base
17
+ self.tileserver_url_base = 'http://a.tile.stamen.com/toner-lite'
18
+
19
+ def self.from_whatever(hsh)
20
+ zl = hsh[:zl] ? hsh[:zl].to_i : nil
21
+ case
22
+ when hsh[:tile_x].present? && hsh[:tile_y].present? && zl.present?
23
+ tile_x, tile_y = [hsh[:tile_x], hsh[:tile_y]]
24
+ when hsh[:longitude].present? && hsh[:latitude].present? && zl.present?
25
+ tile_x, tile_y = Wukong::Geolocated.lng_lat_zl_to_tile_xy(hsh[:longitude], hsh[:latitude], zl)
26
+ when hsh[:quadkey].present?
27
+ quadkey = hsh[:quadkey]
28
+ quadkey = quadkey[0..zl] if zl.to_i > 0
29
+ tile_x, tile_y, zl = Wukong::Geolocated.quadkey_to_tile_xy_zl(quadkey)
30
+ else
31
+ raise ArgumentError, "You must supply keys for either `:longitude`, `:latitude` and `:zl`; `:tile_x`, `:tile_y` and `:zl`; or `:quadkey`: #{hsh.inspect}"
32
+ end
33
+ return new(tile_x, tile_y, zl, hsh.to_hash)
34
+ end
35
+
36
+ def self.tileserver_conn
37
+ @tileserver_conn = Faraday.new(:url => tileserver_url_base)
38
+ end
39
+
40
+ def tile_url
41
+ [tileserver_url_base, zl, tile_x, tile_y].join('/') << ".png"
42
+ end
43
+
44
+ # A
45
+ #
46
+ # @example
47
+ # qt = Quadtile.from_whatever(longitude: -97.759003, latitude: 30.273884, zl: 15)
48
+ # qt.slug # tile-15-64587
49
+ #
50
+ #
51
+ # @returns [String]
52
+ def basename(options={})
53
+ options = { sep: '-', ext: 'png'}
54
+ sep = options[:sep]
55
+ # "%s%s%02d%s%04d%s%04d.%s" % [slug, sep, zl, sep, tile_x, sep, tile_y, options[:ext]]
56
+ "%s/%02d/%s%s%s.%s" % [slug, zl, slug, sep, quadkey, options[:ext]]
57
+ end
58
+
59
+ # Fetch the contents of a map tile from a tileserver
60
+ #
61
+ # You are responsible for requiring the faraday library and its adapter
62
+ #
63
+ def fetch
64
+ self.class.tileserver_conn.get(tile_url)
65
+ end
66
+
67
+ end
68
+ end
69
+ end
File without changes
@@ -0,0 +1,63 @@
1
+ module Gorillib
2
+ module Model
3
+ module Reconcilable
4
+ # @returns [Hash] all attributes that are set with non-nil values
5
+ def reconcilable_attributes
6
+ compact_attributes.compact!
7
+ end
8
+
9
+ # * asks the other object what attributes it has to give, via `#reconcilable_attrs`
10
+ # * if this instance has a `adopt_foo` method, calls it; all further
11
+ # action (such as setting the consensus value) is done over there
12
+ # * otherwise, calls adopt_attribute(attr, val) to set the consensus value
13
+ #
14
+ def adopt(obj)
15
+ peace = true
16
+ obj.reconcilable_attributes.each do |attr, val|
17
+ if self.respond_to?("adopt_#{attr}")
18
+ result = self.public_send("adopt_#{attr}", val, obj)
19
+ else
20
+ result = adopt_attribute(attr, val)
21
+ end
22
+ peace &&= result
23
+ end
24
+ peace
25
+ end
26
+
27
+ def conflicting_attribute!(attr, this_val, that_val)
28
+ warn " - conflicting values for #{attr}: had #{this_val.inspect} got #{that_val.inspect}"
29
+ false
30
+ end
31
+
32
+ protected
33
+ #
34
+ #
35
+ # * if our value is unset or nil: sets it to `that_val` and returns true
36
+ # * if our value is equal to `that_val`: does nothing and returns true
37
+ # * if our value is a reconcilable object,
38
+ # - have it adopt `that_val`
39
+ # - return the result
40
+ # * otherwise the two values are in conflict:
41
+ # - warn about the conflict
42
+ # - return false
43
+ #
44
+ # note: this does _not_ treat a set-but-nil value on itself as important;
45
+ # override the `adopt_{attr}` method if you want that behavior.
46
+ #
47
+ def adopt_attribute(attr, that_val)
48
+ # handle unset immediately,so defaults / lazy evaluations aren't triggered
49
+ if not attribute_set?(attr) then write_attribute(attr, that_val) ; return true ; end
50
+ this_val = read_attribute(attr)
51
+ if this_val.nil? then write_attribute(attr, that_val) ; return true
52
+ elsif this_val == that_val then return true
53
+ elsif this_val.respond_to?(:adopt) then return this_val.adopt(that_val)
54
+ elsif block_given?
55
+ return yield(attr, this_val, that_val)
56
+ else
57
+ return conflicting_attribute!(attr, this_val, that_val)
58
+ end
59
+ end
60
+
61
+ end
62
+ end
63
+ end