-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsauce.py
3717 lines (2919 loc) · 116 KB
/
sauce.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
"""
functions and utilities for spaghetti
this include functions used for cleaning both tiger roads
and tiger edges files
"""
# standard library imports
import os, re, zipfile, copy, io
try:
import requests
except:
print('Could not import package: requests')
from ast import literal_eval
# non-standard library imports
import geopandas as gpd
import numpy as np
from shapely.geometry import Point, MultiPoint
from shapely.geometry import LineString, MultiLineString
from shapely.geometry import GeometryCollection
from shapely.ops import linemerge, polygonize
# used to supress warning in addIDX()
gpd.pd.set_option('mode.chained_assignment',None)
# project library imports
from . import utils
###############################################################################
################ TIGER/Line clean up functionality ############################
###############################################################################
def get_raw_tiger_edges(net, tiger_type='Edges'):
"""set paths for raw tiger data
Parameters
----------
net : spaghetti.SpaghettiNetwork
tiger_type : str
current fucntionality supports 'Edges'
Returns
-------
shp_file : str
update 'initial' path to point to .shp
"""
# descriptive file name
shp_desc = tiger_type + net.place_time
# upper directory to .shp
shp_path = net.segmdata + shp_desc
# full path to local .shp including ,shp itself
shp_file = shp_path + '/' + shp_desc + net.file_type
# if the file already exists return the file path
if os.path.exists(shp_file):
return shp_file
co_st = net.county + '_' + net.state
# for test areas
if net.study_area != co_st:
# path to full set of data
full_file = net.segmdata.replace(net.study_area, co_st)
# make sure full county exits
full_shp_file = full_file + shp_desc + '/' + shp_desc + net.file_type
if not os.path.exists(full_shp_file):
raise Exception(full_shp_file + ' does not exist.')
# make subset directory if it doesn't exist
initial_dir = net.segmdata + shp_desc
if not os.path.exists(initial_dir):
os.makedirs(initial_dir)
# subset roads from full file
subset_roads = subset_for_tests(net.study_area, net.proj_trans)
subset_roads.to_file(shp_file)
return shp_file
# for full counties
else:
# FIPS dictionary
st_fp, ct_fp = utils.get_fips(net.state, net.county)
# file name on site
remote_name = 'tl_' + net.year + '_'\
+ st_fp + ct_fp + '_' + tiger_type.lower()
remote_dir = 'geo/tiger/TIGER' + net.year\
+ '/' + tiger_type.upper() + '/'
# zip file name to be written
zip_file_name = shp_path + '.zip'
# stream from url -- set url for zipped file location
zip_file_url = 'https://www2.census.gov/'\
+ remote_dir + remote_name + '.zip'
# send request
r = requests.get(zip_file_url, stream=True)
# isolate the zipped file and extract
zip_file = zipfile.ZipFile(io.BytesIO(r.content))
# write file to disk
zip_file.extractall(shp_path)
zip_file.close()
# rename files descriptively
for filename in os.listdir(shp_path):
# split on '.' to handle .shp.xml
filename_split = re.split(r'[\.]',filename)
filename_split[0] = shp_desc
# descriptive name
desc_name = '.'.join(filename_split)
rename_from = shp_path + '/' + filename
rename_to = shp_path + '/' + desc_name
# rename files
os.rename(rename_from, rename_to)
return shp_file
def subset_for_tests(subset, crs):
"""Extract network segments intersecting the tract buffer
Parameters
----------
subset : str
network subset name
crs : int
projected coordinate reference system
Returns
-------
tract_segms : geopandas.GeoDataFrame
network segments intersecting the tract buffer
"""
if subset == 'Test_Grid_Leon_County':
raise Exception('does not exist')
else:
# read in roads
full_roads_file =\
'../data/Leon_FL/clean/network_data/SimplifiedSegms_Leon_FL_2010.shp'
full_roads = gpd.read_file(full_roads_file)
full_roads = utils.set_crs(full_roads, proj_init=crs)
# read in tracts
hard_code = '../data/' + subset\
+ '/clean/census_data/CensusTracts_Leon_FL_2010.shp'
tract = gpd.read_file(hard_code)
tract = utils.set_crs(tract, proj_init=crs)
# extract geometry and create small buffer to get border roads
tract_ = tract.geometry.squeeze().buffer(1)
# network segments intersecting the tract buffer
tract_segms = full_roads[full_roads.intersects(tract_)]
tract_segms = utils.set_crs(tract_segms, proj_init=crs)
return tract_segms
def tiger_netprep(net, in_file=None, calc_len=False):
"""scrub a raw tiger lines file at the county level to prep for
network. either TIGER/Line EDGES or ROADS (preferably EDGES)
Parameters
----------
net : spaghetti.SpaghettiNetwork
in_file : str
file path to raw data. Default is None.
calc_len : bool
calculated length and add column. Default is False.
Returns
-------
gdf : geopandas.GeoDataFrame
fully cleansed roads ready to process network instantiation
"""
# Reproject roads and subset by road type
subphase_file = net.inter+'StreetsSubset_Initial'
full_file = net.inter+'StreetsFull'
gdf = initial_subset(net, in_file, calc_len=calc_len,
save_full=full_file, save_subphase=subphase_file)
# Correcting ring roads
subphase_file = net.inter+'RingRoadsCorrected'
gdf = ring_correction(net, gdf, save_keep=subphase_file)
# Cleanse SuperCycle
# Before splitting:
# TIGER EDGES - Weld interstate segment pieces
# TIGER ROADS - Drop equal & contained geoms in sequence
gdf = cleanse_supercycle(net, gdf, series=True, inherit_attrs=True,
calc_len=calc_len, equal_geom=True,
contained_geom=True)
return gdf
def initial_subset(net, raw_data, calc_len=False,
save_full=None, save_subphase=None):
"""Initalize a network data cleanse from raw tiger line files
Parameters
----------
net : spaghetti.SpaghettiNetwork
raw_data : str
directory to find raw tiger data
calc_len : bool
calculated length and add column. Default is False.
save_full : str
directory to save full files. Default is None.
save_subphase : str
path to save subphase file Default is None.
Returns
-------
gdf : geopandas.GeoDataFrame
initial dataframe of scrubbed roads
"""
# Read in raw TIGER street data
gdf = setup_raw(net, raw_data=raw_data, calc_len=calc_len)
# remove trouble maker segments
if net.discard_segs:
gdf = gdf[~gdf[net.attr2].isin(net.discard_segs)]
# Add three new MTFCC columns for feature class,
# description, and rank
if net.mtfcc_types:
mtfcc_columns = ['FClass', 'Desc', 'MTFCCRank']
for c in mtfcc_columns:
gdf[c] = [net.mtfcc_types[mtfcc_type][c]\
for mtfcc_type in gdf[net.attr1]]
if save_full:
gdf.to_file(save_full+net.file_type)
# Subset roads
if 'FClass' in gdf.columns and net.mtfcc_discard:
gdf = utils.record_filter(gdf, column='FClass',
mval=net.mtfcc_discard, oper='out')
gdf.reset_index(drop=True, inplace=True)
gdf = label_rings(gdf, geo_col=net.geo_col)
# create segment xyID
segm2xyid = utils.generate_xyid(df=gdf, geom_type='segm',
geo_col=net.geo_col)
gdf = utils.fill_frame(gdf, col=net.xyid, data=segm2xyid)
if save_subphase:
gdf.to_file(save_subphase+net.file_type)
return gdf
def label_rings(df, geo_col=None):
"""label each line segment as ring (True) or not (False)
Parameters
----------
df : geopandas.GeoDataFrame
dataframe of geometries
geo_col : str
geometry column name. Default is None.
Returns
-------
df : geopandas.GeoDataFrame
dataframe of geometries
"""
df['ring'] = ['False']*df.shape[0]
for idx in df.index:
if df[geo_col][idx].is_ring:
df['ring'][idx] = 'True'
return df
def setup_raw(net, raw_data=None, calc_len=False):
"""initial raw data prep
Parameters
----------
net : spaghetti.SpaghettiNetwork
raw_data : str
directory to find raw tiger data
calc_len : bool
calculated length and add column. Default is False.
Returns
-------
gdf : geopandas.GeoDataFrame
initial dataframe of scrubed roads
"""
gdf = gpd.read_file(raw_data)
try:
# tiger edges subsets
if net.tiger_edges and net.edge_subsets:
for ss in net.edge_subsets:
gdf = gdf[ss[1]['relate'](gdf[ss[1]['col']], ss[1]['val'])]
except KeyError:
pass
# weld multilinestrings segs into linestrings -- only occurs in 'roads'
if net.tiger_roads:
gdf = seg_welder(gdf, geo_col=net.geo_col)
init_records = gdf.shape[0]
gdf['Phase'] = 'Initial'
if net.proj_trans: # Transform
gdf = utils.set_crs(gdf, proj_init=net.proj_init,
proj_trans=net.proj_trans)
if calc_len:
gdf = add_length(gdf, len_col=net.len_col, geo_col=net.geo_col)
initial_len = gdf[net.len_col].sum()
# segment count and length for the raw tiger data
raw_data_info = {'segment_count':init_records, 'length':initial_len}
net.raw_data_info = raw_data_info
return gdf
def add_length(frame, len_col=None, geo_col=None):
"""add length column to a dataframe
Parameters
----------
frame : geopandas.GeoDataFrame
dataframe of geometries
len_col : str
length column name in dataframe. Default is None.
geo_col : str
geometry column name. Default is None.
Returns
-------
frame : geopandas.GeoDataFrame
updated dataframe of geometries
"""
if list(frame.columns).__contains__(len_col):
frame = frame.drop(len_col, axis=1)
frame[len_col] = [frame[geo_col][idx].length for idx in frame.index]
return frame
def ring_correction(net, df, save_keep=None):
"""ring roads should start and end with the point at which it
intersects with another road segment. This algorithm find instances
where rings roads are digitized incorrectly which results in ring
roads having their endpoints somewhere in the middle of the line,
then corrects the loop by updating the geometry. Length and
attributes of the original line segment are not changed.
Parameters
----------
net : spaghetti.SpaghettiNetwork
df : geopandas.GeoDataFrame
dataframe of road segments
save_keep : str
path to save the shapefile. Default is None.
Returns
-------
df : geopandas.GeoDataFrame
updated dataframe of road segments
"""
# subset only ring roads
rings_df = df[df['ring'] == 'True']
ringsidx, corrected_rings = rings_df.index, 0
for idx in ringsidx:
LOI = rings_df[net.geo_col][idx]
# get idividual ring road - normal road pairs intersection
i_geoms = get_intersecting_geoms(net, df1=df, geom1=idx, wbool=False)
i_geoms = i_geoms[i_geoms.index != idx]
# rings that are not connected to the network will be removed
if i_geoms.shape[0] < 1:
continue
node = i_geoms[net.geo_col][:1].intersection(LOI).values[0]
# if pre cleaned and segments still overlap
if type(node) != Point:
continue
node_coords = list(zip(node.xy[0], node.xy[1]))
line_coords = list(zip(LOI.coords.xy[0], LOI.coords.xy[1]))
# if problem ring road
# (e.g. the endpoint is not the intersection)
if node_coords[0] != line_coords[0]:
updated_line = _correct_ring(node_coords, line_coords)
# update dataframe record
df[net.geo_col][idx] = updated_line
corrected_rings += 1
df.reset_index(drop=True, inplace=True)
df = add_ids(df, id_name=net.sid_name)
# add updated xyid
segm2xyid = utils.generate_xyid(df=df, geom_type='segm',
geo_col=net.geo_col)
df = utils.fill_frame(df, col=net.xyid, data=segm2xyid)
# corrected ring road count
net.corrected_rings = corrected_rings
if save_keep:
df.to_file(save_keep+net.file_type)
return df
def _correct_ring(node_coords, line_coords, post_check=False):
"""helper function for ring_correction
Parameters
----------
node_coords : list
xy tuple for a node.
line_coords : list
all xy tuple for a line.
post_check : bool
check following a cleanse cycle. Default is False.
Returns
-------
updated_line : shapely.LineString
ring road updated so that it begins and ends at
the intersecting node.
"""
if post_check:
node_coords = [node_coords]
if node_coords[0] == line_coords[0]:
return line_coords
for itemidx, coord in enumerate(line_coords):
# find the index of the intersecting coord in the line
if coord == node_coords[0]:
break
# adjust the line coordinates for the true ring start/end
updated_line = line_coords[itemidx:] + line_coords[1:itemidx+1]
updated_line = LineString(updated_line)
return updated_line
def get_intersecting_geoms(net, df1=None, geom1=None,
df2=None, geom2=None, wbool=True):
"""return the subset of intersecting geometries
from within a geodataframe
Parameters
----------
net : spaghetti.SpaghettiNetwork
df1 : geopandas.GeoDataFrame
primary dataframe. Default is None.
geom1 : int
geometry index. Default is None.
df2 : geopandas.GeoDataFrame
secondary dataframe . Default is None.
geom2 : int
geometry index. Default is None.
wbool : bool
return a boolean object for intersections. Default is True.
geo_col : str
geometry column name. Default is None.
Returns
-------
i_geom : geopandas.GeoDataFrame
intersecting geometry subset
i_bool : bool array
optional return of intersecting geoms
"""
# if there *IS NO* dataframe 2 in play
if not hasattr(df2, net.geo_col):
i_bool = df1.intersects(df1[net.geo_col][geom1])
# if there *IS* dataframe 2 in play
else:
i_bool = df1.intersects(df2[net.geo_col][geom2])
i_geom = df1[i_bool]
if wbool:
return i_bool, i_geom
else:
return i_geom
def add_ids(frame, id_name=None):
"""add an idx column to a dataframe
Parameters
----------
frame : geopandas.GeoDataFrame
dataframe of geometries
id_name : str
name of id column. Default is None.
Returns
-------
frame : geopandas.GeoDataFrame
updated dataframe of geometries
"""
frame[id_name] = [idx for idx in range(frame.shape[0])]
frame[id_name] = frame[id_name].astype(int)
return frame
def cleanse_supercycle(net, gdf, series=False, inherit_attrs=False,
calc_len=True, equal_geom=False, contained_geom=False,
save_out=True, skip_restr=True):
"""One iteration of a cleanse supercycle; then repeat as
necessary --> 1. Drop equal geoms; 2. Drop contained geoms;
3. Split line segments
Parameters
----------
net : spaghetti.SpaghettiNetwork
gdf : geopandas.GeoDataFrame
streets dataframe
inherit_attrs : bool
inherit attributes from the dominant line segment.
Default is False.
series : bool
search a geoseries. Default is False.
equal_geom : bool
drop all but one of equal geometries. Default is False.
contained_geom : bool
drop all contained geometries. Default is False.
calc_len : bool
calculated length and add column. Default is True.
Returns
-------
gdf : geopandas.GeoDataFrame
streets dataframe
"""
iteration = 0
completely_scrubbed = False
while not completely_scrubbed:
iteration += 1
itr = str(iteration)
if net.tiger_edges:
gdf = restriction_welder(net, gdf)
if net.tiger_roads:
# Drop equal geoms
if net.inter:
inter_file = net.inter+'NoEqualGeom'+itr
else:
inter_file = None
gdf = streets_filter(net, gdf, series=series,
equal_geom=equal_geom, save_keep=inter_file)
# Drop contained geometries
if net.inter:
inter_file = net.inter+'NoContainedGeom'+itr
else:
inter_file = None
gdf = streets_filter(net, gdf, series=series, save_keep=inter_file,
contained_geom=contained_geom)
# Split segments
if net.inter:
inter_file = net.inter+'SplitSegms'+itr
else:
inter_file = None
gdf = line_splitter(net, gdf, proj_init=net.proj_trans,
calc_len=calc_len, save_keep=inter_file, stage=itr,
inherit_attrs=inherit_attrs)
# Determine if completely scrubbed
if not net.tiger_edges:
completely_scrubbed = check_cleanliness(net, gdf)
else:
completely_scrubbed = True
# cycles needed for cleanse
net.cleanse_cycles = iteration
net.scrubbed = completely_scrubbed
# Re-lablel Rings
gdf = label_rings(gdf, geo_col=net.geo_col)
gdf.reset_index(inplace=True, drop=True)
return gdf
def restriction_welder(net, gdf, phase='Phase', phase_name='InterstateWeld'):
"""weld each set of restricted segments (e.g. interstates)
Parameters
----------
net : spaghetti.SpaghettiNetwork
gdf : geopandas.GeoDataFrame
streets dataframe
phase : str
column name in dataframe. Default is 'Phase'.
phase_name : str
name of phase. Default is 'InterstateWeld'.
Returns
-------
gdf : geopandas.GeoDataFrame
updated streets dataframe
"""
# make restricted subset
restr_ss = gdf[gdf[net.attr1] == net.mtfcc_split]
try:
restr_names = [str(grp) for grp\
in restr_ss[net.mtfcc_split_grp].unique()]
except KeyError:
return gdf
# create a sub-subset for each group (e.g. interstate)
for grp in restr_names:
ss = restr_ss[restr_ss[net.mtfcc_split_grp]== grp]
# get restriction segments to restriction nodes lookup dict
# and restriction nodes to restriction segments lookup dict
s2n, n2s = associate(initial_weld=True, net=net, df=restr_ss, ss=ss)
# x2x topologies
s2s = get_neighbors(s2n, n2s, astype=dict)
n2n = get_neighbors(n2s, s2n, astype=dict)
# get rooted connected components
s2s_cc = get_roots(s2s)
# weld together segments from each component of the group
for cc in s2s_cc:
keep_id, all_ids = cc[0], cc[1]
drop_ids = copy.deepcopy(all_ids)
drop_ids.remove(keep_id)
# subset of specific segment to weld
weld_ss = ss[ss[net.attr2].isin(all_ids)]
weld = list(weld_ss.geometry)
weld = _weld_MultiLineString(weld, skip_restr=net.skip_restr)
# if the new segment if a LineString set the new, welded
# geometry to the `keep_id` index of the dataframe
if type(weld) == LineString:
index = weld_ss.loc[(weld_ss[net.attr2] == keep_id)].index[0]
gdf.loc[index, net.geo_col] = weld
gdf.loc[index, phase] = phase_name
# if the weld resulted in a MultiLineString remove ids from
# from `drop_ids` and set to new for each n+1 new segment.
if type(weld) == MultiLineString:
unique_segs = len(weld)
keeps_ids = [keep_id] + drop_ids[:unique_segs-1]
index = list(weld_ss[weld_ss[net.attr2].isin(keeps_ids)].index)
for idx, seg in enumerate(weld):
gdf.loc[index[idx], net.geo_col] = seg
gdf.loc[index, phase] = phase_name
for idx in keeps_ids:
if idx in drop_ids:
drop_ids.remove(idx)
# remove original segments used to create the new, welded
# segment(s) from the full segments dataframe
gdf = gdf[~gdf[net.attr2].isin(drop_ids)]
gdf.reset_index(inplace=True, drop=True)
if net.inter:
gdf.to_file(net.inter+phase_name+net.file_type)
return gdf
def check_cleanliness(net, df):
"""scan segments to determine cleanse_supercycle
needs to be run again
Parameters
----------
net : spaghetti.SpaghettiNetwork
df : geopandas.GeoDataFrame
dataframe of geometries
Returns
-------
cleaned : bool
False (repeat another cycle) or True
(all clean --> break out of loop)
"""
# equal geometry check
cleaned = streets_filter(net, df, equal_geom=True, scrub_check=True)
if not cleaned:
return cleaned
# contained geometry check
cleaned = streets_filter(net, df, contained_geom=True, scrub_check=True)
return cleaned
def line_splitter(net, df, proj_init=None, save_keep=None,
inherit_attrs=False, calc_len=False, stage=None,
road_type='MTFCC'):
"""top level function for spliting line segements
Parameters
----------
net : spaghetti.SpaghettiNetwork
df : geopandas.GeoDataFrame
dataframe of line segments to split
save_keep : str
path to save the shapefile. Default is None.
inherit_attrs : bool
inherit attributes from the dominant line segment.
Default is False.
calc_len : bool
calculated length and add column. Default is False.
stage : str
iteration of phase. Default is None.
road_type : str
column to use for grouping road types. Default is 'MTFCC'.
Returns
-------
split_lines : geopandas.GeoDataFrame
all line segments including unsplit lines
"""
# it `net.mtfcc_split` is string put it into a list
if not hasattr(net.mtfcc_split, '__iter__'):
net.mtfcc_split = [net.mtfcc_split]
# create subset of segments to split and not split
if net.mtfcc_split_by and net.mtfcc_split:
if type(net.mtfcc_split) == list:
subset_codes = net.mtfcc_split_by + net.mtfcc_split
elif type(net.mtfcc_split) == str:
subset_codes = net.mtfcc_split_by + [net.mtfcc_split]
non_subset = df[~df[road_type].isin(subset_codes)]
df = df[df[road_type].isin(subset_codes)]
if inherit_attrs:
drop_cols = [net.len_col, net.geo_col, net.xyid, 'ring']
attrs = [col for col in df.columns if not drop_cols.__contains__(col)]
attr_vals = {attr:[] for attr in attrs}
# Iterate over dataframe to find intersecting and split
split_lines = []
count_lines_split = 0
for loi_idx in df.index:
# Working with TIGER/Line *EDGES*
if net.mtfcc_split_by and net.mtfcc_split:
# if a line segment used for splitting
# but not to be split itself
if df[road_type][loi_idx] not in net.mtfcc_split:
split_lines.extend([df[net.geo_col][loi_idx]])
# fill dictionary with attribute values
if inherit_attrs:
for attr in attrs:
fill_val = [df[attr][loi_idx]]
if attr == 'Phase':
fill_val = ['Split'+stage]
attr_vals[attr].extend(fill_val)
continue
# get segs from the dataset that intersect
# with the Line Of Interest
intersecting = get_intersecting_geoms(net, df1=df, geom1=loi_idx,
wbool=False)
intersecting = intersecting[intersecting.index != loi_idx]
# Working with TIGER/Line *ROADS*
if not net.mtfcc_split_by and not net.mtfcc_split:
# if the LOI is an interstate only pass in
# the ramps for splitting
if df[road_type][loi_idx] == net.mtfcc_intrst:
intersecting = intersecting[\
(intersecting[road_type] == net.mtfcc_ramp)\
| (intersecting[road_type] == net.mtfcc_serv)\
| (intersecting[road_type] == net.mtfcc_intrst)]
# if LOI not ramp and interstates in dataframe
# filter them out
elif list(intersecting[road_type]).__contains__(net.mtfcc_intrst)\
and df[road_type][loi_idx] != net.mtfcc_ramp:
intersecting = intersecting[intersecting[road_type]\
!= net.mtfcc_intrst]
# if There are no intersecting segments
if intersecting.shape[0] == 0:
continue
# ring road bool
ring_road = literal_eval(df['ring'][loi_idx])
# actual line split call happens here
new_lines = _split_line(df[net.geo_col][loi_idx], loi_idx,
df=intersecting, ring_road=ring_road,
geo_col=net.geo_col)
n_lines = len(new_lines)
if n_lines > 1:
count_lines_split += 1
split_lines.extend(new_lines)
# fill dictionary with attribute values
if inherit_attrs:
for attr in attrs:
fill_val = [df[attr][loi_idx]]
if attr == 'Phase' and n_lines != 1:
fill_val = ['Split'+stage]
attr_vals[attr].extend(fill_val*n_lines)
# create dataframe
split_lines = gpd.GeoDataFrame(split_lines, columns=[net.geo_col])
# fill dataframe with attribute values
if inherit_attrs:
for attr in attrs:
split_lines[attr] = attr_vals[attr]
if proj_init:
split_lines = utils.set_crs(split_lines, proj_init=proj_init)
if calc_len:
split_lines = add_length(split_lines, len_col=net.len_col,
geo_col=net.geo_col)
# recombine EDGES subset and non subset segment lists
if net.mtfcc_split_by and net.mtfcc_split:
# combine newly split suset segments with all segments
split_lines = split_lines.append(non_subset, sort=False)
split_lines.reset_index(inplace=True, drop=True)
split_lines = add_ids(split_lines, id_name=net.sid_name)
# add updated xyid
segm2xyid = utils.generate_xyid(df=split_lines, geom_type='segm',
geo_col=net.geo_col)
split_lines = utils.fill_frame(split_lines, col=net.xyid, data=segm2xyid)
split_lines = label_rings(split_lines, geo_col=net.geo_col)
# number of lines split
net.lines_split = count_lines_split
if save_keep:
split_lines.to_file(save_keep+net.file_type)
return split_lines
def _split_line(loi, idx, df=None, geo_col=None, ring_road=False):
"""middle level function for spliting line segements
Parameters
----------
loi : shapely.LineString
line segment in question
idx : int
index number of the LOI
df : geopandas.GeoDataFrame
dataframe of line segments
ring_road : bool
(True) if ring road. (False) if not. Default is False.
geo_col : str
geometry column name. Default is None.
Returns
-------
newLines : list
list of new lines from one iteration of segment splitting
"""
intersectinglines = df[df.index != idx] # all lines not LOI
# Unary Union for intersection determination
intersectinglines = intersectinglines[geo_col].unary_union
# Intersections of LOI and the Unary Union
breaks = loi.intersection(intersectinglines)
# find and return points on the line to split if any exist
unaltered, breaks,\
ring_endpoint, basic_ring,\
complex_ring = _find_break_locs(loi=loi, breaks=breaks,
ring_road=ring_road)
if unaltered:
return unaltered
# Line breaking
if not type(breaks) == list:
breaks = [breaks]
new_lines = _create_split_lines(breaks=breaks, loi=loi,
ring_road=ring_road, basic_ring=basic_ring,
complex_ring=complex_ring,
ring_endpoint=ring_endpoint)
return new_lines
def _create_split_lines(breaks=None, ring_endpoint=None, loi=None,
ring_road=False, basic_ring=False, complex_ring=False):
"""deep function from splitting a single line segment
along break points
Parameters
----------
breaks : list
list of point to break a line along. Default is None.
ring_endpoint : shapely.Point
endpoint of a ring road. Default is None.
loi : shapely.LineString
line segment in question. Default is None.
ring_road : bool
is or is not a ring road. Default is False.
basic_ring : bool
is or is not a basic ring road. This indicates a 'normal' ring
road in which there is one endpoint. Default is False.
complex_ring : bool
is or is not a complex ring road. This indicates a any situation
not deemed a 'basic' ring. Default is False.
Returns
-------
new_lines : list
list of new lines generated from splitting
"""
points = [Point(xy) for xy in breaks]
# First coords of line
coords = list(loi.coords)
# Keep list coords where to cut (cuts = 1)
cuts = [0] * len(coords)
cuts[0] = 1
cuts[-1] = 1
# Add the coords from the points
coords += [list(p.coords)[0] for p in points]
cuts += [1] * len(points)
# Calculate the distance along the line for each point
dists = [loi.project(Point(p)) for p in coords]
# sort the coords/cuts based on the distances
# see http://stackoverflow.com/questions/6618515/
# sorting-list-based-on-values-from-another-list
coords = [p for (d, p) in sorted(zip(dists, coords))]
cuts = [p for (d, p) in sorted(zip(dists, cuts))]
if ring_road: # ensure there is an endpoint for rings
if basic_ring:
coords = ring_endpoint + coords + ring_endpoint
if complex_ring:
archetelos = [loi.coords[0]] # beginning and ending of ring
coords = archetelos + coords + archetelos
cuts = [1] + cuts + [1]
# generate the lines
if cuts[-1] != 1: # ensure there is an endpoint for rings
cuts += [1]