-
Notifications
You must be signed in to change notification settings - Fork 120
/
transform.py
4507 lines (3577 loc) · 147 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
from collections import defaultdict, namedtuple
from numbers import Number
from shapely.geometry.collection import GeometryCollection
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.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 sys import float_info
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 to_float
from zope.dottedname.resolve import resolve
import csv
import pycountry
import re
import shapely.errors
import shapely.wkb
import shapely.ops
import kdtree
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('([^(]*)\(([^)]*)\).*')
# 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 _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 _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
def _building_calc_height(height_val, levels_val, levels_calc_fn):
height = _to_float_meters(height_val)
if height is not None:
return height
levels = _to_float_meters(levels_val)
if levels is None:
return None
levels = levels_calc_fn(levels)
return levels
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 in ('yes', 'true'):
properties['is_bridge'] = True
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 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 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'])
def _convert_wof_l10n_name(x):
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
return LangResult(code=_alpha_2_code_of(lang), 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',
'zh-yue'
])
def _convert_osm_l10n_name(x):
if x in osm_l10n_lookup:
return LangResult(code=x, priority=0)
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
return LangResult(code=result, priority=priority)
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.mapzen.com'
is_osm = source == 'openstreetmap.org'
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
else:
# conversion function only implemented for things which come from OSM
# 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
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
else:
return [shape]
def _filter_geom_types(shape, keep_dim):
"""
Return a geometry which consists of the geometries in
the input shape filtered so that only those of the
given dimension remain. Collapses any structure (e.g:
of geometry collections) down to a single or multi-
geometry.
>>> _filter_geom_types(GeometryCollection(), _POINT_DIMENSION).wkt
'GEOMETRYCOLLECTION EMPTY'
>>> _filter_geom_types(Point(0,0), _POINT_DIMENSION).wkt
'POINT (0 0)'
>>> _filter_geom_types(Point(0,0), _LINE_DIMENSION).wkt
'GEOMETRYCOLLECTION EMPTY'
>>> _filter_geom_types(Point(0,0), _POLYGON_DIMENSION).wkt
'GEOMETRYCOLLECTION EMPTY'
>>> _filter_geom_types(LineString([(0,0),(1,1)]), _LINE_DIMENSION).wkt
'LINESTRING (0 0, 1 1)'
>>> _filter_geom_types(Polygon([(0,0),(1,1),(1,0),(0,0)],[]), _POLYGON_DIMENSION).wkt
'POLYGON ((0 0, 1 1, 1 0, 0 0))'
>>> _filter_geom_types(shapely.wkt.loads('GEOMETRYCOLLECTION (POINT(0 0), LINESTRING(0 0, 1 1))'), _POINT_DIMENSION).wkt
'POINT (0 0)'
>>> _filter_geom_types(shapely.wkt.loads('GEOMETRYCOLLECTION (POINT(0 0), LINESTRING(0 0, 1 1))'), _LINE_DIMENSION).wkt
'LINESTRING (0 0, 1 1)'
>>> _filter_geom_types(shapely.wkt.loads('GEOMETRYCOLLECTION (POINT(0 0), LINESTRING(0 0, 1 1))'), _POLYGON_DIMENSION).wkt
'GEOMETRYCOLLECTION EMPTY'
>>> _filter_geom_types(shapely.wkt.loads('GEOMETRYCOLLECTION (POINT(0 0), GEOMETRYCOLLECTION (POINT(1 1), LINESTRING(0 0, 1 1)))'), _POINT_DIMENSION).wkt
'MULTIPOINT (0 0, 1 1)'
>>> _filter_geom_types(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_DIMENSION).wkt
'MULTIPOINT (-1 -1, 0 0, 1 1, 2 2, 3 3)'
>>> _filter_geom_types(shapely.wkt.loads('GEOMETRYCOLLECTION (LINESTRING(-1 -1, 0 0), GEOMETRYCOLLECTION (LINESTRING(1 1, 2 2), GEOMETRYCOLLECTION (POINT(3 3))), LINESTRING(0 0, 1 1))'), _LINE_DIMENSION).wkt
'MULTILINESTRING ((-1 -1, 0 0), (1 1, 2 2), (0 0, 1 1))'
>>> _filter_geom_types(shapely.wkt.loads('GEOMETRYCOLLECTION (POLYGON((-2 -2, -2 2, 2 2, 2 -2, -2 -2)), GEOMETRYCOLLECTION (LINESTRING(1 1, 2 2), GEOMETRYCOLLECTION (POLYGON((3 3, 0 0, 1 0, 3 3)))), LINESTRING(0 0, 1 1))'), _POLYGON_DIMENSION).wkt
'MULTIPOLYGON (((-2 -2, -2 2, 2 2, 2 -2, -2 -2)), ((3 3, 0 0, 1 0, 3 3)))'
""" # noqa
# flatten the geometries, and keep the parts with the
# dimension that we want. each item in the parts list
# should be a single (non-multi) geometry.
parts = []
for g in _flatten_geoms(shape):
if _geom_dimensions(g) == keep_dim:
parts.append(g)
# figure out how to construct a multi-geometry of the
# dimension wanted.
if keep_dim == _POINT_DIMENSION:
constructor = MultiPoint
elif keep_dim == _LINE_DIMENSION:
constructor = MultiLineString
elif keep_dim == _POLYGON_DIMENSION:
constructor = MultiPolygon
else:
raise ValueError('Unknown dimension %d in _filter_geom_types'
% keep_dim)
if len(parts) == 0:
return constructor()
elif len(parts) == 1:
# return the singular geometry
return parts[0]
else:
if keep_dim == _POINT_DIMENSION:
# not sure why the MultiPoint constructor wants
# its coordinates differently from MultiPolygon
# and MultiLineString...
coords = []
for p in parts:
coords.extend(p.coords)
return MultiPoint(coords)
else:
return constructor(parts)
# creates a list of indexes, each one for a different cut
# attribute value, in priority order.
#
# STRtree stores geometries and returns these from the query,
# but doesn't appear to allow any other attributes to be
# stored along with the geometries. this means we have to
# separate the index out into several "layers", each having
# the same attribute value. which isn't all that much of a
# pain, as we need to cut the shapes in a certain order to
# ensure priority anyway.
#
# intersect_func is a functor passed in to control how an
# intersection is performed. it is passed
class _Cutter:
def __init__(self, features, attrs, attribute,
target_attribute, keep_geom_type,
intersect_func):
group = defaultdict(list)
for feature in features:
shape, props, fid = feature
attr = props.get(attribute)
group[attr].append(shape)
# if the user didn't supply any options for controlling
# the cutting priority, then just make some up based on
# the attributes which are present in the dataset.
if attrs is None:
all_attrs = set()
for feature in features:
all_attrs.add(feature[1].get(attribute))
attrs = list(all_attrs)
# alternatively, the user can specify an ordering
# function over the attributes.
elif isinstance(attrs, dict):
attrs = _sorted_attributes(features, attrs,
attribute)
cut_idxs = list()
for attr in attrs:
if attr in group:
cut_idxs.append((attr, STRtree(group[attr])))
self.attribute = attribute
self.target_attribute = target_attribute
self.cut_idxs = cut_idxs
self.keep_geom_type = keep_geom_type
self.intersect_func = intersect_func
self.new_features = []
# cut up the argument shape, projecting the configured
# attribute to the properties of the intersecting parts
# of the shape. adds all the selected bits to the
# new_features list.
def cut(self, shape, props, fid):
original_geom_dim = _geom_dimensions(shape)
for cutting_attr, cut_idx in self.cut_idxs:
cutting_shapes = cut_idx.query(shape)
for cutting_shape in cutting_shapes:
if cutting_shape.intersects(shape):
shape = self._intersect(
shape, props, fid, cutting_shape,
cutting_attr, original_geom_dim)
# if there's no geometry left outside the
# shape, then we can exit the function
# early, as nothing else will intersect.
if shape.is_empty:
return
# if there's still geometry left outside, then it
# keeps the old, unaltered properties.
self._add(shape, props, fid, original_geom_dim)
# only keep geometries where either the type is the
# same as the original, or we're not trying to keep the
# same type.
def _add(self, shape, props, fid, original_geom_dim):
# if keeping the same geometry type, then filter
# out anything that's different.
if self.keep_geom_type:
shape = _filter_geom_types(
shape, original_geom_dim)
# don't add empty shapes, they're completely
# useless. the previous step may also have created
# an empty geometry if there weren't any items of
# the type we're looking for.
if shape.is_empty:
return
# add the shape as-is unless we're trying to keep
# the geometry type or the geometry dimension is
# identical.
self.new_features.append((shape, props, fid))
# intersects the shape with the cutting shape and
# handles attribute projection. anything "inside" is
# kept as it must have intersected the highest
# priority cutting shape already. the remainder is
# returned.
def _intersect(self, shape, props, fid, cutting_shape,
cutting_attr, original_geom_dim):
inside, outside = \
self.intersect_func(shape, cutting_shape)
# intersections are tricky, and it seems that the geos
# library (perhaps only certain versions of it) don't
# handle intersection of a polygon with its boundary
# very well. for example:
#
# >>> import shapely.geometry as g
# >>> p = g.Point(0,0).buffer(1.0, resolution=2)
# >>> b = p.boundary
# >>> b.intersection(p).wkt
# 'MULTILINESTRING ((1 0, 0.7071067811865481 -0.7071067811865469), (0.7071067811865481 -0.7071067811865469, 1.615544574432587e-15 -1), (1.615544574432587e-15 -1, -0.7071067811865459 -0.7071067811865491), (-0.7071067811865459 -0.7071067811865491, -1 -3.231089148865173e-15), (-1 -3.231089148865173e-15, -0.7071067811865505 0.7071067811865446), (-0.7071067811865505 0.7071067811865446, -4.624589118372729e-15 1), (-4.624589118372729e-15 1, 0.7071067811865436 0.7071067811865515), (0.7071067811865436 0.7071067811865515, 1 0))' # noqa
#
# the result multilinestring could be joined back into
# the original object. but because it has separate parts,
# each requires duplicating the start and end point, and
# each separate segment gets a different polygon buffer
# in Tangram - basically, it's a problem all round.
#
# two solutions to this: given that we're cutting, then
# the inside and outside should union back to the
# original shape - if either is empty then the whole
# object ought to be in the other.
#
# the second solution, for when there is actually some
# part cut, is that we can attempt to merge lines back
# together.
if outside.is_empty and not inside.is_empty:
inside = shape
elif inside.is_empty and not outside.is_empty:
outside = shape
elif original_geom_dim == _LINE_DIMENSION:
inside = _linemerge(inside)
outside = _linemerge(outside)
if cutting_attr is not None:
inside_props = props.copy()
inside_props[self.target_attribute] = cutting_attr
else:
inside_props = props
self._add(inside, inside_props, fid,
original_geom_dim)
return outside
def _intersect_cut(shape, cutting_shape):
"""
intersect by cutting, so that the cutting shape defines
a part of the shape which is inside and a part which is
outside as two separate shapes.
"""
inside = shape.intersection(cutting_shape)
outside = shape.difference(cutting_shape)
return inside, outside
# intersect by looking at the overlap size. we can define
# a cut-off fraction and if that fraction or more of the
# area of the shape is within the cutting shape, it's
# inside, else outside.
#
# this is done using a closure so that we can curry away
# the fraction parameter.
def _intersect_overlap(min_fraction):
# the inner function is what will actually get
# called, but closing over min_fraction means it
# will have access to that.
def _f(shape, cutting_shape):
overlap = shape.intersection(cutting_shape).area
area = shape.area
# need an empty shape of the same type as the
# original shape, which should be possible, as
# it seems shapely geometries all have a default
# constructor to empty.
empty = type(shape)()
if ((area > 0) and (overlap / area) >= min_fraction):
return shape, empty
else:
return empty, shape
return _f
# find a layer by iterating through all the layers. this
# would be easier if they layers were in a dict(), but
# that's a pretty invasive change.
#
# returns None if the layer can't be found.
def _find_layer(feature_layers, name):
for feature_layer in feature_layers:
layer_datum = feature_layer['layer_datum']
layer_name = layer_datum['name']
if layer_name == name:
return feature_layer
return None
# shared implementation of the intercut algorithm, used
# both when cutting shapes and using overlap to determine
# inside / outsideness.
def _intercut_impl(intersect_func, feature_layers,
base_layer, cutting_layer, attribute,
target_attribute, cutting_attrs,
keep_geom_type):
# the target attribute can default to the attribute if
# they are distinct. but often they aren't, and that's
# why target_attribute is a separate parameter.
if target_attribute is None:
target_attribute = attribute
# search through all the layers and extract the ones
# which have the names of the base and cutting layer.
# it would seem to be better to use a dict() for
# layers, and this will give odd results if names are
# allowed to be duplicated.
base = _find_layer(feature_layers, base_layer)
cutting = _find_layer(feature_layers, cutting_layer)
# base or cutting layer not available. this could happen
# because of a config problem, in which case you'd want
# it to be reported. but also can happen when the client
# selects a subset of layers which don't include either
# the base or the cutting layer. then it's not an error.
# the interesting case is when they select the base but
# not the cutting layer...
if base is None or cutting is None:
return None
base_features = base['features']
cutting_features = cutting['features']
# make a cutter object to help out
cutter = _Cutter(cutting_features, cutting_attrs,
attribute, target_attribute,
keep_geom_type, intersect_func)
for base_feature in base_features:
# we use shape to track the current remainder of the
# shape after subtracting bits which are inside cuts.
shape, props, fid = base_feature
cutter.cut(shape, props, fid)
base['features'] = cutter.new_features
return base
# intercut takes features from a base layer and cuts each
# of them against a cutting layer, splitting any base
# feature which intersects into separate inside and outside
# parts.
#
# the parts of each base feature which are outside any
# cutting feature are left unchanged. the parts which are
# inside have their property with the key given by the
# 'target_attribute' parameter set to the same value as the
# property from the cutting feature with the key given by
# the 'attribute' parameter.
#
# the intended use of this is to project attributes from one
# layer to another so that they can be styled appropriately.
#
# - feature_layers: list of layers containing both the base
# and cutting layer.
# - base_layer: str name of the base layer.
# - cutting_layer: str name of the cutting layer.
# - attribute: optional str name of the property / attribute
# to take from the cutting layer.
# - target_attribute: optional str name of the property /
# attribute to assign on the base layer. defaults to the
# same as the 'attribute' parameter.
# - cutting_attrs: list of str, the priority of the values
# to be used in the cutting operation. this ensures that