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
Remove chunked requests, better docs for new API
  • Loading branch information
IKupriyanov-HORIS committed Oct 20, 2020
commit f6fc7c8107916cbc9b60424f485cd3c192d1ce2a
60 changes: 2 additions & 58 deletions python-package/lets_plot/geo_data/gis/geocoding_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,64 +12,8 @@


class GeocodingService:
def do_request(self, request: Request, chunk_size=None, progress_callback=None) -> Response:
# level autodetection can work only with whole request
if chunk_size is not None and isinstance(request, GeocodingRequest) and request.level is not None:
return self._execute_chunked(request, chunk_size, progress_callback)
else:
return self._execute(request)

def _execute_chunked(self, request: GeocodingRequest, chunk_size, progress_callback) -> Response:
success_chunks = []
ambiguous_chunks = []

def chunked(items):
for i in range(0, len(items), chunk_size):
yield items[i:i + chunk_size]

total_count = len(request.region_queries)
i = 0
if progress_callback:
progress_callback(i, total_count)

for q in chunked(request.region_queries):
chunked_request = GeocodingRequest(
requested_payload=request.requested_payload,
resolution=request.resolution,
region_queries=q,
level=request.level,
namesake_example_limit=request.namesake_example_limit,
allow_ambiguous=request.allow_ambiguous
)

response = self._execute(chunked_request)
if progress_callback:
i = i + len(q)
progress_callback(i, total_count)

if isinstance(response, ErrorResponse):
return response
elif isinstance(response, SuccessResponse):
success_chunks.append(response)
elif isinstance(response, AmbiguousResponse):
ambiguous_chunks.append(response)
else:
raise ValueError('Unknown response type: ' + type(response).__name__)

# combine ambiguous features from all chunks
if ambiguous_chunks:
ambiguous_features = []
for response in ambiguous_chunks:
ambiguous_features.extend(response.features)

return AmbiguousResponse(ambiguous_chunks[0].message, request.level, ambiguous_features)

# no errors or ambiguous responses - combine success features from all chunks
success_features = []
for response in success_chunks:
success_features.extend(response.features)

return SuccessResponse(success_chunks[0].message, request.level, success_features)
def do_request(self, request: Request) -> Response:
return self._execute(request)

def _execute(self, request: Request) -> Response:
if not has_global_value(GEOCODING_PROVIDER_URL):
Expand Down
23 changes: 10 additions & 13 deletions python-package/lets_plot/geo_data/new_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,19 @@ def regions_builder2(level=None, names=None, scope=None, countries=None, states=
level : ['country' | 'state' | 'county' | 'city' | None]
The level of administrative division. Default is a 'state'.
names : [array | string | None]
Data can be filtered by full names at any level (only exact matching).
Names of objects to be geocoded.
For 'state' level:
-'US-48' returns continental part of United States (48 states) in a compact form.
countries : [array | string | None]
Parent countries. Should have same size as names.
states : [array | string | None]
Parent states. Should have same size as names.
counties : [array | string | None]
Parent counties. Should have same size as names.
countries : [array | None]
Parent countries. Should have same size as names. Can contain strings or Regions objects.
states : [array | None]
Parent states. Should have same size as names. Can contain strings or Regions objects.
counties : [array | None]
Parent counties. Should have same size as names. Can contain strings or Regions objects.
scope : [array | string | Regions | None]
Data can be filtered by within name.
If within is array then request and within will be merged positionally (size should be equal).
If within is Regions then request will be searched in any of these regions.
'US-48' includes continental part of United States (48 states).
Limits area of geocoding. Applyed to a highest admin level of parents that are set or to names, if no parents given.
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.

Returns
-------
Expand All @@ -58,8 +57,6 @@ def regions_builder2(level=None, names=None, scope=None, countries=None, states=
>>> r = regions_builder(level='city', request=['moscow', 'york']).where('york', regions_state('New York')).build()
"""
return RegionsBuilder(level, names, scope, highlights,
progress_callback=None,
chunk_size=None,
allow_ambiguous=False,
countries=countries,
states=states,
Expand Down
15 changes: 8 additions & 7 deletions python-package/lets_plot/geo_data/regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,11 @@ class Resolution(enum.Enum):
def contains_values(column):
return any(v is not None for v in column)


def select_request(query: RegionQuery, answer: Answer, feature: GeocodedFeature) -> str:
return query.request if len(answer.features) <= 1 else feature.name


def zip_answers(queries: List, answers: List):
if len(queries) > 0:
return zip(queries, answers)
Expand Down Expand Up @@ -76,7 +78,6 @@ def append_row(self, request: str, found_name: str, query: Optional[RegionQuery]
self._state.append(MapRegion.name_or_none(query.state))
self._country.append(MapRegion.name_or_none(query.country))


def build_dict(self):
data = {}
data[DF_REQUEST] = self._request
Expand All @@ -93,14 +94,14 @@ def build_dict(self):

return data


@abstractmethod
def to_data_frame(self, answers: List[Answer], queries: List[RegionQuery] = []) -> DataFrame:
raise ValueError('Not implemented')


class Regions(CanToDataFrame):
def __init__(self, level_kind: LevelKind, answers: List[Answer], queries: List[RegionQuery], highlights: bool = False):
def __init__(self, level_kind: LevelKind, answers: List[Answer], queries: List[RegionQuery],
highlights: bool = False):
assert_list_type(answers, Answer)
assert_list_type(queries, RegionQuery)
assert len(answers) == len(queries)
Expand Down Expand Up @@ -136,11 +137,12 @@ def to_map_regions(self):

def as_list(self) -> List['Regions']:
if len(self._queries) == 0:
return [Regions(self._level_kind, [answer], [RegionQuery(request=None)], self._highlights) for answer in self._answers]
return [Regions(self._level_kind, [answer], [RegionQuery(request=None)], self._highlights) for answer in
self._answers]

assert len(self._queries) == len(self._answers)
return [Regions(self._level_kind, [answer], [query], self._highlights) for query, answer in zip(self._queries, self._answers)]

return [Regions(self._level_kind, [answer], [query], self._highlights) for query, answer in
zip(self._queries, self._answers)]

def unique_ids(self) -> List[str]:
seen = set()
Expand Down Expand Up @@ -287,7 +289,6 @@ def to_data_frame(self) -> DataFrame:

return DataFrame(data)


def _execute(self, request_builder: RequestBuilder, df_converter):
response = GeocodingService().do_request(request_builder.build())

Expand Down
41 changes: 15 additions & 26 deletions python-package/lets_plot/geo_data/regions_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,23 @@ def _to_near_coord(near: Optional[Union[Regions, ShapelyPointType]]) -> Optional
else:
raise ValueError("Unexpected geocoding response for id " + str(near_id[0]))

if ShapelyWrapper.is_point(near):
if LazyShapely.is_point(near):
return GeoPoint(lon=near.x, lat=near.y)

raise ValueError('Not supported type')


def _split(box: Optional[Union[str, List[str], Regions, List[Regions], ShapelyPolygonType]]) -> Tuple[scope_types, Optional[GeoRect]]:
if not ShapelyWrapper.is_polygon(box):
def _split(box: Optional[Union[str, List[str], Regions, List[Regions], ShapelyPolygonType]]) -> Tuple[
scope_types, Optional[GeoRect]]:
if not LazyShapely.is_polygon(box):
return box, None

return None, GeoRect(min_lon=box.bounds[0], min_lat=box.bounds[1], max_lon=box.bounds[2], max_lat=box.bounds[3])


def _create_queries(request: request_types, scope: scope_types, ambiguity_resovler: AmbiguityResolver,
countries: parent_types = None, states: parent_types = None, counties: parent_types = None) -> List[RegionQuery]:
countries: parent_types = None, states: parent_types = None, counties: parent_types = None) -> List[
RegionQuery]:
requests: Optional[List[str]] = _ensure_is_list(request)

if (countries is None and states is None and counties is None) or requests is None:
Expand Down Expand Up @@ -93,7 +95,6 @@ def ensure_is_parent_list(obj):
states = ensure_is_parent_list(states)
counties = ensure_is_parent_list(counties)


if countries is not None and len(countries) != len(requests):
raise ValueError('Countries count({}) != names count({})'.format(len(countries), len(requests)))

Expand All @@ -118,25 +119,25 @@ def ensure_is_parent_list(obj):
return queries


class ShapelyWrapper:
class LazyShapely:
@staticmethod
def is_point(p) -> bool:
if not ShapelyWrapper.is_shapely_available():
if not LazyShapely._is_shapely_available():
return False

from shapely.geometry import Point
return isinstance(p, Point)

@staticmethod
def is_polygon(p):
if not ShapelyWrapper.is_shapely_available():
if not LazyShapely._is_shapely_available():
return False

from shapely.geometry import Polygon
return isinstance(p, Polygon)

@staticmethod
def is_shapely_available():
def _is_shapely_available():
try:
import shapely
return True
Expand All @@ -150,21 +151,18 @@ def __init__(self,
request: request_types = None,
scope: scope_types = None,
highlights: bool = False,
progress_callback = None,
chunk_size = None,
allow_ambiguous = False,
allow_ambiguous=False,
countries=None,
states=None,
counties=None
):

self._level: Optional[LevelKind] = _to_level_kind(level)
self._overridings: List[RegionQuery] = []
self._default_ambiguity_resolver: AmbiguityResolver = AmbiguityResolver.empty() # TODO rename to geohint
self._queries: List[RegionQuery] = _create_queries(request, scope, self._default_ambiguity_resolver, countries, states, counties)
self._default_ambiguity_resolver: AmbiguityResolver = AmbiguityResolver.empty() # TODO rename to geohint
self._queries: List[RegionQuery] = _create_queries(request, scope, self._default_ambiguity_resolver, countries,
states, counties)
self._highlights: bool = highlights
self._on_progress = progress_callback
self._chunk_size = chunk_size
self._allow_ambiguous = allow_ambiguous

def drop_not_found(self) -> 'RegionsBuilder':
Expand All @@ -180,11 +178,6 @@ def allow_ambiguous(self) -> 'RegionsBuilder':
self._allow_ambiguous = True
return self

def chunk_request(self, on_progress=None, chunk_size=40):
self._chunk_size = chunk_size
self._on_progress = on_progress
return self

def where(self,
request: request_types = None,
within: Optional[Union[str, List[str], Regions, List[Regions], ShapelyPolygonType]] = None,
Expand Down Expand Up @@ -251,11 +244,7 @@ def build(self) -> Regions:
.set_allow_ambiguous(self._allow_ambiguous) \
.build()

# Too many queries - can fail with timeout. Chunk queries.
if len(self._get_queries()) > 100_000 and self._chunk_size is None:
self.chunk_request(self._on_progress, 40)

response: Response = GeocodingService().do_request(request, self._chunk_size, self._on_progress)
response: Response = GeocodingService().do_request(request)

if not isinstance(response, SuccessResponse):
_raise_exception(response)
Expand Down
8 changes: 2 additions & 6 deletions python-package/test/geo_data/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ def test_regions(mock_geocoding):
level=LEVEL_KIND,
namesake_example_limit=NAMESAKES_EXAMPLE_LIMIT,
allow_ambiguous=False
),
None, # chunk_size
None # progress_callback
)
)


Expand All @@ -90,9 +88,7 @@ def test_regions_with_highlights(mock_geocoding):
level=LEVEL_KIND,
namesake_example_limit=NAMESAKES_EXAMPLE_LIMIT,
allow_ambiguous=False
),
None, # chunk_size
None # progress_callback
)
)

FOO_FEATURE = FeatureBuilder().set_name('fooname').set_id('fooid').build_geocoded()
Expand Down