polyline-normalizer 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9ca14e34f0d7c6f2a122d9e7d7a5e9e7fd36e0a558ca51cf70c8be26363dca37
4
+ data.tar.gz: 9cdb793c129e20d02dd436bda4e9bd13de1d69c4a8e89d9fdd8c3d1472f25980
5
+ SHA512:
6
+ metadata.gz: 9696e41187b0683c5af455fd752a01e434f2b7cae9e8a5414cc052a373ccfb52f4724a8e1f4124be895652168eb1d3c1a06d9b9fbfa3258c209b49bc2c9f655c
7
+ data.tar.gz: ab7a4f54195ec183e95ffdd9f659b9c2e2b1a342de10e521ae445ce7792d8018a27d3ad9290fa44507259dd06b4bd32bc054824a72deeeeebb48823676ab08b8
@@ -0,0 +1,14 @@
1
+ name: Ruby
2
+ on: [push,pull_request]
3
+ jobs:
4
+ build:
5
+ runs-on: ubuntu-latest
6
+ steps:
7
+ - uses: actions/checkout@v2
8
+ - name: Set up Ruby
9
+ uses: ruby/setup-ruby@v1
10
+ with:
11
+ ruby-version: '2.7'
12
+ bundler-cache: true
13
+ - name: Run Tests
14
+ run: bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
10
+ vendor/bundle
11
+
12
+ # rspec failure tracking
13
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,14 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ SuggestExtensions: false
4
+ Gemspec/RequiredRubyVersion:
5
+ Enabled: false
6
+ Metrics/AbcSize:
7
+ Max: 30
8
+ Metrics/MethodLength:
9
+ Max: 25
10
+ Naming/FileName:
11
+ Exclude:
12
+ - 'lib/polyline-normalizer.rb'
13
+ Style/Documentation:
14
+ Enabled: false
data/.simplecov ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ SimpleCov.start do
4
+ SimpleCov.minimum_coverage 100.00
5
+ end
data/CODEOWNERS ADDED
@@ -0,0 +1 @@
1
+ * @amaabca/red
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at channel.developer@ama.ab.ca. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
6
+
7
+ gem 'pry'
8
+ gem 'rake'
9
+ gem 'rspec'
10
+ gem 'rubocop'
11
+ gem 'simplecov'
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Alberta Motor Association
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # Polyline::Normalizer
2
+
3
+ This library implements a heuristic-based approach to normalize paths encoded with the [Google Polyline Format](https://developers.google.com/maps/documentation/utilities/polylinealgorithm).
4
+
5
+ The goal of this project is to "clean up" existing polyline data to match real-world roadway segments.
6
+
7
+ For example, we want to take a polyline that looks something like:
8
+
9
+ ![Input](https://raw.github.com/amaabca/polyline-normalizer/master/data/original.png)
10
+
11
+ and produce an output line that looks like this:
12
+
13
+ ![Output](https://raw.github.com/amaabca/polyline-normalizer/master/data/normalized.png)
14
+
15
+ The algorithm attempts to order the points encoded in the polyline by closest [geodesic distance](https://en.wikipedia.org/wiki/Great-circle_distance) to one another. This approach may produce sub-optimal output if a polyline contains points that vary greatly in direction, yet are close to one another.
16
+
17
+ ## Installation
18
+
19
+ Add this line to your application's Gemfile:
20
+
21
+ ```ruby
22
+ gem 'polyline-normalizer'
23
+ ```
24
+
25
+ And then execute:
26
+
27
+ $ bundle install
28
+
29
+ Or install it yourself as:
30
+
31
+ $ gem install polyline-normalizer
32
+
33
+ ## Usage
34
+
35
+ To normalize an encoded polyline, simply do the following:
36
+
37
+ ```ruby
38
+ require 'polyline-normalizer'
39
+ encoded_polyline = 'kjrlHlbjvTa`@A...'
40
+ Polyline::Normalizer::RoadSegment.new(encoded_polyline).normalize # => returns a string representing the normalized encoded polyline
41
+ ```
42
+
43
+ ## Development
44
+
45
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
46
+
47
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
48
+
49
+ ## Contributing
50
+
51
+ Bug reports and pull requests are welcome on GitHub at https://github.com/amaabca/polyline-normalizer. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/amaabca/polyline-normalizer/blob/master/CODE_OF_CONDUCT.md).
52
+
53
+ ## License
54
+
55
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
56
+
57
+ ## Code of Conduct
58
+
59
+ Everyone interacting in the Polyline::Normalizer project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/amaabca/polyline-normalizer/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[rubocop spec]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'polyline/normalizer'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
Binary file
data/data/original.png ADDED
Binary file
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Polyline
4
+ module Normalizer
5
+ class RoadSegment
6
+ EARTHS_RADIUS = 6_371_000.to_f # meters
7
+ DEGREES_TO_RADIANS = Math::PI / 180
8
+
9
+ attr_accessor(
10
+ :input,
11
+ :points,
12
+ :distance_threshold
13
+ )
14
+
15
+ def initialize(input, distance_threshold: 5000)
16
+ self.input = input
17
+ self.distance_threshold = distance_threshold
18
+ self.points = FastPolylines.decode(input).uniq
19
+ end
20
+
21
+ def normalize
22
+ @normalize ||= FastPolylines.encode(join(divide))
23
+ end
24
+
25
+ private
26
+
27
+ # Perform a basic heuristic to determine what we should sort by (either
28
+ # the lat or the lon coordinate).
29
+ #
30
+ # If the difference between the latitudes of the start/end point is
31
+ # greater than the difference of the longitudes of the start/end point,
32
+ # then sort by latitude (south to north). Otherwise sort by longitude
33
+ # (east to west).
34
+ def sort_by_index
35
+ start = points.first
36
+ stop = points.last
37
+ d_lat = (stop[0] - start[0]).abs
38
+ d_lon = (stop[1] - start[1]).abs
39
+
40
+ if d_lat > d_lon
41
+ 0
42
+ else
43
+ 1
44
+ end
45
+ end
46
+
47
+ def join(parts)
48
+ sort_index = sort_by_index
49
+ parts
50
+ .sort { |a, b| a.first[sort_index] <=> b.first[sort_index] }
51
+ .each_with_object([]) { |s, acc| acc.push(*s) }
52
+ end
53
+
54
+ def divide
55
+ unvisited_nodes = points.dup
56
+ path = [unvisited_nodes.pop]
57
+ segments = [path]
58
+
59
+ while unvisited_nodes.any?
60
+ current = path.last
61
+ min_index = -1
62
+ min_distance = Float::INFINITY
63
+
64
+ unvisited_nodes.each_with_index do |point, index|
65
+ distance = geodesic_distance(current, point)
66
+
67
+ if distance < min_distance
68
+ min_distance = distance
69
+ min_index = index
70
+ end
71
+ end
72
+
73
+ if min_distance > distance_threshold
74
+ # new segment
75
+ path = [unvisited_nodes.delete_at(min_index)]
76
+ segments << path
77
+ else
78
+ path.push(unvisited_nodes.delete_at(min_index))
79
+ end
80
+ end
81
+
82
+ segments
83
+ end
84
+
85
+ # returns the geodesic distance between 2 lat/lon coordinates in metres
86
+ # calculated from the haversine formula for great-circle distance
87
+ def geodesic_distance(one, two)
88
+ # first make sure all of our inputs are in radians
89
+ delta_lat = (two[0] - one[0]) * DEGREES_TO_RADIANS
90
+ delta_lon = (two[1] - one[1]) * DEGREES_TO_RADIANS
91
+ lat_one = one[0] * DEGREES_TO_RADIANS
92
+ lat_two = two[0] * DEGREES_TO_RADIANS
93
+
94
+ # haversine formula
95
+ a = (Math.sin(delta_lat / 2)**2) +
96
+ ((Math.sin(delta_lon / 2)**2) *
97
+ Math.cos(lat_one) * Math.cos(lat_two))
98
+ c = 2 * Math.asin(Math.sqrt(a))
99
+ c * EARTHS_RADIUS
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Polyline
4
+ module Normalizer
5
+ VERSION = '1.0.0'
6
+ end
7
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fast-polylines'
4
+ require_relative 'normalizer/version'
5
+ require_relative 'normalizer/road_segment'
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'polyline/normalizer'
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/polyline/normalizer/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'polyline-normalizer'
7
+ spec.version = Polyline::Normalizer::VERSION
8
+ spec.authors = [
9
+ 'Jesse Doyle',
10
+ 'Michael van den Beuken',
11
+ 'Darko Dosenovic',
12
+ 'Zoie Carnegie'
13
+ ]
14
+ spec.email = [
15
+ 'jesse.doyle@ama.ab.ca',
16
+ 'michael.vandenbeuken@ama.ab.ca',
17
+ 'darko.dosenovic@ama.ab.ca',
18
+ 'zoie.carnegie@ama.ab.ca'
19
+ ]
20
+ spec.summary = 'Normalize paths encoded with the Google Polyline Algorithm'
21
+ spec.description = <<~SUMMARY
22
+ Sort and scale the points of a path encoded with the Google Polyline
23
+ Algorithm by distance to one another.
24
+ SUMMARY
25
+ spec.homepage = 'https://github.com/amaabca/polyline-normalizer'
26
+ spec.license = 'MIT'
27
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
28
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org/'
29
+ spec.metadata['homepage_uri'] = spec.homepage
30
+ spec.metadata['source_code_uri'] = spec.homepage
31
+ spec.metadata['rubygems_mfa_required'] = 'true'
32
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
33
+ `git ls-files -z`
34
+ .split("\x0")
35
+ .reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
36
+ end
37
+ spec.bindir = 'exe'
38
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
39
+ spec.require_paths = ['lib']
40
+ spec.add_dependency 'fast-polylines', '~> 2.0'
41
+ end
metadata ADDED
@@ -0,0 +1,89 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: polyline-normalizer
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Jesse Doyle
8
+ - Michael van den Beuken
9
+ - Darko Dosenovic
10
+ - Zoie Carnegie
11
+ autorequire:
12
+ bindir: exe
13
+ cert_chain: []
14
+ date: 2021-11-25 00:00:00.000000000 Z
15
+ dependencies:
16
+ - !ruby/object:Gem::Dependency
17
+ name: fast-polylines
18
+ requirement: !ruby/object:Gem::Requirement
19
+ requirements:
20
+ - - "~>"
21
+ - !ruby/object:Gem::Version
22
+ version: '2.0'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '2.0'
30
+ description: |
31
+ Sort and scale the points of a path encoded with the Google Polyline
32
+ Algorithm by distance to one another.
33
+ email:
34
+ - jesse.doyle@ama.ab.ca
35
+ - michael.vandenbeuken@ama.ab.ca
36
+ - darko.dosenovic@ama.ab.ca
37
+ - zoie.carnegie@ama.ab.ca
38
+ executables: []
39
+ extensions: []
40
+ extra_rdoc_files: []
41
+ files:
42
+ - ".github/workflows/main.yml"
43
+ - ".gitignore"
44
+ - ".rspec"
45
+ - ".rubocop.yml"
46
+ - ".simplecov"
47
+ - CODEOWNERS
48
+ - CODE_OF_CONDUCT.md
49
+ - Gemfile
50
+ - LICENSE
51
+ - README.md
52
+ - Rakefile
53
+ - bin/console
54
+ - bin/setup
55
+ - data/normalized.png
56
+ - data/original.png
57
+ - lib/polyline-normalizer.rb
58
+ - lib/polyline/normalizer.rb
59
+ - lib/polyline/normalizer/road_segment.rb
60
+ - lib/polyline/normalizer/version.rb
61
+ - polyline-normalizer.gemspec
62
+ homepage: https://github.com/amaabca/polyline-normalizer
63
+ licenses:
64
+ - MIT
65
+ metadata:
66
+ allowed_push_host: https://rubygems.org/
67
+ homepage_uri: https://github.com/amaabca/polyline-normalizer
68
+ source_code_uri: https://github.com/amaabca/polyline-normalizer
69
+ rubygems_mfa_required: 'true'
70
+ post_install_message:
71
+ rdoc_options: []
72
+ require_paths:
73
+ - lib
74
+ required_ruby_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: 2.3.0
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: '0'
84
+ requirements: []
85
+ rubygems_version: 3.1.2
86
+ signing_key:
87
+ specification_version: 4
88
+ summary: Normalize paths encoded with the Google Polyline Algorithm
89
+ test_files: []