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
WIP: answers in protocol
  • Loading branch information
IKupriyanov-HORIS committed Oct 14, 2020
commit a37a3f57b5dd9d4dd094df3cf45af17358a44585
6 changes: 5 additions & 1 deletion python-package/lets_plot/export/simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from os.path import abspath
from typing import Union

from .. import _kbridge as kbr
from .._global_settings import is_production
from .._version import __version__
from ..plot.core import PlotSpec
Expand All @@ -32,6 +31,8 @@ def export_svg(plot: Union[PlotSpec, GGBunch], filename: str) -> str:
if not (isinstance(plot, PlotSpec) or isinstance(plot, GGBunch)):
raise ValueError("PlotSpec or GGBunch expected but was: {}".format(type(plot)))

from .. import _kbridge as kbr

svg = kbr._generate_svg(plot.as_dict())
with io.open(filename, mode="w", encoding="utf-8") as f:
f.write(svg)
Expand Down Expand Up @@ -62,6 +63,9 @@ def export_html(plot: Union[PlotSpec, GGBunch], filename: str, iframe: bool = Fa
raise ValueError("PlotSpec or GGBunch expected but was: {}".format(type(plot)))

version = __version__ if is_production() else "latest"

from .. import _kbridge as kbr

html_page = kbr._generate_static_html_page(plot.as_dict(), version, iframe)
with io.open(filename, mode="w", encoding="utf-8") as f:
f.write(html_page)
Expand Down
72 changes: 44 additions & 28 deletions python-package/lets_plot/geo_data/gis/json_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@
from .geometry import Ring
from .response import Multipolygon, GeoPoint, GeoRect, Boundary, Polygon
from .response import Response, ResponseBuilder, SuccessResponse, AmbiguousResponse
from .response import Status, LevelKind, GeocodedFeature, AmbiguousFeature, Namesake, NamesakeParent, FeatureBuilder
from .response import Status, LevelKind, Answer, GeocodedFeature, AmbiguousFeature, Namesake, NamesakeParent, FeatureBuilder


class ResponseField(Enum):
status = 'status'
message = 'message'
data = 'data'
answers = 'answers'
features = 'features'
geocoded_data = 'good_features'
incorrect_data = 'bad_features'
Expand Down Expand Up @@ -66,7 +67,7 @@ def parse(response_json: Dict) -> Response:
.visit_enum_existing(ResponseField.level, LevelKind, response.set_level)

if response.status == Status.success:
data_dict.visit(ResponseField.features, partial(ResponseParser._parse_geocoded_features, response=response))
data_dict.visit(ResponseField.answers, partial(ResponseParser._parse_answers, response=response))
elif response.status == Status.ambiguous:
data_dict.visit(ResponseField.features, partial(ResponseParser._parse_ambiguous_features, response=response))
else:
Expand All @@ -75,23 +76,28 @@ def parse(response_json: Dict) -> Response:
return response.build()

@staticmethod
def _parse_geocoded_features(features_json: List[Dict], response: ResponseBuilder):
geocoded_features: List[GeocodedFeature] = []
for feature_json in features_json:
feature = FeatureBuilder()
FluentDict(feature_json) \
.visit_str(ResponseField.query, feature.set_query) \
.visit_str(ResponseField.geo_object_id, feature.set_id) \
.visit_str(ResponseField.name, feature.set_name) \
.visit_str_list_optional(ResponseField.highlights, feature.set_highlights) \
.visit_str_existing(ResponseField.boundary, lambda json: feature.set_boundary(GeoJson().parse_geometry(json))) \
.visit_object_optional(ResponseField.centroid, lambda json: feature.set_centroid(ResponseParser._parse_point(json))) \
.visit_object_optional(ResponseField.limit, lambda json: feature.set_limit(ResponseParser._parse_rect(json))) \
.visit_object_optional(ResponseField.position, lambda json: feature.set_position(ResponseParser._parse_rect(json)))

geocoded_features.append(feature.build_geocoded())

response.set_geocoded_features(geocoded_features)
def _parse_answers(answers_json: List[Dict], response: ResponseBuilder):
answers: List[Answer] = []
for answer_json in answers_json:
query = answer_json.get(ResponseField.query.value)
features_json = answer_json.get(ResponseField.features.value, [])
geocoded_features: List[GeocodedFeature] = []
for feature_json in features_json:
feature = FeatureBuilder().set_query(query)

FluentDict(feature_json) \
.visit_str(ResponseField.geo_object_id, feature.set_id) \
.visit_str(ResponseField.name, feature.set_name) \
.visit_str_list_optional(ResponseField.highlights, feature.set_highlights) \
.visit_str_existing(ResponseField.boundary, lambda json: feature.set_boundary(GeoJson().parse_geometry(json))) \
.visit_object_optional(ResponseField.centroid, lambda json: feature.set_centroid(ResponseParser._parse_point(json))) \
.visit_object_optional(ResponseField.limit, lambda json: feature.set_limit(ResponseParser._parse_rect(json))) \
.visit_object_optional(ResponseField.position, lambda json: feature.set_position(ResponseParser._parse_rect(json)))

geocoded_features.append(feature.build_geocoded())
answers.append(Answer(query, geocoded_features))

response.set_answers(answers)

@staticmethod
def _parse_ambiguous_features(features_json: List[Dict], response: ResponseBuilder):
Expand Down Expand Up @@ -146,7 +152,7 @@ def format(response: Response) -> Dict:
.put(ResponseField.message, response.message) \
.put(ResponseField.data, FluentDict()
.put(ResponseField.level, response.level.value)
.put(ResponseField.features, list(map(ResponseFormatter._format_geocoded_feature, response.features)))) \
.put(ResponseField.answers, list(map(ResponseFormatter._format_answer, response.answers)))) \
.to_dict()
elif isinstance(response, AmbiguousResponse):
return FluentDict() \
Expand All @@ -158,17 +164,27 @@ def format(response: Response) -> Dict:
.to_dict()

@staticmethod
def _format_geocoded_feature(feature: GeocodedFeature) -> Dict:
def _format_answer(answer: Answer) -> Dict:
features = []
for feature in answer.features:
features.append(
FluentDict() \
.put(ResponseField.query, feature.query) \
.put(ResponseField.geo_object_id, feature.id) \
.put(ResponseField.name, feature.name) \
.put(ResponseField.boundary, ResponseFormatter._format_boundary(feature.boundary)) \
.put(ResponseField.centroid, ResponseFormatter._format_centroid(feature.centroid)) \
.put(ResponseField.limit, ResponseFormatter._format_rect(feature.limit)) \
.put(ResponseField.position, ResponseFormatter._format_rect(feature.position)) \
.to_dict()
)

return FluentDict() \
.put(ResponseField.query, feature.query) \
.put(ResponseField.geo_object_id, feature.id) \
.put(ResponseField.name, feature.name) \
.put(ResponseField.boundary, ResponseFormatter._format_boundary(feature.boundary)) \
.put(ResponseField.centroid, ResponseFormatter._format_centroid(feature.centroid)) \
.put(ResponseField.limit, ResponseFormatter._format_rect(feature.limit)) \
.put(ResponseField.position, ResponseFormatter._format_rect(feature.position)) \
.put(ResponseField.query, answer.query) \
.put(ResponseField.features, features) \
.to_dict()


@staticmethod
def _format_centroid(point: Optional[GeoPoint]) -> Optional[Dict]:
if point is None:
Expand Down
35 changes: 29 additions & 6 deletions python-package/lets_plot/geo_data/gis/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,30 @@ def __init__(self, message: str):
assert_type(message, str)
self.message: str = message

class Answer:
def __init__(self, query: str, features: List[GeocodedFeature]):
assert_type(query, str)
assert_list_type(features, GeocodedFeature)

self.query: str = query
self.features: List[GeocodedFeature] = features


class SuccessResponse(Response):
def __init__(self, message: str, level: LevelKind, features: List[GeocodedFeature]):
def __init__(self, message: str, level: LevelKind, answers: List[Answer]):
super().__init__(message)

assert_type(message, str)
assert_optional_type(level, LevelKind)
assert_list_type(features, GeocodedFeature)
assert_list_type(answers, Answer)

self.level: LevelKind = level
self.answers: List[Answer] = answers

features = []
for answer in answers:
features.extend(answer.features)

self.features: List[GeocodedFeature] = features


Expand Down Expand Up @@ -187,7 +201,7 @@ def __init__(self):
self.status: Status = None
self.level: LevelKind = None
self.message: str = None
self.geocoded_features: List[GeocodedFeature] = None
self.answers: List[Answer] = None
self.ambiguous_features: List[AmbiguousFeature] = None
self.data: Dict = None

Expand All @@ -211,16 +225,25 @@ def set_ambiguous_features(self, v: List[AmbiguousFeature]) -> 'ResponseBuilder'
self.ambiguous_features = v
return self

def set_geocoded_features(self, v: List[GeocodedFeature]) -> 'ResponseBuilder':
def set_answers(self, v: List[Answer]) -> 'ResponseBuilder':
assert_list_type(v, Answer)
self.answers = v
return self

def set_geocoded_features(self, v: List[GeocodedFeature]):
'''
Exactly matching non-exploding features, i.e. one feature per answer
'''
assert_list_type(v, GeocodedFeature)
self.geocoded_features = v
self.answers = [Answer(f.query, [f]) for f in v]
return self


def build(self) -> Response:
if self.status == Status.error:
return ErrorResponse(self.message)
elif self.status == Status.success:
return SuccessResponse(self.message, self.level, self.geocoded_features)
return SuccessResponse(self.message, self.level, self.answers)
elif self.status == Status.ambiguous:
return AmbiguousResponse(self.message, self.level, self.ambiguous_features)
else:
Expand Down
36 changes: 28 additions & 8 deletions python-package/lets_plot/geo_data/regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,21 @@ def select_not_empty_name(feature: GeocodedFeature) -> str:
return feature.name if feature.query is None or feature.query == '' else feature.query


def arrange_queries(features: List[GeocodedFeature], queries: List[RegionQuery]) -> List[Optional[RegionQuery]]:
res = []
for feature in features:
request: Optional[RegionQuery] = None

for query in queries:
if query.request == feature.query:
request = query
break

res.append(request)

return res


class PlacesDataFrameBuilder:
def __init__(self):
self._request: List[str] = []
Expand All @@ -57,16 +72,16 @@ def __init__(self):
self._state: List[Optional[str]] = []
self._country: List[Optional[str]] = []

def append_row(self, request: str, found_name: str, queries: Optional[List[RegionQuery]], parent_row: int):
def append_row(self, request: str, found_name: str, queries: List[Optional[RegionQuery]], parent_row: int):
self._request.append(request)
self._found_name.append(found_name)

if queries is None or len(queries) == 0:
self._county.append(None)
self._state.append(None)
self._country.append(None)
query: Optional[RegionQuery] = queries[parent_row]
if query is None:
self._county.append(MapRegion.name_or_none(None))
self._state.append(MapRegion.name_or_none(None))
self._country.append(MapRegion.name_or_none(None))
else:
query: RegionQuery = queries[parent_row]
self._county.append(MapRegion.name_or_none(query.county))
self._state.append(MapRegion.name_or_none(query.state))
self._country.append(MapRegion.name_or_none(query.country))
Expand Down Expand Up @@ -252,7 +267,7 @@ def to_data_frame(self) -> DataFrame:
data[DF_ID] = [feature.id for feature in self._geocoded_features]

# for us-48 queries doesnt' count
queries = self._queries if len(self._queries) == len(self._geocoded_features) else None
queries: List[Optional[RegionQuery]] = arrange_queries(self._geocoded_features, self._queries)

for i in range(len(self._geocoded_features)):
feature = self._geocoded_features[i]
Expand All @@ -272,7 +287,12 @@ def _execute(self, request_builder: RequestBuilder, df_converter):
if not isinstance(response, SuccessResponse):
_raise_exception(response)

self._join_payload(response.features)
features = []

for a in response.answers:
features.extend(a.features)

self._join_payload(features)

return df_converter.to_data_frame(self._geocoded_features, self._queries)

Expand Down
8 changes: 4 additions & 4 deletions python-package/lets_plot/geo_data/to_geo_data_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pandas import DataFrame
from shapely.geometry import box

from lets_plot.geo_data import PlacesDataFrameBuilder, select_not_empty_name, DF_REQUEST, DF_FOUND_NAME, abstractmethod
from lets_plot.geo_data import PlacesDataFrameBuilder, arrange_queries, select_not_empty_name, DF_REQUEST, DF_FOUND_NAME, abstractmethod
from lets_plot.geo_data.gis.response import GeocodedFeature, GeoRect, Boundary, Multipolygon, Polygon, GeoPoint
from lets_plot.geo_data.gis.request import RegionQuery

Expand Down Expand Up @@ -42,7 +42,7 @@ def __init__(self):

def to_data_frame(self, features: List[GeocodedFeature], queries: List[RegionQuery] = []) -> DataFrame:
places = PlacesDataFrameBuilder()
queries = queries if len(queries) == len(features) else None
queries: List[Optional[RegionQuery]] = arrange_queries(features, queries)

for i in range(len(features)):
feature = features[i]
Expand Down Expand Up @@ -81,7 +81,7 @@ def __init__(self):

def to_data_frame(self, features: List[GeocodedFeature], queries: List[RegionQuery] = []) -> DataFrame:
places = PlacesDataFrameBuilder()
queries = queries if len(queries) == len(features) else None
queries: List[Optional[RegionQuery]] = arrange_queries(features, queries)

for i in range(len(features)):
feature = features[i]
Expand All @@ -99,7 +99,7 @@ def __init__(self):

def to_data_frame(self, features: List[GeocodedFeature], queries: List[RegionQuery] = []) -> DataFrame:
places = PlacesDataFrameBuilder()
queries = queries if len(queries) == len(features) else None
queries: List[Optional[RegionQuery]] = arrange_queries(features, queries)

geometry = []
for i in range(len(features)):
Expand Down
2 changes: 1 addition & 1 deletion python-package/test/geo_data/geo_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def assert_str(column, expected):

if isinstance(expected, list):
actual = df[column][index:index + len(expected)].tolist()
assert actual == expected
assert actual == expected, str(expected) + '!=' + str(actual)
return

raise ValueError('Not support type of expected: {}'.format(str(type(expected))))
Expand Down
6 changes: 3 additions & 3 deletions python-package/test/geo_data/gis/test_response_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ def test_valid_success_response():

assert isinstance(response, SuccessResponse)
assert 'OK' == response.message
assert 2 == len(response.features)
assert_geocoded(foo, response.features[0])
assert_geocoded(foofoo, response.features[1])
assert 2 == len(response.answers)
assert_geocoded(foo, response.answers[0].features[0])
assert_geocoded(foofoo, response.answers[1].features[0])


def test_ambiguous_response():
Expand Down
Loading