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
Fix more tests
  • Loading branch information
IKupriyanov-HORIS committed Sep 25, 2020
commit 54b4457f937f5f0efea743e3a8f748fa62534772
Original file line number Diff line number Diff line change
Expand Up @@ -1942,7 +1942,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.8"
"version": "3.7.6"
}
},
"nbformat": 4,
Expand Down
1,073 changes: 959 additions & 114 deletions docs/examples/jupyter-notebooks-dev/map_US_household_income_new_ik.ipynb

Large diffs are not rendered by default.

157 changes: 68 additions & 89 deletions docs/examples/jupyter-notebooks/map_quickstart.ipynb

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion python-package/lets_plot/_global_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def _get_env_val(actual_name: str) -> Any:
'dev_offline': _init_value('dev_offline', True), # default: embed js into the notebook
'dev_js_base_url': "https://0.0.0.0:8080",
'dev_js_name': '', # default: lets-plot-<version>.js
'dev_geocoding_url': _init_value('dev_geocoding_url', 'https:https://geo.datalore.jetbrains.com')
'dev_geocoding_url': _init_value('dev_geocoding_url', 'http:https://localhost:3012')
}


Expand Down
2 changes: 1 addition & 1 deletion python-package/lets_plot/geo_data/gis/geocoding_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,5 +97,5 @@ def _execute(self, request: Request) -> Response:
except Exception as e:
return ResponseBuilder() \
.set_status(Status.error) \
.set_message('Geocoding service exception: {}'.format(str(e))) \
.set_message('Internal service exception: {}'.format(str(e))) \
.build()
10 changes: 9 additions & 1 deletion python-package/lets_plot/geo_data/gis/json_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from .fluent_dict import FluentDict, FluentList
from .geometry import GeoPoint
from .request import RegionQuery, MapRegion, PayloadKind, RegionQueryBuilder, IgnoringStrategyKind, MapRegionBuilder
from .request import RegionQuery, MapRegion, MapRegionKind, PayloadKind, RegionQueryBuilder, IgnoringStrategyKind, MapRegionBuilder
from .request import Request, GeocodingRequest, ExplicitRequest, RequestBuilder, RequestKind, ReverseGeocodingRequest
from .response import LevelKind, GeoRect

Expand Down Expand Up @@ -118,6 +118,14 @@ def _format_map_region(parent: Optional[MapRegion]) -> Optional[Dict]:
if parent is None:
return None

# special case - place is just a geocoded object with id and extra information, used by client
# server doesn't need this extra information
if parent.kind.value == 'place':
return FluentDict() \
.put(Field.map_region_kind, MapRegionKind.id.value) \
.put(Field.map_region_values, parent.values) \
.to_dict()

return FluentDict() \
.put(Field.map_region_kind, parent.kind.value) \
.put(Field.map_region_values, parent.values) \
Expand Down
21 changes: 16 additions & 5 deletions python-package/lets_plot/geo_data/gis/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,17 @@ class MapRegion:
with_name - single name, not yet geocoded.
'''
@staticmethod
def request_or_none(place: Optional['MapRegion']):
def name_or_none(place: Optional['MapRegion']):
if place is None:
return None

assert place.kind == MapRegionKind.place, 'Only palce MapRegion contains request'
return place._request
if place.kind == MapRegionKind.place:
return place.request()

if place.kind == MapRegionKind.name:
return place.name()

raise ValueError('MapRegion with kind \'{}\' doesn\'t have a name'.format(place.kind))


@staticmethod
Expand Down Expand Up @@ -94,10 +99,16 @@ def __init__(self, kind: MapRegionKind, values: List[str], request: Optional[str
self._level_kind: Optional[LevelKind] = level_kind
self._hash = hash((self.values, self.kind))

def request(self) -> Optional[str]:
assert self.kind == MapRegionKind.place, 'Invalid MapRegion kind: only place contains request'
def request(self) -> str:
assert self.kind == MapRegionKind.place, 'Invalid MapRegion kind. Expected \'place\', but was ' + str(self.kind)
assert_type(self._request, str)
return self._request

def name(self) -> str:
assert self.kind == MapRegionKind.name, 'Invalid MapRegion kind. Expected \'name\', but was ' + str(self.kind)
assert_type(self.values[0], str)
return self.values[0]

def level_kind(self) -> Optional[LevelKind]:
assert self.kind == MapRegionKind.place, 'Invalid MapRegion kind: only place contains level_kind'
return self._level_kind
Expand Down
6 changes: 3 additions & 3 deletions python-package/lets_plot/geo_data/regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ def append_row(self, request: str, found_name: str, queries: Optional[List[Regio
self._country.append(None)
else:
query: RegionQuery = queries[parent_row]
self._county.append(MapRegion.request_or_none(query.county))
self._state.append(MapRegion.request_or_none(query.state))
self._country.append(MapRegion.request_or_none(query.country))
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))


def build_dict(self):
Expand Down
22 changes: 18 additions & 4 deletions python-package/lets_plot/geo_data/regions_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,23 @@ def _create_queries(request: request_types, scope: scope_types, ambiguity_resovl

return [RegionQuery(r, scopes, ambiguity_resovler) for r in requests]
else:
countries = _ensure_is_list(countries)
states = _ensure_is_list(states)
counties = _ensure_is_list(counties)
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]

countries = ensure_is_parent_list(countries)
states = ensure_is_parent_list(states)
counties = ensure_is_parent_list(counties)

assert countries is None or len(countries) == len(requests)
assert states is None or len(states) == len(requests)
Expand Down Expand Up @@ -232,7 +246,7 @@ def build(self) -> Regions:
.build()

# Too many queries - can fail with timeout. Chunk queries.
if len(self._get_queries()) > 100 and self._chunk_size is None:
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)
Expand Down
54 changes: 53 additions & 1 deletion python-package/test/geo_data/geo_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
import json
from typing import List, Union

from lets_plot.geo_data import DF_REQUEST, DF_FOUND_NAME
from lets_plot.geo_data import DF_ID, DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTY, DF_PARENT_STATE, DF_PARENT_COUNTRY
from lets_plot.geo_data.gis.geometry import Ring, Polygon, Multipolygon
from lets_plot.geo_data.gis.json_response import ResponseField, GeometryKind
from lets_plot.geo_data.gis.response import GeocodedFeature, FeatureBuilder, LevelKind, Status, GeoRect, GeoPoint, \
Response, SuccessResponse, AmbiguousResponse, ErrorResponse, ResponseBuilder
from lets_plot.geo_data.regions import Regions

from pandas import DataFrame
from shapely.geometry import Point

GEOJSON_TYPE = ResponseField.boundary_type.value
GEOJSON_COORDINATES = ResponseField.boundary_coordinates.value
Expand Down Expand Up @@ -44,6 +45,57 @@
GEO_RECT_MAX_LON: float = 9
GEO_RECT_MAX_LAT: float = 7

def run_intergration_tests() -> bool:
import os
if 'RUN_GEOCODING_INTEGRATION_TEST' in os.environ.keys():
return os.environ.get('RUN_GEOCODING_INTEGRATION_TEST').lower() == 'true'
return False


def use_local_server():
old = os.environ.copy()
os.environ.update({'GEOSERVER_URL': 'https://localhost:3012', **old})

NO_COLUMN = '<no column>'
IGNORED = '__value_ignored__'

def assert_row(df, index: int = 0, request: Union[str, List] = IGNORED, found_name: Union[str, List] = IGNORED, id: Union[str, List] = IGNORED, county: Union[str, List] = IGNORED, state: Union[str, List] = IGNORED, country: Union[str, List] = IGNORED, lon=None, lat=None) -> dict:
def assert_str(column, expected):
if expected == IGNORED:
return

if expected == NO_COLUMN:
assert column not in df.columns.tolist()
return

if isinstance(expected, str):
assert expected == df[column][index]
return

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

raise ValueError('Not support type of expected: {}'.format(str(type(expected))))


assert_str(DF_ID, id)
assert_str(DF_REQUEST, request)
assert_str(DF_FOUND_NAME, found_name)
assert_str(DF_PARENT_COUNTY, county)
assert_str(DF_PARENT_STATE, state)
assert_str(DF_PARENT_COUNTRY, country)
if lon is not None:
assert Point(df.geometry[index]).x == lon

if lat is not None:
assert Point(df.geometry[index]).y == lat


def assert_found_names(df: DataFrame, names: List[str]):
assert names == df[DF_FOUND_NAME].tolist()


def make_geocode_region(request: str, name: str, geo_object_id: str, highlights: List[str], level_kind: LevelKind = LevelKind.city) -> Regions:
return Regions(level_kind, [make_region(request, name, geo_object_id, highlights)])
Expand Down
80 changes: 80 additions & 0 deletions python-package/test/geo_data/test_integration_new_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# 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.

import lets_plot.geo_data as geodata
from lets_plot.geo_data import DF_FOUND_NAME, DF_ID, DF_REQUEST, DF_PARENT_COUNTRY, DF_PARENT_STATE, DF_PARENT_COUNTY
from .geo_data import assert_row, NO_COLUMN

def test_all_columns_order():
boston = geodata.regions_builder2(level='city', names='boston', counties='suffolk', states='massachusetts', countries='usa').build()
assert boston.to_data_frame().columns.tolist() == [DF_ID, DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTY, DF_PARENT_STATE, DF_PARENT_COUNTRY]
assert boston.limits().columns.tolist() == [DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTY, DF_PARENT_STATE, DF_PARENT_COUNTRY, 'geometry']
assert boston.centroids().columns.tolist() == [DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTY, DF_PARENT_STATE, DF_PARENT_COUNTRY, 'geometry']
assert boston.boundaries().columns.tolist() == [DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTY, DF_PARENT_STATE, DF_PARENT_COUNTRY, 'geometry']

def test_do_not_add_unsued_parents_columns():
moscow = geodata.regions_builder2(level='city', names='moscow', countries='rusria').build()
assert moscow.to_data_frame().columns.tolist() == [DF_ID, DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTRY]
assert moscow.limits().columns.tolist() == [DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTRY, 'geometry']
assert moscow.centroids().columns.tolist() == [DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTRY, 'geometry']
assert moscow.boundaries().columns.tolist() == [DF_REQUEST, DF_FOUND_NAME, DF_PARENT_COUNTRY, 'geometry']


#@pytest.mark.skipif(TURN_OFF_INTERACTION_TEST, reason='Need proper server ip')
def test_parents_in_regions_object_and_geo_data_frame():
boston = geodata.regions_builder2(level='city', names='boston', counties='suffolk', states='massachusetts', countries='usa').build()

assert_row(boston.to_data_frame(), request='boston', county='suffolk', state='massachusetts', country='usa')
assert_row(boston.limits(), request='boston', county='suffolk', state='massachusetts', country='usa')
assert_row(boston.centroids(), request='boston', county='suffolk', state='massachusetts', country='usa')
assert_row(boston.boundaries(), request='boston', county='suffolk', state='massachusetts', country='usa')

# antimeridian
ru = geodata.regions_builder2(level='country', names='russia').build()
assert_row(ru.to_data_frame(), request='russia', county=NO_COLUMN, state=NO_COLUMN, country=NO_COLUMN)
assert_row(ru.limits(), request=['russia', 'russia'], county=NO_COLUMN, state=NO_COLUMN, country=NO_COLUMN)


#@pytest.mark.skipif(TURN_OFF_INTERACTION_TEST, reason='Need proper server ip')
def test_regions_parents_in_regions_object_and_geo_data_frame():
# parent request from regions object should be propagated to resulting GeoDataFrame
massachusetts = geodata.regions_builder2(level='state', names='massachusetts').build()
boston = geodata.regions_builder2(level='city', names='boston', states=massachusetts).build()

assert_row(boston.to_data_frame(), request='boston', state='massachusetts', county=NO_COLUMN, country=NO_COLUMN)
assert_row(boston.centroids(), request='boston', state='massachusetts', county=NO_COLUMN, country=NO_COLUMN)

def test_list_of_regions_parents_in_regions_object_and_geo_data_frame():
# parent request from regions object should be propagated to resulting GeoDataFrame
states = geodata.regions_builder2(level='state', names=['massachusetts', 'texas']).build()
cities = geodata.regions_builder2(level='city', names=['boston', 'austin'], states=states).build()

assert_row(cities.to_data_frame(),
request=['boston', 'austin'],
state=['massachusetts', 'texas'],
county=NO_COLUMN,
country=NO_COLUMN
)

assert_row(cities.centroids(),
request=['boston', 'austin'],
state=['massachusetts', 'texas'],
county=NO_COLUMN,
country=NO_COLUMN
)

def test_parents_lists():
states = geodata.regions_builder2(level='state', names=['texas', 'nevada'], countries=['usa', 'usa']).build()
assert_row(states.to_data_frame(), request=['texas', 'nevada'], found_name=['Texas', 'Nevada'], country=['usa', 'usa'])

def test_with_drop_not_found():
states = geodata.regions_builder2(
level='state',
names=['texas', 'trololo', 'nevada'],
countries=['usa', 'usa', 'usa']
)\
.drop_not_found() \
.build()

assert_row(states.to_data_frame(), request=['texas', 'nevada'], found_name=['Texas', 'Nevada'], country=['usa', 'usa'])

Loading