-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
369 lines (305 loc) · 9.77 KB
/
utils.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Utils
A QGIS plugin
Computes ecological continuities based on environments permeability
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2018-04-12
git sha : $Format:%H$
copyright : (C) 2018 by IRSTEA
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
"""
Utility functions independent from QGIS API.
"""
import datetime
import os.path
import pathlib
import sys
import subprocess
import time
import html
import platform
import glob
import csv
import re
file_dir = os.path.dirname(__file__)
if file_dir not in sys.path:
sys.path.append(file_dir)
# STRING UTILITIES
def isValidTag(tag):
valid = re.match('^[\w_-]+$', tag) is not None
return valid
# LOG UTILITIES
def printLine(msg):
print(msg + "\n")
def doNothing(msg):
pass
debug_flag=True
print_func = printLine
#print_func = doNothing
curr_language = "fr"
dialog_base_dir = None
platform_sys = platform.system()
class CustomException(Exception):
def __init__(self, message):
super().__init__(message)
class UserError(Exception):
def __init__(self, message):
super().__init__(message)
class InternalError(Exception):
def __init__(self, message):
super().__init__(message)
class TodoError(Exception):
def __init__(self, message):
super().__init__(message)
def printDate(msg):
date_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print_func ("[" + date_str + "] " + msg)
def debug(msg):
if debug_flag:
printDate("<font color=\"gray\">[debug] " + msg + "</font>")
def info(msg):
printDate("<font color=\"black\">[info] " + msg + "</font>")
def warn(msg):
printDate("<font color=\"orange\">[warn] " + msg + "</font>")
def mkBoldRed(msg):
return "<b><font color=\"red\">" + msg + "</font></b>"
def error_msg(msg,prefix=""):
printDate(mkBoldRed("[" + prefix + "] " + msg))
def user_error(msg):
raise UserError(msg)
# error_msg(msg,"user error")
# raise CustomException(msg)
def internal_error(msg):
raise InternalError(msg)
# error_msg(msg,"internal error")
# raise CustomException(msg)
def todo_error(msg):
raise TodoError(msg)
# error_msg(msg,"Feature not yet implemented")
# raise CustomException(msg)
class Section:
def __init__(self,title,prefix=">>>>"):
self.title = title
self.prefix = prefix
def start_section(self):
self.start_time = time.time()
info(self.prefix + " Start " + self.title)
def end_section(self):
info(self.prefix + " End " + self.title)
self.end_time = time.time()
diff_time = self.end_time - self.start_time
info(self.title + " finished in " + str(diff_time) + " seconds")
# FILE UTILITIES
def normPath(fname):
p = pathlib.Path(fname)
pp = p.as_posix()
return pp
#return fname.replace('\\','/')
def joinPath(p1,p2):
pp1 = pathlib.Path(p1)
res = pp1.joinpath(p2)
return res.as_posix()
def mkDir(dirname):
if not os.path.isdir(dirname):
info("Creating directory '" + dirname + "'")
os.makedirs(dirname)
return dirname
def createSubdir(par_dir,name):
path = joinPath(par_dir,name)
return mkDir(path)
def pathEquals(p1,p2):
if p1 and p2:
p1_parts = pathlib.Path(p1).parts
p2_parts = pathlib.Path(p2).parts
return (p1 == p2)
else:
return False
def fileExists(fname,prefix=""):
if not fname:
return False
path = pathlib.Path(fname)
if not path.exists():
return False
if not (os.path.isfile(fname)):
return False
return True
def checkFileExists(fname,prefix=""):
path = pathlib.Path(fname)
debug("path = " + str(path))
debug("pathparts = " + str(path.parts))
if not path.exists():
user_error("path does not exist : " + str(path))
if not fname:
user_error(prefix + " File not selected")
if not (os.path.isfile(fname)):
user_error(prefix + "File '" + fname + "' does not exist")
def removeFile(path):
if os.path.isfile(path):
debug("Deleting existing file '" + path + "'")
os.remove(path)
def writeFile(fname,str):
with open(fname,"w",encoding="utf-8") as f:
f.write(str)
def parseAssocFileCSV(fname,fieldnames):
res = {}
if os.path.isfile(fname):
with open(fname,newline='') as csvfile:
reader = csv.DictReader(csvfile,fieldnames=fieldnames,delimiter=';')
for row in reader:
try:
model, eff = row['Modele'], float(row['Eff'])
if model:
res[model] = eff
except ValueError:
user_error("Could not parse " + str(row))
except TypeError:
user_error("Could not parse " + str(row))
else:
raise Exception("File " + str(fname) + " does not exist")
return res
# PATH UTILITIES
def mkTmpPath(path,suffix="_tmp"):
bn,extension = os.path.splitext(path)
return (bn + suffix + extension)
def fromTmpPath(tmp_path):
bn, extension = os.path.splitext(path)
return (bn[:-4] + extension)
def findFilesFromDir(dir,fname):
regexp = dir + "/**/" + fname
glob_res = glob.glob(regexp,recursive=True)
return glob_res
def findFileFromDir(dir,fname):
#if dir.endsWith('/'):
if False:
regexp = dir + "**/" + fname
else:
regexp = dir + "/**/" + fname
glob_res = glob.glob(regexp,recursive=True)
nb_res = len(glob_res)
if nb_res == 0:
user_error("No file '" + fname + "' found in directory '" + dir + "'")
else:
res = glob_res[0]
debug("Found " + str(nb_res) + " files named '" + fname + "' in directory '" + dir + "'")
return res
# TYPE UTILITIES
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def is_integer(s):
try:
int(s)
return True
except ValueError:
return False
def castVal(v):
if v is None or v == "None":
newVal = None
elif v in ["True","False"]:
newVal = eval(v)
elif v.isnumeric():
newVal = int(v)
else:
try:
newVal = float(v)
except ValueError:
newVal = v
return newVal
def castDict(d):
res = {}
for k,v in d.items():
newVal = castVal(v)
res[k] = newVal
return res
# Validity checkers
def checkFields(ref_fields,fields):
if ref_fields != fields:
for rf in ref_fields:
if rf not in fields:
user_error("Missing field '" + rf + "' in " + str(fields))
def checkDictField(item,fieldname,prefix=None):
if prefix == None:
prefix = item.__class__.name
if not item.dict[fieldname]:
user_error(prefix + " with empty name '" + str(item.dict[fieldname]) + "'")
def checkName(item,prefix=None):
checkDictField(item,"name",prefix)
def checkDescr(item,prefix=None):
if prefix == None:
prefix = item.__class__.name
if not item.dict["descr"]:
if "name" in item.dict:
name = " " + str(item.dict["name"])
else:
name = " "
warn(prefix + name + " with empty description")
# Subprocess utils
def checkCmd(cmd):
try:
subprocess.call([cmd])
except FileNotFoundError:
raise UserError("Command " + str(cmd) + " does not exist")
def executeCmd(cmd_args):
debug("command = " + str(cmd_args))
p = subprocess.Popen(cmd_args,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
out,err = p.communicate()
debug(str(p.args))
if out:
info(str(out))
if err:
if "invalid value encountered in less" in str(err):
warn(str(err))
else:
user_error(str(err))
def executeCmdAsScript(cmd_args):
debug("executeCmdAsScript")
new_args = [sys.executable] + cmd_args
debug(str(new_args))
ret = subprocess.call(new_args)
debug("return code = " + str(ret))
# Misc
def getIntValues(nb_values,start=1,exclude_values=[]):
cpt = 0
currVal = start
res = []
while cpt < nb_values:
if currVal not in exclude_values:
res.append(currVal)
cpt += 1
currVal += 1
return res
# Import checks
def scipyIsInstalled():
try:
import scipy
# from scipy import ndimage
import_scipy_ok = True
except ImportError as e:
import_scipy_ok = False
return import_scipy_ok
def numpyIsInstalled():
try:
import numpy
# from scipy import ndimage
import_numpy_ok = True
except ImportError as e:
import_numpy_ok = False
return import_numpy_ok