-
Notifications
You must be signed in to change notification settings - Fork 7
/
calc_density_tiles.py
executable file
·235 lines (187 loc) · 7.69 KB
/
calc_density_tiles.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
import argparse
import logging
import os
import sys
from datetime import *
from osgeo import osr, ogr
from lib import dem, taskhandler, VERSION, SHORT_VERSION, utils
#### Create Logger
logger = logging.getLogger("logger")
logger.setLevel(logging.DEBUG)
ogrDriver = ogr.GetDriverByName("ESRI Shapefile")
tgt_srs = osr.SpatialReference()
tgt_srs.ImportFromEPSG(4326)
submission_script_map = {
'pbs': 'pbs_package.sh',
'slurm': 'slurm_package.sh'
}
def main():
#### Set Up Arguments
parser = argparse.ArgumentParser(
description="calculate density for setsm tile or subtile DEMS and save to a density.txt file"
)
#### Positional Arguments
parser.add_argument('src', help="source directory or dem")
parser.add_argument('scratch', help="scratch space")
#### Optionsl Arguments
parser.add_argument('-v', action='store_true', default=False, help="verbose output")
parser.add_argument('--dryrun', action='store_true', default=False,
help="print actions without executing")
parser.add_argument('--version', action='version', version=f"Current version: {SHORT_VERSION}",
help='print version and exit')
pos_arg_keys = ['src', 'scratch']
arg_keys_to_remove = utils.SCHEDULER_ARGS + ['dryrun']
utils.add_scheduler_options(parser, submission_script_map, include_tasks_per_job=True)
#### Parse Arguments
scriptpath = os.path.abspath(sys.argv[0])
args = parser.parse_args()
src = os.path.abspath(args.src)
scratch = os.path.abspath(args.scratch)
#### Verify Arguments
if not os.path.isdir(args.src) and not os.path.isfile(args.src):
parser.error("Source directory or file does not exist: %s" %args.src)
if not os.path.isdir(args.scratch) and not args.scheduler: #scratch dir may not exist on head node when running jobs via pbs
parser.error("Scratch directory does not exist: %s" %args.scratch)
## Verify qsubscript
qsubpath = utils.verify_scheduler_args(parser, args, scriptpath, submission_script_map)
if args.v:
log_level = logging.DEBUG
else:
log_level = logging.INFO
lsh = logging.StreamHandler()
lsh.setLevel(log_level)
formatter = logging.Formatter('%(asctime)s %(levelname)s- %(message)s','%m-%d-%Y %H:%M:%S')
lsh.setFormatter(formatter)
logger.addHandler(lsh)
logger.info("Current version: %s", VERSION)
#### Get args ready to pass to task handler
arg_str_base = taskhandler.convert_optional_args_to_string(args, pos_arg_keys, arg_keys_to_remove)
j=0
scenes = []
#### ID rasters
logger.info('Identifying DEMs')
if os.path.isfile(src) and src.endswith('.tif'):
logger.debug(src)
try:
raster = dem.SetsmTile(src)
except RuntimeError as e:
logger.error( e )
else:
j+=1
if not os.path.isfile(raster.density_file):
scenes.append(src)
elif os.path.isfile(src) and src.endswith('.txt'):
fh = open(src,'r')
for line in fh.readlines():
sceneid = line.strip()
try:
raster = dem.SetsmTile(sceneid)
except RuntimeError as e:
logger.error( e )
else:
j+=1
if not os.path.isfile(raster.density_file):
scenes.append(sceneid)
elif os.path.isdir(src):
for root,dirs,files in os.walk(src):
for f in files:
if f.endswith("_dem.tif") and "m_" in f:
srcfp = os.path.join(root,f)
logger.debug(srcfp)
try:
raster = dem.SetsmTile(srcfp)
except RuntimeError as e:
logger.error( e )
else:
j+=1
if not os.path.isfile(raster.density_file):
scenes.append(srcfp)
else:
logger.error( "src must be a directory, a strip dem, or a text file")
scenes = list(set(scenes))
logger.info('Number of src rasters: {}'.format(j))
logger.info('Number of incomplete tasks: {}'.format(len(scenes)))
tm = datetime.now()
job_count=0
scene_count=0
scenes_in_job_count=0
task_queue = []
for srcfp in scenes:
scene_count+=1
srcdir, srcfn = os.path.split(srcfp)
if args.tasks_per_job:
# bundle tasks into text files in the dst dir and pass the text file in as src
scenes_in_job_count+=1
src_txt = os.path.join(scratch,'src_dems_{}_{}.txt'.format(tm.strftime("%Y%m%d%H%M%S"),job_count))
if scenes_in_job_count == 1:
# remove text file if dst already exists
try:
os.remove(src_txt)
except OSError:
pass
if scenes_in_job_count <= args.tasks_per_job:
# add to txt file
fh = open(src_txt,'a')
fh.write("{}\n".format(srcfp))
fh.close()
if scenes_in_job_count == args.tasks_per_job or scene_count == len(scenes):
scenes_in_job_count=0
job_count+=1
task = taskhandler.Task(
'Dens{:04g}'.format(job_count),
'Dens{:04g}'.format(job_count),
'python',
'{} {} {} {}'.format(scriptpath, arg_str_base, src_txt, scratch),
build_archive,
[srcfp, scratch, args]
)
task_queue.append(task)
else:
job_count += 1
task = taskhandler.Task(
srcfn,
'Dens{:04g}'.format(job_count),
'python',
'{} {} {} {}'.format(scriptpath, arg_str_base, srcfp, scratch),
build_archive,
[srcfp, scratch, args]
)
task_queue.append(task)
if len(task_queue) > 0:
logger.info("Submitting Tasks")
if args.scheduler:
try:
task_handler = taskhandler.get_scheduler_taskhandler(args.scheduler, qsubpath)
except RuntimeError as e:
logger.error(e)
else:
if not args.dryrun:
task_handler.run_tasks(task_queue)
elif args.parallel_processes > 1:
task_handler = taskhandler.ParallelTaskHandler(args.parallel_processes)
logger.info("Number of child processes to spawn: {0}".format(task_handler.num_processes))
if not args.dryrun:
task_handler.run_tasks(task_queue)
else:
for task in task_queue:
src, scratch, task_arg_obj = task.method_arg_list
if not args.dryrun:
task.method(src, scratch, task_arg_obj)
else:
logger.info("No tasks found to process")
def build_archive(src,scratch,args):
logger.info("Calculating density of raster: {}".format(src))
raster = dem.SetsmTile(src)
try:
raster.get_dem_info()
except RuntimeError as e:
logger.error(e)
else:
## get raster density if not precomputed
if raster.density is None:
try:
raster.compute_density_and_statistics()
except RuntimeError as e:
logger.warning(e)
if __name__ == '__main__':
main()