-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshape_it.py
299 lines (222 loc) · 8.78 KB
/
shape_it.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
import os
import sys
import argparse
import csv
import logging
from functools import partial
import json
from shapely.geometry import mapping, shape, Point, Polygon, MultiPoint
from shapely.wkt import dumps, loads
from shapely.ops import transform as stran
import fiona
from fiona.crs import from_epsg, from_string
from pyproj import Proj, transform
#setup logging
logging.basicConfig(filename='shape_it.log', format='%(asctime)s %(message)s', level=logging.DEBUG)
flog = logging.getLogger('Fiona')
flog.setLevel(logging.ERROR)
# setup the variables
code_3857 = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs'
proj_3857 = from_string(code_3857)
proj_4326 = from_epsg(4326)
p_in = Proj(proj_4326)
p_out = Proj(proj_3857)
# from_epsg(3857)
project = partial(transform, p_out, p_in)
output = "output"
IDX_PROGRESS = 0
class Within(object):
def __init__(self, o):
self.o = o
def __lt__(self, other):
return self.o['polygon'].within(other.o['polygon'])
def print_exit_message(msg):
print("\nUnable to process the file. \n Messages:\n")
print("=========================")
# print(" Shapefile generator ")
# print("=========================")
print(msg)
print("=========================")
print("\n")
sys.exit(1)
def check_output_directory():
if os.path.exists(output):
if os.path.isfile(output):
print_exit_message("Output folder already exists but is a file. Please delete it before proceeding.")
else:
print("Output folder already exists. Please rename or delete it before proceeding.")
return True
else:
os.mkdir(output)
return True
return False
def process_file_with_species_location(csvfile, spcol, lngcol, latcol):
global IDX_PROGRESS
logging.info("Processing file: %s" % csvfile)
print("Processing file: %s" % csvfile)
snlist = {}
with open(csvfile) as f:
reader = csv.DictReader(f, skipinitialspace=True)
for row in reader:
sciname = row[spcol]
coords = [float(row[lngcol]), float(row[latcol])]
if not snlist.has_key(sciname):
snlist[sciname] = []
snlist[sciname].append(coords)
IDX_PROGRESS = 0
for key in snlist:
IDX_PROGRESS += 1
update_progress(IDX_PROGRESS)
coords = snlist[key]
logging.debug("---------------------")
# Sort the coordinates so it's easier to match them
scoords = sorted(coords, key=lambda crd: crd[1])
scoords = sorted(scoords, key=lambda crd: crd[0])
logging.info('Processing species: %s', key)
if len(coords) > 1:
output_geoms = get_multi_polygons(scoords)
else:
output_geoms = get_single_polygon(scoords)
write_shapefile(key.replace(' ', '_'), output_geoms)
logging.debug("---------------------\n")
# clean up the progress bar
sys.stdout.write("\n")
print("Completed")
def process_file_with_latlon(csvfile, lngcol, latcol):
global IDX_PROGRESS
logging.info("Processing file: %s", csvfile)
print("Processing file: %s" % csvfile)
lyrname = os.path.basename(csvfile)
outfilename = os.path.splitext(lyrname)[0]
lyrname = outfilename
with open(csvfile) as f:
reader = csv.DictReader(f, skipinitialspace=True)
rows = list(reader)
coords = []
points = []
for i, row in enumerate(rows):
IDX_PROGRESS += 1
update_progress(IDX_PROGRESS)
coords.append([float(row[lngcol]), float(row[latcol])])
points.append(Point([float(row[lngcol]), float(row[latcol])]))
# Sort the coordinates so it's easier to match them
scoords = sorted(coords, key=lambda crd: crd[1])
scoords = sorted(scoords, key=lambda crd: crd[0])
output_geoms = get_multi_polygons(scoords)
write_shapefile(lyrname, output_geoms)
# clean up the progress bar
sys.stdout.write("\n")
print("Completed.\nCheck shape_it.log for additional details")
def get_single_polygon(coords):
global IDX_PROGRESS
logging.info("Processing %d points", len(coords))
polygons = [{
'polygon': MultiPoint([coords[0]]).convex_hull,
'coords': [coords[0]]
}]
return polygons
def get_multi_polygons(coords):
global IDX_PROGRESS
logging.info("Processing %d points", len(coords))
tcoords = coords
polygons = [{
'polygon': None,
'coords': []
}]
poly_coords = []
pts_coords = []
# 1. Take the first 2 set of coords and
# create a polygon if close <80km
# or create 2 polygons
c1 = tcoords[0]
c2 = tcoords[1]
if not is_feature_far(Point(c1), Point(c2)): # 0.720
polygons[0]['polygon'] = MultiPoint([c1, c2]).convex_hull
polygons[0]['coords'].append(c1)
polygons[0]['coords'].append(c2)
else:
polygons[0]['polygon'] = MultiPoint([c1]).convex_hull
polygons[0]['coords'].append(c1)
polygons.append({'polygon': MultiPoint([c2]).convex_hull, 'coords': [c2]})
# 2. Starting with the 3rd coord, check which polygon it falls in and add
# that point
for crd in tcoords[2:]:
IDX_PROGRESS += 1
update_progress(IDX_PROGRESS)
coord_added = False
for i, poly in enumerate(polygons):
pp = Point(crd[0], crd[1])
d = poly['polygon'].distance(pp) * 111.111
is_far = is_feature_far(poly['polygon'], pp)
if not is_far:
ecoords = poly['coords']
ecoords.append(crd)
poly['polygon'] = MultiPoint(ecoords).convex_hull
coord_added = True
break
if not coord_added:
polygons.append({'polygon': MultiPoint([crd]).convex_hull, 'coords': [crd]})
# 3. Check and merge any polygons that are <80km
polygons = check_and_merge_polygons(polygons)
logging.info("Generated buffered point")
return polygons
def check_and_merge_polygons(polygons):
global IDX_PROGRESS
logging.info('Check and sort...')
# if it's a single polygon, we are good
if len(polygons) == 1:
return polygons
spolys = sorted(polygons, key=Within)
out_polygons = [spolys[0]]
for poly in spolys[1:]:
IDX_PROGRESS += 1
update_progress(IDX_PROGRESS)
poly_merged = False
for idx, opoly in enumerate(out_polygons):
if not is_feature_far(opoly['polygon'], poly['polygon']):
opoly['coords'] = opoly['coords'] + poly['coords']
opoly['polygon'] = MultiPoint(opoly['coords'] + poly['coords']).convex_hull
poly_merged = True
if not poly_merged:
out_polygons.append(poly)
return out_polygons
def write_shapefile(lyrname, features):
logging.info("Writing layer: %s ", lyrname)
output_path = "%s/%s/" % (output, lyrname)
output_file = "%s/%s.shp" % (output_path, lyrname)
if not os.path.exists(output_path):
os.mkdir(output_path)
schema = {'geometry': 'Polygon', 'properties': {}}
with fiona.open(output_file, 'w', crs=proj_4326, driver='ESRI Shapefile', schema=schema) as out:
for feature in features:
feature['polygon'] = feature['polygon'].buffer(0.20)
out.write({
'properties': {},
'geometry': mapping(feature['polygon'])
})
logging.info("Generated polygon shapefile")
def is_feature_far(f1, f2, dist=80):
return (f1.distance(f2) * 111.111) > dist
def update_progress(iprg):
sys.stdout.write('\r[{0}]'.format('#'*(iprg/2)))
sys.stdout.flush()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate shapefiles')
# mandatory arguments
parser.add_argument("input", metavar="input", help="Input CSV file")
# optional arguments
parser.add_argument("-g", "--group", dest="group", default=None,
help="Group column, e.g. scientific name. Default: None.")
parser.add_argument("-lon", "--longitude", dest="lon", default='longitude',
help="Longitude column name, e.g. longitude. Default: longitude.")
parser.add_argument("-lat", "--latitude", dest="lat", default='latitude',
help="Latitude column name, e.g. latitude. Default: latitude.")
parser.add_argument("-o", "--output", dest="output", default=output,
help="Output directory. (default: ./output/)")
args = parser.parse_args()
output = args.output
if check_output_directory():
if args.group:
process_file_with_species_location(args.input, args.group, args.lon, args.lat)
else:
process_file_with_latlon(args.input, args.lon, args.lat)