-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathutils.py
More file actions
executable file
·332 lines (234 loc) · 10.7 KB
/
Copy pathutils.py
File metadata and controls
executable file
·332 lines (234 loc) · 10.7 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import multiprocessing
import math
import os
# import platform
import psycopg
import subprocess
# import sys
# calculates the area tolerance (in m2) for vector simplification using the Visvalingam-Whyatt algorithm
def get_tolerance(zoom_level):
# pixels squared factor
tolerance_square_pixels = 7
# default Google/Bing map tile scales
metres_per_pixel = 156543.03390625 / math.pow(2.0, float(zoom_level + 1))
# the tolerance (metres) for vector simplification using the VW algorithm
square_metres_per_pixel = math.pow(metres_per_pixel, 2.0)
# tolerance to use
tolerance = square_metres_per_pixel * tolerance_square_pixels
return tolerance
# maximum number of decimal places for boundary coordinates - improves display performance
def get_decimal_places(zoom_level):
# rough metres to degrees conversation, using spherical WGS84 datum radius for simplicity and speed
metres2degrees = (2.0 * math.pi * 6378137.0) / 360.0
# default Google/Bing map tile scales
metres_per_pixel = 156543.03390625 / math.pow(2.0, float(zoom_level))
# the tolerance for thinning data and limiting decimal places in GeoJSON responses
degrees_per_pixel = metres_per_pixel / metres2degrees
scale_string = "{:10.9f}".format(degrees_per_pixel).split(".")[1]
places = 1
trigger = "0"
# find how many zero decimal places there are. e.g. 0.00001234 = 4 zeros
for c in scale_string:
if c == trigger:
places += 1
else:
trigger = "don't do anything else" # used to cleanly exit the loop
return places
# takes a list of sql queries or command lines and runs them using multiprocessing
def multiprocess_csv_import(work_list, max_concurrent_processes, pg_connect_string,
data_schema, pg_user, region_id_field, logger):
pool = multiprocessing.Pool(processes=max_concurrent_processes)
num_jobs = len(work_list)
results = pool.imap_unordered(run_csv_import_multiprocessing,
[[w, pg_connect_string, data_schema, pg_user, region_id_field] for w in work_list])
pool.close()
pool.join()
result_list = list(results)
num_results = len(result_list)
if num_jobs > num_results:
logger.warning("\t- A MULTIPROCESSING PROCESS FAILED WITHOUT AN ERROR\nACTION: Check the record counts")
for result in result_list:
if result != "SUCCESS":
logger.info(result)
def run_csv_import_multiprocessing(args):
file_dict = args[0]
pg_connect_string = args[1]
data_schema = args[2]
pg_user = args[3]
region_id_field = args[4]
pg_conn = psycopg.connect(pg_connect_string)
pg_conn.autocommit = True
pg_cur = pg_conn.cursor()
# CREATE TABLE
# get the census fields to use in the create table statement
field_list = list()
# select the field ordered by sequential_id (required to match field names with the right data)
sql = f"""SELECT sequential_id || ' double precision' AS field
FROM {data_schema}.metadata_stats
WHERE lower(table_number) LIKE '{file_dict["table"]}%'
ORDER BY table_number, right(sequential_id, length(sequential_id) - 1)::integer"""
pg_cur.execute(sql)
fields = pg_cur.fetchall()
for field in fields:
field_list.append(field[0].lower())
fields_string = ",".join(field_list)
# create the table
table_name = file_dict["boundary"] + "_" + file_dict["table"]
create_table_sql = f"""DROP TABLE IF EXISTS {data_schema}.{table_name} CASCADE;
CREATE TABLE {data_schema}.{table_name} (
{region_id_field} text,
{fields_string}
) WITH (OIDS=FALSE);
ALTER TABLE {data_schema}.{table_name} OWNER TO {pg_user}"""
pg_cur.execute(create_table_sql)
# IMPORT CSV FILE
try:
# read CSV into a string
raw_string = open(file_dict["path"], 'r').read()
# clean whitespace and rogue non-ascii characters
clean_string = raw_string.lstrip().rstrip().replace(" ", "").replace("\x1A", "")
# convert to in memory stream
csv_file = io.StringIO(clean_string)
csv_file.seek(0) # move position back to beginning of file before reading
# import into Postgres
sql = f"COPY {data_schema}.{table_name} FROM stdin WITH CSV HEADER DELIMITER as ',' NULL as '..'"
with pg_cur.copy(sql) as copy:
while data := csv_file.read():
copy.write(data)
except Exception as ex:
return f"IMPORT CSV INTO POSTGRES FAILED! : {file_dict['path']} : {ex}"
# add primary key and vacuum index
sql = f"""ALTER TABLE {data_schema}.{table_name} ADD CONSTRAINT {table_name}_pkey PRIMARY KEY ({region_id_field});
ALTER TABLE {data_schema}.{table_name} CLUSTER ON {table_name}_pkey"""
pg_cur.execute(sql)
pg_cur.execute(f"VACUUM ANALYSE {data_schema}.{table_name}")
result = "SUCCESS"
pg_cur.close()
pg_conn.close()
return result
# takes a list of sql queries or command lines and runs them using multiprocessing
def multiprocess_list(mp_type, work_list, max_concurrent_processes, pg_connect_string, logger):
pool = multiprocessing.Pool(processes=max_concurrent_processes)
num_jobs = len(work_list)
if mp_type == "sql":
results = pool.imap_unordered(run_sql_multiprocessing, [[w, pg_connect_string] for w in work_list])
else:
results = pool.imap_unordered(run_command_line, work_list)
pool.close()
pool.join()
result_list = list(results)
num_results = len(result_list)
if num_jobs > num_results:
logger.warning("\t- A MULTIPROCESSING PROCESS FAILED WITHOUT AN ERROR\nACTION: Check the record counts")
for result in result_list:
if result != "SUCCESS":
logger.info(result)
def run_sql_multiprocessing(args):
the_sql = args[0]
pg_connect_string = args[1]
pg_conn = psycopg.connect(pg_connect_string)
pg_conn.autocommit = True
pg_cur = pg_conn.cursor()
# # set raw gnaf database schema (it's needed for the primary and foreign key creation)
# if raw_gnaf_schema != "public":
# pg_cur.execute(f"SET search_path = {raw_gnaf_schema}, public, pg_catalog")
try:
pg_cur.execute(the_sql)
result = "SUCCESS"
except Exception as ex:
result = f"SQL FAILED! : {the_sql} : {ex}"
pg_cur.close()
pg_conn.close()
return result
def run_command_line(cmd):
# run the command line without any output (it'll still tell you if it fails miserably)
try:
fnull = open(os.devnull, "w")
subprocess.call(cmd, shell=True, stdout=fnull, stderr=subprocess.STDOUT)
result = "SUCCESS"
except Exception as ex:
result = f"COMMAND FAILED! : {cmd} : {ex}"
return result
def multiprocess_shapefile_load(work_list, max_concurrent_processes, pg_connect_string, logger):
pool = multiprocessing.Pool(processes=max_concurrent_processes)
num_jobs = len(work_list)
results = pool.imap_unordered(intermediate_shapefile_load_step,
[[w, pg_connect_string] for w in work_list])
pool.close()
pool.join()
result_list = list(results)
num_results = len(result_list)
if num_jobs > num_results:
logger.warning("\t- A MULTIPROCESSING PROCESS FAILED WITHOUT AN ERROR\nACTION: Check the record counts")
for result in result_list:
if result != "SUCCESS":
logger.info(result)
def intermediate_shapefile_load_step(args):
work_dict = args[0]
pg_connect_string = args[1]
# logger = args[2]
file_path = work_dict["file_path"]
pg_table = work_dict["pg_table"]
pg_schema = work_dict["pg_schema"]
delete_table = work_dict["delete_table"]
spatial = work_dict["spatial"]
pg_conn = psycopg.connect(pg_connect_string)
pg_conn.autocommit = True
pg_cur = pg_conn.cursor()
result = import_shapefile_to_postgres(pg_cur, file_path, pg_table, pg_schema, delete_table, spatial)
return result
# imports a Shapefile into Postgres in 2 steps: SHP > SQL; SQL > Postgres
# overcomes issues trying to use psql with PGPASSWORD set at runtime
def import_shapefile_to_postgres(pg_cur, file_path, pg_table, pg_schema, delete_table, spatial):
# delete target table or append to it?
if delete_table:
delete_append_flag = "-d"
else:
delete_append_flag = "-a"
# assign coordinate system if spatial, otherwise flag as non-spatial
if spatial:
spatial_or_dbf_flags = "-s 4283 -I"
else:
spatial_or_dbf_flags = "-G -n"
# build shp2pgsql command line
shp2pgsql_cmd = f"shp2pgsql {delete_append_flag} {spatial_or_dbf_flags} -i \"{file_path}\" {pg_schema}.{pg_table}"
# print(shp2pgsql_cmd)
# convert the Shapefile to SQL statements
try:
process = subprocess.Popen(shp2pgsql_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
sql_obj, err = process.communicate()
except:
return f"Importing {file_path} - Couldn't convert Shapefile to SQL"
# print(f"SQL object is this long: {len(sql_obj)}")
# print(f"Error is: {err}")
# prep Shapefile SQL
sql = sql_obj.decode("utf-8") # this is required for Python 3
sql = sql.replace("Shapefile type: ", "-- Shapefile type: ")
sql = sql.replace("Postgis type: ", "-- Postgis type: ")
sql = sql.replace("SELECT DropGeometryColumn", "-- SELECT DropGeometryColumn")
# bug in shp2pgsql? - an append command will still create a spatial index if requested - disable it
if not delete_table or not spatial:
sql = sql.replace("CREATE INDEX ", "-- CREATE INDEX ")
# this is required due to differing approaches by different versions of PostGIS
sql = sql.replace("DROP TABLE ", "DROP TABLE IF EXISTS ")
sql = sql.replace("DROP TABLE IF EXISTS IF EXISTS ", "DROP TABLE IF EXISTS ")
# import data to Postgres
try:
pg_cur.execute(sql)
except:
# if import fails for some reason - output sql to file for debugging
target = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), f"fail_{pg_table}.sql"), "w")
target.write(sql)
return f"\tImporting {file_path} - Couldn't run Shapefile SQL\nshp2pgsql result was: {err} "
# Cluster table on spatial index for performance
if delete_table and spatial:
sql = f"ALTER TABLE {pg_schema}.{pg_table} CLUSTER ON {pg_table}_geom_idx"
try:
pg_cur.execute(sql)
except:
return f"\tImporting {pg_table} - Couldn't cluster on spatial index"
return "SUCCESS"
# print(get_tolerance(13))