Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Geocoding 2.0 #304

Merged
merged 79 commits into from
Jan 29, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
79 commits
Select commit Hold shift + click to select a range
173d618
Put parents into regions dataframe and geodataframe
IKupriyanov-HORIS Sep 11, 2020
c8f8d1b
Implementing parents in regions_builder.
IKupriyanov-HORIS Sep 14, 2020
1fccca9
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Sep 14, 2020
6fef609
WIP: parents
IKupriyanov-HORIS Sep 15, 2020
9b5ae98
Fix tests, sync protocol with server
IKupriyanov-HORIS Sep 15, 2020
38f1db7
Fix more tests
IKupriyanov-HORIS Sep 16, 2020
54b4457
Fix more tests
IKupriyanov-HORIS Sep 25, 2020
299b6aa
New server IP in demo
IKupriyanov-HORIS Sep 25, 2020
701f78c
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Oct 5, 2020
a37a3f5
WIP: answers in protocol
IKupriyanov-HORIS Oct 14, 2020
f6ca8a3
WIP: moving to Answers instead of flat list of GeocodedFeature
IKupriyanov-HORIS Oct 14, 2020
52e7c1f
WIP: link between request and response
IKupriyanov-HORIS Oct 15, 2020
be18cc5
Getting rid of a query string from Answer and GeocodedFeature
IKupriyanov-HORIS Oct 17, 2020
e8219a8
Remove query from Answer and GeocodedFeature
IKupriyanov-HORIS Oct 19, 2020
326550b
Fix assertion condition
IKupriyanov-HORIS Oct 20, 2020
f6fc7c8
Remove chunked requests, better docs for new API
IKupriyanov-HORIS Oct 20, 2020
cbc1745
WIP: scope
IKupriyanov-HORIS Oct 21, 2020
02aa0ba
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Oct 21, 2020
cca501d
Update example with counties
IKupriyanov-HORIS Oct 22, 2020
91b027a
Update example with counties
IKupriyanov-HORIS Oct 22, 2020
21ec386
Basic support for scope in the new geocoding API
IKupriyanov-HORIS Oct 22, 2020
6f99bbe
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Oct 23, 2020
60968ca
Default scope value to None
IKupriyanov-HORIS Oct 26, 2020
f44d979
Unit tests for new geocoding API
IKupriyanov-HORIS Oct 28, 2020
9ed17b0
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Oct 28, 2020
539ef98
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Oct 28, 2020
4345821
Request validation, tests
IKupriyanov-HORIS Oct 28, 2020
648eef7
Experiment with map and nbviewer
IKupriyanov-HORIS Oct 29, 2020
d492167
Experiment with map and nbviewer and stamen tiles
IKupriyanov-HORIS Oct 29, 2020
bc846fa
Better parents/scope support, more tests
IKupriyanov-HORIS Oct 30, 2020
dcfd17b
where(..., near=..., within=...)
IKupriyanov-HORIS Nov 2, 2020
41e0ce1
Better error handling
IKupriyanov-HORIS Nov 3, 2020
26804b4
Tests for not available features in new API
IKupriyanov-HORIS Nov 4, 2020
fbd7c50
Better error handling for where function (missing key, scope and othe…
IKupriyanov-HORIS Nov 5, 2020
c444036
map_join with multikeys
IKupriyanov-HORIS Nov 14, 2020
0e213d9
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Nov 14, 2020
f7f5df8
Single key data_join_on and map_join_on.
IKupriyanov-HORIS Nov 15, 2020
a31ca74
Multi key data_join_on and map_join_on.
IKupriyanov-HORIS Nov 16, 2020
1f69608
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Nov 23, 2020
08f250f
map_join with dups, but livemap fails with null values in data
IKupriyanov-HORIS Nov 24, 2020
71060c2
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Nov 25, 2020
6c5f57b
Handle null values in pie/bar
IKupriyanov-HORIS Nov 26, 2020
cec1bdc
LP-62
IKupriyanov-HORIS Nov 27, 2020
c5375fb
Better error message on using scope with parents
IKupriyanov-HORIS Dec 4, 2020
5a2569d
Better error message for invalid scope type, countries request suppor…
IKupriyanov-HORIS Dec 7, 2020
4926246
More tests for us-48
IKupriyanov-HORIS Dec 8, 2020
c7c72ba
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Dec 8, 2020
dc5a21f
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Dec 14, 2020
b0ba74f
WIP: changing public API
IKupriyanov-HORIS Dec 15, 2020
536ed25
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Dec 18, 2020
fe750f7
Support Geocoder as geom_xxx(map=...) parameter
IKupriyanov-HORIS Dec 21, 2020
c317a16
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Dec 21, 2020
7531be1
Code cleanup, more tests
IKupriyanov-HORIS Dec 22, 2020
425fef3
Copy not matched dups from map on map_join (fix for last cell in geop…
IKupriyanov-HORIS Dec 23, 2020
ed5f0ea
Use single entry parent for all names
IKupriyanov-HORIS Dec 23, 2020
371525a
Fix empty result for select all kind of request
IKupriyanov-HORIS Dec 24, 2020
481b90d
where -> scope, near -> closest_to, single entry scope, remove auto-c…
IKupriyanov-HORIS Jan 11, 2021
4f3e114
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Jan 11, 2021
5002f32
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Jan 11, 2021
d316cbe
Remove MapRegion from 'scope' type error message
IKupriyanov-HORIS Jan 13, 2021
bfe2d0b
scope can now be used with county and state. scope and country will c…
IKupriyanov-HORIS Jan 14, 2021
f1a3014
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Jan 18, 2021
e747a7e
Handle any Iterable types in parents functions (counties/states/count…
IKupriyanov-HORIS Jan 20, 2021
3915dba
Enable gzip for geocoding responses
IKupriyanov-HORIS Jan 21, 2021
d8b1fac
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Jan 21, 2021
93c7aaa
Update docs
IKupriyanov-HORIS Jan 21, 2021
f1e98cd
Update docs
IKupriyanov-HORIS Jan 21, 2021
4b4a9ba
Keep original query name for ambiguous result with allow_ambiguous flag
IKupriyanov-HORIS Jan 22, 2021
ffaaab8
Fix error message
IKupriyanov-HORIS Jan 22, 2021
50156ed
Remove method to_data_frame and interface CanToDataFrame
IKupriyanov-HORIS Jan 25, 2021
8131764
WIP: update geocoding.md
IKupriyanov-HORIS Jan 26, 2021
1917b39
WIP: update geocoding.md
IKupriyanov-HORIS Jan 26, 2021
a908666
Revert changes to builder.ipynb
IKupriyanov-HORIS Jan 26, 2021
ff331eb
WIP: update geocoding.md
IKupriyanov-HORIS Jan 26, 2021
b6fa9b4
Use geocoding level instead of 'request' for a column name, remove da…
IKupriyanov-HORIS Jan 28, 2021
851fa40
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Jan 28, 2021
83002eb
Support Geocoder in ggplot(data=...)
IKupriyanov-HORIS Jan 29, 2021
99bd3c3
Switch to the new geocoding server
IKupriyanov-HORIS Jan 29, 2021
a203c3b
Merge branch 'master' into geoservices-1.1.0
IKupriyanov-HORIS Jan 29, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Unit tests for new geocoding API
  • Loading branch information
IKupriyanov-HORIS committed Oct 28, 2020
commit f44d979137682b6e747b2db724e1b379d7863f2e
182 changes: 173 additions & 9 deletions python-package/lets_plot/geo_data/new_api.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,190 @@
# Copyright (c) 2020. JetBrains s.r.o.
# Use of this source code is governed by the MIT license that can be found in the LICENSE file.
from typing import Any, Union, List, Optional
from typing import Any, Union, List, Optional, Dict
from collections import namedtuple

import numpy as np
from pandas import Series

from .gis.geocoding_service import GeocodingService
from .gis.geometry import GeoPoint
from .gis.request import RequestBuilder, RequestKind, MapRegion, MapRegionKind
from .gis.request import RequestBuilder, Request, GeocodingRequest, RequestKind, MapRegion, MapRegionKind, AmbiguityResolver, RegionQuery, \
LevelKind, IgnoringStrategyKind
from .gis.response import Response, SuccessResponse
from .regions import Regions, _raise_exception, _to_level_kind, _to_scope
from .regions_builder import RegionsBuilder
from .regions import Regions, _raise_exception, _to_level_kind, _to_scope, _make_parent_region
from .regions_builder import RegionsBuilder, NAMESAKE_MAX_COUNT
from .type_assertion import assert_list_type
from .regions import _to_level_kind, request_types, parent_types, scope_types, Regions, _raise_exception, \
_ensure_is_list

__all__ = [
'regions_builder2'
]

def _prepare_new_scope(scope) -> List[MapRegion]:
QuerySpec = namedtuple('QuerySpec', 'name, county, state, country')
WithinSpec = namedtuple('WithinSpec', 'scope, polygon')

def _get_or_none(list, index):
if index >= len(list):
return None
return list[index]


def _ensure_is_parent_list(obj):
if obj is None:
return None

if isinstance(obj, str):
return [obj]
if isinstance(obj, Regions):
return obj.as_list()

if isinstance(obj, list):
return obj

return [obj]




class RegionsBuilder2:
def __init__(self,
level: Optional[Union[str, LevelKind]] = None,
request: request_types = None,
scope: scope_types = None,
highlights: bool = False,
allow_ambiguous=False
):

self._level: Optional[LevelKind] = _to_level_kind(level)
self._default_ambiguity_resolver: AmbiguityResolver = AmbiguityResolver.empty() # TODO rename to geohint
self._highlights: bool = highlights
self._allow_ambiguous = allow_ambiguous
self._countries: List[Optional[MapRegion]] = []
self._states: List[Optional[MapRegion]] = []
self._counties: List[Optional[MapRegion]] = []
self._overridings: Dict[QuerySpec, WhereSpec] = {} # query to scope

requests: Optional[List[str]] = _ensure_is_list(request)

self._names: List[Optional[str]] = list(map(lambda name: name if requests is not None else None, requests))
self._scope: List[Optional[MapRegion]] = _prepare_new_scope(scope)

def countries(self, countries) -> 'RegionsBuilder2':
self._countries = self._make_parents(countries, 'countries')
return self

def states(self, states) -> 'RegionsBuilder2':
self._states = self._make_parents(states, 'states')
return self

def counties(self, counties) -> 'RegionsBuilder2':
self._counties = self._make_parents(counties, 'counties')
return self

def drop_not_found(self) -> 'RegionsBuilder2':
self._default_ambiguity_resolver = AmbiguityResolver(IgnoringStrategyKind.skip_missing)
return self

def drop_not_matched(self) -> 'RegionsBuilder2':
self._default_ambiguity_resolver = AmbiguityResolver(IgnoringStrategyKind.skip_all)
return self

def allow_ambiguous(self) -> 'RegionsBuilder2':
self._default_ambiguity_resolver = AmbiguityResolver(IgnoringStrategyKind.take_namesakes)
self._allow_ambiguous = True
return self

def where(self, name: str,
county: Optional[parent_types]=None,
state: Optional[parent_types]=None,
country: Optional[parent_types]=None,
scope: scope_types=None):
new_scope: List[MapRegion] = _prepare_new_scope(scope)
if len(new_scope) != 1:
raise ValueError('Scope for where should have length of 1, but was {}'.format(len(new_scope)))

county_region = _make_parent_region(county)
state_region = _make_parent_region(state)
country_region = _make_parent_region(country)

self._overridings[QuerySpec(name, county_region, state_region, country_region)] = WithinSpec(new_scope[0], AmbiguityResolver.empty())
return self

def _build_request(self) -> GeocodingRequest:
queries = []
for i in range(len(self._names)):
name = self._names[i]
country = _get_or_none(self._countries, i)
state = _get_or_none(self._states, i)
county = _get_or_none(self._counties, i)

scope, ambiguity_resolver = self._overridings.get(QuerySpec(name, county, state, country),
WithinSpec(None, self._default_ambiguity_resolver))

query = RegionQuery(
request=name,
country=country,
state=state,
county=county,
scope=scope,
ambiguity_resolver=ambiguity_resolver
)

queries.append(query)

request = RequestBuilder() \
.set_request_kind(RequestKind.geocoding) \
.set_requested_payload([PayloadKind.highlights] if self._highlights else []) \
.set_queries(queries) \
.set_scope(self._scope) \
.set_level(self._level) \
.set_namesake_limit(NAMESAKE_MAX_COUNT) \
.set_allow_ambiguous(self._allow_ambiguous) \
.build()

return request

def build(self) -> Regions:
request: GeocodingRequest = self._build_request()

response: Response = GeocodingService().do_request(request)

if not isinstance(response, SuccessResponse):
_raise_exception(response)

return Regions(response.level, response.answers, request.region_queries, self._highlights)

def _make_parents(self, values, kind) -> List[Optional[MapRegion]]:
values = _ensure_is_parent_list(values)

if values is None:
return []

if values is not None and len(values) != len(self._names):
raise ValueError('{} count({}) != names count({})'.format(kind, len(values), len(self._names)))

return list(map(lambda v: _make_parent_region(v) if values is not None else None, values))

def __eq__(self, o):
return isinstance(o, RegionsBuilder2) \
and self._overridings == o._overridings

def __ne__(self, o):
return not self == o


def _prepare_new_scope(scope: Optional[Union[str, Regions, MapRegion, List]]) -> List[MapRegion]:
def obj_to_map_region(obj) -> List[MapRegion]:
if isinstance(obj, str):
return [MapRegion.with_name(obj)]
if isinstance(obj, Regions):
return obj.to_map_regions()
if isinstance(obj, MapRegion):
if scope.kind == MapRegionKind.id:
return [MapRegion.scope([id]) for id in obj.values] # flat_map ids
return [MapRegion.scope([id]) for id in obj.values] # flat_map ids
else:
assert len(obj.values) == 1 # only id have more than one value
assert len(obj.values) == 1 # only id have more than one value
return [obj]

if scope is None:
Expand All @@ -43,7 +200,8 @@ def obj_to_map_region(obj) -> List[MapRegion]:
return flatten_scope


def regions_builder2(level=None, names=None, countries=None, states=None, counties=None, scope=None, highlights=False) -> RegionsBuilder:
def regions_builder2(level=None, names=None, countries=None, states=None, counties=None, scope=None,
highlights=False) -> RegionsBuilder2:
"""
Create a RegionBuilder class by level and request. Allows to refine ambiguous request with
where method. build() method creates Regions object or shows details for ambiguous result.
Expand Down Expand Up @@ -85,6 +243,11 @@ def regions_builder2(level=None, names=None, countries=None, states=None, counti

new_scope = _prepare_new_scope(scope)

return RegionsBuilder2(level, names, scope, highlights, allow_ambiguous=False)\
.countries(countries) \
.states(states) \
.counties(counties)

return RegionsBuilder(level, names, scope, highlights,
allow_ambiguous=False,
countries=countries,
Expand All @@ -93,6 +256,7 @@ def regions_builder2(level=None, names=None, countries=None, states=None, counti
new_api=True,
new_scope=new_scope)


def regions2(level=None, names=None, countries=None, states=None, counties=None, scope=None) -> Regions:
"""
Returns regions object.
Expand All @@ -116,4 +280,4 @@ def regions2(level=None, names=None, countries=None, states=None, counties=None,
If all parents are set (including countries) then the scope parameter is ignored.
If scope is an array then geocoding will try to search objects in all scopes.
"""
return regions_builder2(level, names, countries, states, counties, scope).build()
return regions_builder2(level, names, countries, states, counties, scope).build()
29 changes: 17 additions & 12 deletions python-package/lets_plot/geo_data/regions_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,14 @@ def __init__(self,
new_scope: List[MapRegion]=[]
):

self._new_api: bool = new_api
self._level: Optional[LevelKind] = _to_level_kind(level)
self._default_ambiguity_resolver: AmbiguityResolver = AmbiguityResolver.empty() # TODO rename to geohint
self._highlights: bool = highlights
self._allow_ambiguous = allow_ambiguous
self._overridings: List[RegionQuery] = []

if new_api:
if self._new_api:
self._scope: List[MapRegion] = new_scope
self._queries: List[RegionQuery] = _create_new_queries(request, self._default_ambiguity_resolver, countries, states, counties)
else:
Expand All @@ -199,7 +200,11 @@ def allow_ambiguous(self) -> 'RegionsBuilder':
def where(self,
request: request_types = None,
within: Optional[Union[str, List[str], Regions, List[Regions], ShapelyPolygonType]] = None,
near: Optional[Union[Regions, ShapelyPointType]] = None) -> 'RegionsBuilder':
near: Optional[Union[Regions, ShapelyPointType]] = None,
country: Optional[str] = None,
state: Optional[str] = None,
county: Optional[str] = None,
) -> 'RegionsBuilder':
"""
If request is not exist - append it to a list with specified scope.
If request is already exist in the list - specify scope exactly for that request.
Expand Down Expand Up @@ -236,19 +241,19 @@ def where(self,
"""

scope, box = _split(within)
if self._new_api:
if scope is not None:
raise ValueError('Parameter scope is not available in new version of where function')
else:
ambiguity_resolver = AmbiguityResolver(None, _to_near_coord(near), box)

ambiguity_resolver = AmbiguityResolver(
None,
_to_near_coord(near),
box
)
new_overridings = _create_queries(request, scope, ambiguity_resolver)
for overriding in self._overridings:
if overriding.request in set([overriding.request for overriding in new_overridings]):
self._overridings.remove(overriding)

new_overridings = _create_queries(request, scope, ambiguity_resolver)
for overriding in self._overridings:
if overriding.request in set([overriding.request for overriding in new_overridings]):
self._overridings.remove(overriding)
self._overridings.extend(new_overridings)

self._overridings.extend(new_overridings)
return self

def build(self) -> Regions:
Expand Down
88 changes: 88 additions & 0 deletions python-package/test/geo_data/request_assertion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Copyright (c) 2020. JetBrains s.r.o.
# Use of this source code is governed by the MIT license that can be found in the LICENSE file.
from typing import TypeVar, Generic, Optional

from lets_plot.geo_data.gis.request import Request, GeocodingRequest, RegionQuery, MapRegion, AmbiguityResolver

T = TypeVar('T')

class ValueMatcher(Generic[T]):
def check(self, value):
raise ValueError('abstract')

class any(ValueMatcher[T]):
def check(self, value):
return

class eq(ValueMatcher[T]):
def __init__(self, v):
self.expected = v

def check(self, value):
assert self.expected == value, '{} != {}'.format(self.expected, value)

class eq_map_region(eq):
def __init__(self, v):
self.expected = MapRegion.with_name(v)


class empty(ValueMatcher[T]):
def check(self, value):
assert value is None, '{} is not None'.format(value)

class RegionQueryMatcher:
def __init__(self,
request: ValueMatcher[Optional[str]] = any(),
scope: ValueMatcher[Optional[MapRegion]] = any(),
ambiguity_resolver: ValueMatcher[AmbiguityResolver] = any(),
country: ValueMatcher[Optional[MapRegion]] = any(),
state: ValueMatcher[Optional[MapRegion]] = any(),
county: ValueMatcher[Optional[MapRegion]] = any()
):
self._request: ValueMatcher[Optional[str]] = request
self._scope: ValueMatcher[Optional[MapRegion]] = scope
self._ambiguity_resolver: ValueMatcher[AmbiguityResolver] = ambiguity_resolver
self._country: ValueMatcher[Optional[MapRegion]] = country
self._state: ValueMatcher[Optional[MapRegion]] = state
self._county: ValueMatcher[Optional[MapRegion]] = county

def request(self, request: ValueMatcher[Optional[str]]) -> 'RegionQueryMatcher':
self._request = request
return self

def scope(self, scope: ValueMatcher[Optional[MapRegion]]) -> 'RegionQueryMatcher':
self._scope = scope
return self

def ambiguity_resolver(self, ambiguity_resolver: ValueMatcher[AmbiguityResolver]) -> 'RegionQueryMatcher':
self._ambiguity_resolver = ambiguity_resolver
return self

def country(self, country: ValueMatcher[Optional[MapRegion]]) -> 'RegionQueryMatcher':
self._country: ValueMatcher[Optional[MapRegion]]
return self

def state(self, state: ValueMatcher[Optional[MapRegion]]) -> 'RegionQueryMatcher':
self._state = state
return self

def county(self, county: ValueMatcher[Optional[MapRegion]]) -> 'RegionQueryMatcher':
self._county = county
return self

def check(self, q: RegionQuery):
self._request.check(q.request)
self._scope.check(q.scope)
self._ambiguity_resolver.check(q.ambiguity_resolver)
self._country.check(q.country)
self._state.check(q.state)
self._county.check(q.county)

class GeocodingRequestAssertion:
def __init__(self, request: Request):
assert isinstance(request, GeocodingRequest)
self._request: GeocodingRequest = request

def has_query(self, i: int, query_matcher: RegionQueryMatcher) -> 'GeocodingRequestAssertion':
query_matcher.check(self._request.region_queries[i])
return self
5 changes: 5 additions & 0 deletions python-package/test/geo_data/test_integration_new_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,8 @@ def test_simple_scope():
florida_with_scope = geodata.regions_builder2('state', names=['florida'], scope='Uruguay').build().to_data_frame()

assert florida_with_country[DF_ID][0] == florida_with_scope[DF_ID][0]


def test_where():
geodata.regions_builder2('city', names='warwick')\
.where('warwick', scope='oklahoma').build()
Loading