-
Notifications
You must be signed in to change notification settings - Fork 120
/
transform.py
9803 lines (7732 loc) · 306 KB
/
transform.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
# transformation functions to apply to features
import copy
import csv
import re
from collections import defaultdict
from collections import namedtuple
from math import ceil
from numbers import Number
from sys import float_info
import hanzidentifier
import kdtree
import pycountry
import shapely.errors
import shapely.ops
import shapely.wkb
from shapely.geometry import box as Box
from shapely.geometry import LinearRing
from shapely.geometry import LineString
from shapely.geometry import Point
from shapely.geometry import Polygon
from shapely.geometry.collection import GeometryCollection
from shapely.geometry.multilinestring import MultiLineString
from shapely.geometry.multipoint import MultiPoint
from shapely.geometry.multipolygon import MultiPolygon
from shapely.geometry.polygon import orient
from shapely.ops import linemerge
from shapely.strtree import STRtree
from sort import pois as sort_pois
from StreetNames import short_street_name
from tilequeue.process import _make_valid_if_necessary
from tilequeue.process import _visible_shape
from tilequeue.tile import calc_meters_per_pixel_area
from tilequeue.tile import normalize_geometry_type
from tilequeue.tile import tolerance_for_zoom
from tilequeue.transform import calculate_padded_bounds
from util import safe_int
from util import to_float
from zope.dottedname.resolve import resolve
feet_pattern = re.compile('([+-]?[0-9.]+)\'(?: *([+-]?[0-9.]+)")?')
number_pattern = re.compile('([+-]?[0-9.]+)')
# pattern to detect numbers with units.
# PLEASE: keep this in sync with the conversion factors below.
unit_pattern = re.compile('([+-]?[0-9.]+) *(mi|km|m|nmi|ft)')
# multiplicative conversion factor from the unit into meters.
# PLEASE: keep this in sync with the unit_pattern above.
unit_conversion_factor = {
'mi': 1609.3440,
'km': 1000.0000,
'm': 1.0000,
'nmi': 1852.0000,
'ft': 0.3048
}
# used to detect if the "name" of a building is
# actually a house number.
digits_pattern = re.compile('^[0-9-]+$')
# used to detect station names which are followed by a
# parenthetical list of line names.
station_pattern = re.compile(r'([^(]*)\(([^)]*)\).*')
# used to detect if an airport's IATA code is the "short"
# 3-character type. there are also longer codes, and ones
# which include numbers, but those seem to be used for
# less important airports.
iata_short_code_pattern = re.compile('^[A-Z]{3}$')
def _to_float_meters(x):
if x is None:
return None
as_float = to_float(x)
if as_float is not None:
return as_float
# trim whitespace to simplify further matching
x = x.strip()
# try looking for a unit
unit_match = unit_pattern.match(x)
if unit_match is not None:
value = unit_match.group(1)
units = unit_match.group(2)
value_as_float = to_float(value)
if value_as_float is not None:
return value_as_float * unit_conversion_factor[units]
# try if it looks like an expression in feet via ' "
feet_match = feet_pattern.match(x)
if feet_match is not None:
feet = feet_match.group(1)
inches = feet_match.group(2)
feet_as_float = to_float(feet)
inches_as_float = to_float(inches)
total_inches = 0.0
parsed_feet_or_inches = False
if feet_as_float is not None:
total_inches = feet_as_float * 12.0
parsed_feet_or_inches = True
if inches_as_float is not None:
total_inches += inches_as_float
parsed_feet_or_inches = True
if parsed_feet_or_inches:
# international inch is exactly 25.4mm
meters = total_inches * 0.0254
return meters
# try and match the first number that can be parsed
for number_match in number_pattern.finditer(x):
potential_number = number_match.group(1)
as_float = to_float(potential_number)
if as_float is not None:
return as_float
return None
def _to_int_degrees(x):
if x is None:
return None
as_int = safe_int(x)
if as_int is not None:
# always return within range of 0 to 360
return as_int % 360
# trim whitespace to simplify further matching
x = x.strip()
cardinals = {
'north': 0, 'N': 0, 'NNE': 22, 'NE': 45, 'ENE': 67,
'east': 90, 'E': 90, 'ESE': 112, 'SE': 135, 'SSE': 157,
'south': 180, 'S': 180, 'SSW': 202, 'SW': 225, 'WSW': 247,
'west': 270, 'W': 270, 'WNW': 292, 'NW': 315, 'NNW': 337
}
# protect against bad cardinal notations
return cardinals.get(x)
def _coalesce(properties, *property_names):
for prop in property_names:
val = properties.get(prop)
if val:
return val
return None
def _remove_properties(properties, *property_names):
for prop in property_names:
properties.pop(prop, None)
return properties
def _is_name(key):
"""
Return True if this key looks like a name.
This isn't as simple as testing if key == 'name', as there are alternative
name-like tags such as 'official_name', translated names such as 'name:en',
and left/right names for boundaries. This function aims to match all of
those variants.
"""
# simplest and most common case first
if key == 'name':
return True
# translations next
if key.startswith('name:'):
return True
# then any of the alternative forms of name
return any(key.startswith(p) for p in tag_name_alternates)
def _remove_names(props):
"""
Remove entries in the props dict for which the key looks like a name.
Modifies the props dict in-place and also returns it.
"""
for k in props.keys():
if _is_name(k):
props.pop(k)
return props
def _has_name(props):
"""
Return true if any of the props look like a name.
"""
for k in props.keys():
if _is_name(k):
return True
return False
def _building_calc_levels(levels):
levels = max(levels, 1)
levels = (levels * 3) + 2
return levels
def _building_calc_min_levels(min_levels):
min_levels = max(min_levels, 0)
min_levels = min_levels * 3
return min_levels
# slightly bigger than the tallest structure in the world. at the time
# of writing, the Burj Khalifa at 829.8m. this is used as a check to make
# sure that nonsense values (e.g: buildings a million meters tall) don't
# make it into the data.
TALLEST_STRUCTURE_METERS = 1000.0
def _building_calc_height(height_val, levels_val, levels_calc_fn):
height = _to_float_meters(height_val)
if height is not None and 0 <= height <= TALLEST_STRUCTURE_METERS:
return height
levels = _to_float_meters(levels_val)
if levels is None:
return None
levels = levels_calc_fn(levels)
if 0 <= levels <= TALLEST_STRUCTURE_METERS:
return levels
return None
def add_id_to_properties(shape, properties, fid, zoom):
properties['id'] = fid
return shape, properties, fid
def detect_osm_relation(shape, properties, fid, zoom):
# Assume all negative ids indicate the data was a relation. At the
# moment, this is true because only osm contains negative
# identifiers. Should this change, this logic would need to become
# more robust
if isinstance(fid, Number) and fid < 0:
properties['osm_relation'] = True
return shape, properties, fid
def remove_feature_id(shape, properties, fid, zoom):
return shape, properties, None
def building_height(shape, properties, fid, zoom):
height = _building_calc_height(
properties.get('height'), properties.get('building_levels'),
_building_calc_levels)
if height is not None:
properties['height'] = height
else:
properties.pop('height', None)
return shape, properties, fid
def building_min_height(shape, properties, fid, zoom):
min_height = _building_calc_height(
properties.get('min_height'), properties.get('building_min_levels'),
_building_calc_min_levels)
if min_height is not None:
properties['min_height'] = min_height
else:
properties.pop('min_height', None)
return shape, properties, fid
def synthesize_volume(shape, props, fid, zoom):
area = props.get('area')
height = props.get('height')
if area is not None and height is not None:
props['volume'] = int(area * height)
return shape, props, fid
def building_trim_properties(shape, properties, fid, zoom):
properties = _remove_properties(
properties,
'building', 'building_part',
'building_levels', 'building_min_levels')
return shape, properties, fid
def road_classifier(shape, properties, fid, zoom):
source = properties.get('source')
assert source, 'Missing source in road query'
if source == 'naturalearthdata.com':
return shape, properties, fid
properties.pop('is_link', None)
properties.pop('is_tunnel', None)
properties.pop('is_bridge', None)
kind_detail = properties.get('kind_detail', '')
tunnel = properties.get('tunnel', '')
bridge = properties.get('bridge', '')
if kind_detail.endswith('_link'):
properties['is_link'] = True
if tunnel in ('yes', 'true'):
properties['is_tunnel'] = True
if bridge and bridge != 'no':
properties['is_bridge'] = True
return shape, properties, fid
def add_road_network_from_ncat(shape, properties, fid, zoom):
"""
Many South Korean roads appear to have an "ncat" tag, which seems to
correspond to the type of road network (perhaps "ncat" = "national
category"?)
This filter carries that through into "network", unless it is already
populated.
"""
if properties.get('network') is None:
tags = properties.get('tags', {})
ncat = _make_unicode_or_none(tags.get('ncat'))
if ncat == u'국도':
# national roads - gukdo
properties['network'] = 'KR:national'
elif ncat == u'광역시도로':
# metropolitan city roads - gwangyeoksido
properties['network'] = 'KR:metropolitan'
elif ncat == u'특별시도':
# special city (Seoul) roads - teukbyeolsido
properties['network'] = 'KR:metropolitan'
elif ncat == u'고속도로':
# expressways - gosokdoro
properties['network'] = 'KR:expressway'
elif ncat == u'지방도':
# local highways - jibangdo
properties['network'] = 'KR:local'
return shape, properties, fid
def road_trim_properties(shape, properties, fid, zoom):
properties = _remove_properties(properties, 'bridge', 'tunnel')
return shape, properties, fid
def _reverse_line_direction(shape):
if shape.type != 'LineString':
return False
shape.coords = shape.coords[::-1]
return True
def road_oneway(shape, properties, fid, zoom):
oneway = properties.get('oneway')
if oneway in ('-1', 'reverse'):
did_reverse = _reverse_line_direction(shape)
if did_reverse:
properties['oneway'] = 'yes'
elif oneway in ('true', '1'):
properties['oneway'] = 'yes'
elif oneway in ('false', '0'):
properties['oneway'] = 'no'
return shape, properties, fid
def road_abbreviate_name(shape, properties, fid, zoom):
name = properties.get('name', None)
if not name:
return shape, properties, fid
short_name = short_street_name(name)
properties['name'] = short_name
return shape, properties, fid
def route_name(shape, properties, fid, zoom):
rn = properties.get('route_name')
if rn:
name = properties.get('name')
if not name:
properties['name'] = rn
del properties['route_name']
elif rn == name:
del properties['route_name']
return shape, properties, fid
def place_population_int(shape, properties, fid, zoom):
population_str = properties.pop('population', None)
population = to_float(population_str)
if population is not None:
properties['population'] = int(population)
return shape, properties, fid
def _calculate_population_rank(population):
population = to_float(population)
if population is None:
population = 0
else:
population = int(population)
pop_breaks = [
1000000000,
100000000,
50000000,
20000000,
10000000,
5000000,
1000000,
500000,
200000,
100000,
50000,
20000,
10000,
5000,
2000,
1000,
200,
0,
]
for i, pop_break in enumerate(pop_breaks):
if population >= pop_break:
rank = len(pop_breaks) - i
break
else:
rank = 0
return rank
def population_rank(shape, properties, fid, zoom):
population = properties.get('population')
properties['population_rank'] = _calculate_population_rank(population)
return (shape, properties, fid)
def pois_capacity_int(shape, properties, fid, zoom):
pois_capacity_str = properties.pop('capacity', None)
capacity = to_float(pois_capacity_str)
if capacity is not None:
properties['capacity'] = int(capacity)
return shape, properties, fid
def pois_direction_int(shape, props, fid, zoom):
direction = props.get('direction')
if not direction:
return shape, props, fid
props['direction'] = _to_int_degrees(direction)
return shape, props, fid
def water_tunnel(shape, properties, fid, zoom):
tunnel = properties.pop('tunnel', None)
if tunnel in (None, 'no', 'false', '0'):
properties.pop('is_tunnel', None)
else:
properties['is_tunnel'] = True
return shape, properties, fid
def admin_level_as_int(shape, properties, fid, zoom):
admin_level_str = properties.pop('admin_level', None)
if admin_level_str is None:
return shape, properties, fid
try:
admin_level_int = int(admin_level_str)
except ValueError:
return shape, properties, fid
properties['admin_level'] = admin_level_int
return shape, properties, fid
def tags_create_dict(shape, properties, fid, zoom):
tags_hstore = properties.get('tags')
if tags_hstore:
tags = dict(tags_hstore)
properties['tags'] = tags
return shape, properties, fid
def tags_remove(shape, properties, fid, zoom):
properties.pop('tags', None)
return shape, properties, fid
tag_name_alternates = (
'int_name',
'loc_name',
'nat_name',
'official_name',
'old_name',
'reg_name',
'short_name',
'name_left',
'name_right',
'name:short',
)
def _alpha_2_code_of(lang):
try:
alpha_2_code = lang.alpha_2.encode('utf-8')
except AttributeError:
return None
return alpha_2_code
# a structure to return language code lookup results preserving the priority
# (lower is better) of the result for use in situations where multiple inputs
# can map to the same output.
LangResult = namedtuple('LangResult', ['code', 'priority'])
zh_alpha_2_lang_code = 'zh'
# key is the name in WOF source; value is the Tilezen internal name and its
# priority
wof_zh_variants_lookup = {
'zho_cn_x_preferred': ('zh-Hans', 0), # Simplified Chinese
'zho_x_preferred': ('zh-Hans', 1), # Simplified Chinese
'wuu_x_preferred': ('zh-Hans', 2), # Simplified Chinese
'zho_tw_x_preferred': ('zh-Hant', 0), # Traditional Chinese
'zho_x_variant': ('zh-Hant', 1), # Traditional Chinese
}
def _convert_wof_l10n_name(x):
if x in wof_zh_variants_lookup:
return LangResult(code=wof_zh_variants_lookup[x][0],
priority=wof_zh_variants_lookup[x][1])
lang_str_iso_639_3 = x[:3]
if len(lang_str_iso_639_3) != 3:
return None
try:
lang = pycountry.languages.get(alpha_3=lang_str_iso_639_3)
except KeyError:
return None
lang_code = _alpha_2_code_of(lang)
if lang_code == zh_alpha_2_lang_code:
return None
return LangResult(code=_alpha_2_code_of(lang), priority=0)
# key is the name in NE source; value is a tuple of Tilezen internal
# name and its priority value
ne_zh_variants_lookup = {
'zh': ('zh-Hans', 0), # Simplified Chinese
'zht': ('zh-Hant', 0), # Traditional Chinese
}
def _convert_ne_l10n_name(x):
if x in ne_zh_variants_lookup:
return LangResult(code=ne_zh_variants_lookup[x][0],
priority=ne_zh_variants_lookup[x][1])
if len(x) != 2:
return None
try:
lang = pycountry.languages.get(alpha_2=x)
except KeyError:
return None
lang_code = _alpha_2_code_of(lang)
if lang_code == zh_alpha_2_lang_code:
return None
return LangResult(code=lang_code, priority=0)
def _normalize_osm_lang_code(x):
# first try an alpha-2 code
try:
lang = pycountry.languages.get(alpha_2=x)
except KeyError:
# next, try an alpha-3 code
try:
lang = pycountry.languages.get(alpha_3=x)
except KeyError:
# finally, try a "bibliographic" code
try:
lang = pycountry.languages.get(bibliographic=x)
except KeyError:
return None
return _alpha_2_code_of(lang)
def _normalize_country_code(x):
x = x.upper()
try:
c = pycountry.countries.get(alpha_2=x)
except KeyError:
try:
c = pycountry.countries.get(alpha_3=x)
except KeyError:
try:
c = pycountry.countries.get(numeric=x)
except KeyError:
return None
alpha2_code = c.alpha_2
return alpha2_code
osm_l10n_lookup = set([
'zh-min-nan',
])
# key is the name in OSM source; value is a tuple of Tilezen internal name
# and its priority value
osm_zh_variants_lookup = {
'zh-Hans': ('zh-Hans', 0), # Simplified Chinese
'zh-SG': ('zh-Hans', 1), # Simplified Chinese
'zh': ('zh-default', 0), # Simplified Chinese presumably, can contain Traditional Chinese
'zh-Hant': ('zh-Hant', 0), # Traditional Chinese
'zh-Hant-tw': ('zh-Hant', 1), # Traditional Chinese
'zh-Hant-hk': ('zh-Hant', 2), # Traditional Chinese
'zh-yue': ('zh-Hant', 3), # Traditional Chinese
'zh-HK': ('zh-Hant', 4), # Traditional Chinese
}
def _convert_osm_l10n_name(x):
if x in osm_l10n_lookup:
return LangResult(code=x, priority=0)
if x in osm_zh_variants_lookup:
return LangResult(code=osm_zh_variants_lookup[x][0],
priority=osm_zh_variants_lookup[x][1])
# all accepted Chinese variants should be handled in the shortcuts already
# so won't accept other tags that starts with `zh` any more
if x.startswith('zh'):
return None
if '_' not in x:
lang_code_candidate = x
country_candidate = None
else:
fields_by_underscore = x.split('_', 1)
lang_code_candidate, country_candidate = fields_by_underscore
lang_code_result = _normalize_osm_lang_code(lang_code_candidate)
if lang_code_result is None:
return None
priority = 0
if country_candidate:
country_result = _normalize_country_code(country_candidate)
if country_result is None:
result = lang_code_result
priority = 1
else:
result = '%s_%s' % (lang_code_result, country_result)
else:
result = lang_code_result
if result == zh_alpha_2_lang_code:
return None
return LangResult(code=result, priority=priority)
def post_process_ne_wof_zh(properties):
""" If there is no Simplified Chinese, Traditional
Chinese will be used to further backfill, and vice versa """
if 'name:zh-Hans' not in properties and 'name:zh-Hant' in properties:
properties['name:zh-Hans'] = properties['name:zh-Hant']
if 'name:zh-Hant' not in properties and 'name:zh-Hans' in properties:
properties['name:zh-Hant'] = properties['name:zh-Hans']
def clean_backfill_zh(properties):
""" only select one of the options if the field is separated by "/"
for example if the field is "旧金山市县/三藩市市縣/舊金山市郡" only the first
one 旧金山市县 will be preserved
also some data source may have leading backslash char or whitespace,
need to remove those too.
Also for backward compatibility, we also populate name:zh field
Finally, if any of the 'name:zh-Hans', 'name:zh-Hant' or 'name:zh' field
is empty or is whitespace string, we remove it.
"""
if properties.get('name:zh-Hans'):
properties['name:zh-Hans'] = properties['name:zh-Hans'].split('/')[0].strip().strip('\\')
if properties.get('name:zh-Hant'):
properties['name:zh-Hant'] = properties['name:zh-Hant'].split('/')[0].strip().strip('\\')
if properties.get('name:zh-Hans'):
properties['name:zh'] = properties['name:zh-Hans']
elif properties.get('name:zh-Hant'):
properties['name:zh'] = properties['name:zh-Hant']
# if the field is empty/whitespace string we don't include the properties
if 'name:zh-Hans' in properties and \
(properties['name:zh-Hans'] is None or
not properties['name:zh-Hans'].strip()):
del properties['name:zh-Hans']
if 'name:zh-Hant' in properties and \
(properties['name:zh-Hant'] is None or
not properties['name:zh-Hant'].strip()):
del properties['name:zh-Hant']
if 'name:zh' in properties and \
(properties['name:zh'] is None or
not properties['name:zh'].strip()):
del properties['name:zh']
def post_process_osm_zh(properties):
""" First check whether name:zh (Simplified) and name:zht(Traditional)
are set already, if not we use the name:zh-default to backfill them.
During the backfill, if there is no Simplified Chinese, Traditional
Chinese will be used to further backfill, and vice versa
It also deletes the intermediate property `zh-default`
Before the function returns, 'name:zh-Hant' or 'name:zh-Hans' may
contain an empty string or whitespaces string.
"""
if 'name:zh-Hans' not in properties and 'name:zh-Hant' not in properties and \
'name:zh-default' not in properties:
return
if 'name:zh-Hans' in properties and 'name:zh-Hant' in properties:
if 'name:zh-default' in properties:
del properties['name:zh-default']
return
zh_Hans_fallback = properties['name:zh-Hans'] if 'name:zh-Hans' in \
properties else u''
zh_Hant_fallback = properties['name:zh-Hant'] if 'name:zh-Hant' in \
properties else u''
if properties.get('name:zh-default'):
names = properties['name:zh-default'].split('/')
for name in names:
if hanzidentifier.is_simplified(name) and \
len(zh_Hans_fallback) == 0:
zh_Hans_fallback = name
if hanzidentifier.is_traditional(name) and \
len(zh_Hant_fallback) == 0:
zh_Hant_fallback = name
# hanzidentifier cannot deem it either way
if len(names) != 0:
if len(zh_Hans_fallback) == 0:
zh_Hans_fallback = names[0]
if len(zh_Hant_fallback) == 0:
zh_Hant_fallback = names[0]
if not properties.get('name:zh-Hans'):
if zh_Hans_fallback:
properties['name:zh-Hans'] = zh_Hans_fallback
elif zh_Hant_fallback:
properties['name:zh-Hans'] = zh_Hant_fallback
if not properties.get('name:zh-Hant'):
if zh_Hant_fallback:
properties['name:zh-Hant'] = zh_Hant_fallback
elif zh_Hans_fallback:
properties['name:zh-Hant'] = zh_Hans_fallback
if 'name:zh-default' in properties:
del properties['name:zh-default']
def tags_name_i18n(shape, properties, fid, zoom):
tags = properties.get('tags')
if not tags:
return shape, properties, fid
name = properties.get('name')
if not name:
return shape, properties, fid
source = properties.get('source')
is_wof = source == 'whosonfirst.org'
is_osm = source == 'openstreetmap.org'
is_ne = source == 'naturalearthdata.com'
if is_osm:
alt_name_prefix_candidates = [
'name:left:', 'name:right:', 'name:', 'alt_name:', 'old_name:'
]
convert_fn = _convert_osm_l10n_name
elif is_wof:
alt_name_prefix_candidates = ['name:']
convert_fn = _convert_wof_l10n_name
elif is_ne:
# replace name_xx with name:xx in tags
for k in tags.keys():
if k.startswith('name_'):
value = tags.pop(k)
tag_k = k.replace('_', ':')
tags[tag_k] = value
alt_name_prefix_candidates = ['name:']
convert_fn = _convert_ne_l10n_name
else:
# conversion function only implemented for things which come from OSM,
# NE or WOF - implement more cases here when more localized named
# sources become available.
return shape, properties, fid
langs = {}
for k, v in tags.items():
for candidate in alt_name_prefix_candidates:
if k.startswith(candidate):
lang_code = k[len(candidate):]
normalized_lang_code = convert_fn(lang_code)
if normalized_lang_code:
code = normalized_lang_code.code
priority = normalized_lang_code.priority
lang_key = '%s%s' % (candidate, code)
if lang_key not in langs or \
priority < langs[lang_key][0].priority:
langs[lang_key] = (normalized_lang_code, v)
for lang_key, (lang, v) in langs.items():
properties[lang_key] = v
if is_osm:
post_process_osm_zh(properties)
if is_wof or is_ne:
post_process_ne_wof_zh(properties)
clean_backfill_zh(properties)
for alt_tag_name_candidate in tag_name_alternates:
alt_tag_name_value = tags.get(alt_tag_name_candidate)
if alt_tag_name_value and alt_tag_name_value != name:
properties[alt_tag_name_candidate] = alt_tag_name_value
return shape, properties, fid
def _no_none_min(a, b):
"""
Usually, `min(None, a)` will return None. This isn't
what we want, so this one will return a non-None
argument instead. This is basically the same as
treating None as greater than any other value.
"""
if a is None:
return b
elif b is None:
return a
else:
return min(a, b)
def _sorted_attributes(features, attrs, attribute):
"""
When the list of attributes is a dictionary, use the
sort key parameter to order the feature attributes.
evaluate it as a function and return it. If it's not
in the right format, attrs isn't a dict then returns
None.
"""
sort_key = attrs.get('sort_key')
reverse = attrs.get('reverse')
assert sort_key is not None, 'Configuration ' + \
"parameter 'sort_key' is missing, please " + \
'check your configuration.'
# first, we find the _minimum_ ordering over the
# group of key values. this is because we only do
# the intersection in groups by the cutting
# attribute, so can only sort in accordance with
# that.
group = dict()
for feature in features:
val = feature[1].get(sort_key)
key = feature[1].get(attribute)
val = _no_none_min(val, group.get(key))
group[key] = val
# extract the sorted list of attributes from the
# grouped (attribute, order) pairs, ordering by
# the order.
all_attrs = sorted(group.iteritems(),
key=lambda x: x[1], reverse=bool(reverse))
# strip out the sort key in return
return [x[0] for x in all_attrs]
# the table of geometry dimensions indexed by geometry
# type name. it would be better to use geometry type ID,
# but it seems like that isn't exposed.
#
# each of these is a bit-mask, so zero dimentions is
# represented by 1, one by 2, etc... this is to support
# things like geometry collections where the type isn't
# statically known.
_NULL_DIMENSION = 0
_POINT_DIMENSION = 1
_LINE_DIMENSION = 2
_POLYGON_DIMENSION = 4
_GEOMETRY_DIMENSIONS = {
'Point': _POINT_DIMENSION,
'LineString': _LINE_DIMENSION,
'LinearRing': _LINE_DIMENSION,
'Polygon': _POLYGON_DIMENSION,
'MultiPoint': _POINT_DIMENSION,
'MultiLineString': _LINE_DIMENSION,
'MultiPolygon': _POLYGON_DIMENSION,
'GeometryCollection': _NULL_DIMENSION,
}
# returns the dimensionality of the object. so points have
# zero dimensions, lines one, polygons two. multi* variants
# have the same as their singular variant.
#
# geometry collections can hold many different types, so
# we use a bit-mask of the dimensions and recurse down to
# find the actual dimensionality of the stored set.
#
# returns a bit-mask, with these bits ORed together:
# 1: contains a point / zero-dimensional object
# 2: contains a linestring / one-dimensional object
# 4: contains a polygon / two-dimensional object
def _geom_dimensions(g):
dim = _GEOMETRY_DIMENSIONS.get(g.geom_type)
assert dim is not None, 'Unknown geometry type ' + \
'%s in transform._geom_dimensions.' % \
repr(g.geom_type)
# recurse for geometry collections to find the true
# dimensionality of the geometry.
if dim == _NULL_DIMENSION:
for part in g.geoms:
dim = dim | _geom_dimensions(part)
return dim
def _flatten_geoms(shape):
"""
Flatten a shape so that it is returned as a list
of single geometries.
>>> [g.wkt for g in _flatten_geoms(shapely.wkt.loads('GEOMETRYCOLLECTION (MULTIPOINT(-1 -1, 0 0), GEOMETRYCOLLECTION (POINT(1 1), POINT(2 2), GEOMETRYCOLLECTION (POINT(3 3))), LINESTRING(0 0, 1 1))'))]
['POINT (-1 -1)', 'POINT (0 0)', 'POINT (1 1)', 'POINT (2 2)', 'POINT (3 3)', 'LINESTRING (0 0, 1 1)']
>>> _flatten_geoms(Polygon())
[]
>>> _flatten_geoms(MultiPolygon())
[]
""" # noqa
if shape.geom_type.startswith('Multi'):
return shape.geoms
elif shape.is_empty:
return []
elif shape.type == 'GeometryCollection':
geoms = []
for g in shape.geoms:
geoms.extend(_flatten_geoms(g))
return geoms