r3.in.xyz.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: r3.in.xyz
  5. # AUTHOR: M. Hamish Bowman, Dunedin, New Zealand
  6. # PURPOSE: Run r.in.xyz in a loop for various z-levels and construct
  7. # a 3D raster. Unlike r.in.xyz, reading from stdin and z-scaling
  8. # won't work.
  9. #
  10. # COPYRIGHT: (c) 2011-2012 Hamish Bowman, and the GRASS Development Team
  11. # Port of r3.in.xyz(.sh) for GRASS 6.4.
  12. # This program is free software under the GNU General Public
  13. # License (>=v2). Read the file COPYING that comes with GRASS
  14. # for details.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. #############################################################################
  22. #%Module
  23. #% description: Create a 3D raster map from an assemblage of many coordinates using univariate statistics
  24. #% keywords: raster3d, import, voxel, LiDAR
  25. #%End
  26. #%Flag
  27. #% key: s
  28. #% description: Scan data file for extent then exit
  29. #%End
  30. #%Flag
  31. #% key: g
  32. #% description: In scan mode, print using shell script style
  33. #%End
  34. #%Flag
  35. #% key: i
  36. #% description: Ignore broken lines
  37. #%End
  38. #%Option
  39. #% key: input
  40. #% type: string
  41. #% required: yes
  42. #% multiple: no
  43. #% key_desc: name
  44. #% description: ASCII file containing input data
  45. #% gisprompt: old_file,file,input
  46. #%End
  47. #%Option
  48. #% key: output
  49. #% type: string
  50. #% required: yes
  51. #% multiple: no
  52. #% key_desc: name
  53. #% description: Name for output raster map
  54. #% gisprompt: new,grid3,3d-raster
  55. #%End
  56. #%Option
  57. #% key: method
  58. #% type: string
  59. #% required: no
  60. #% multiple: no
  61. #% options: n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean
  62. #% description: Statistic to use for raster values
  63. #% answer: mean
  64. #% guisection: Statistic
  65. #%End
  66. #%Option
  67. #% key: type
  68. #% type: string
  69. #% required: no
  70. #% multiple: no
  71. #% options: float,double
  72. #% description: Storage type for resultant raster map
  73. #% answer: float
  74. #%End
  75. #%Option
  76. #% key: fs
  77. #% type: string
  78. #% required: no
  79. #% multiple: no
  80. #% key_desc: character
  81. #% description: Field separator
  82. #% answer: |
  83. #% guisection: Input
  84. #%End
  85. #%Option
  86. #% key: x
  87. #% type: integer
  88. #% required: no
  89. #% multiple: no
  90. #% description: Column number of x coordinates in input file (first column is 1)
  91. #% answer: 1
  92. #% guisection: Input
  93. #%End
  94. #%Option
  95. #% key: y
  96. #% type: integer
  97. #% required: no
  98. #% multiple: no
  99. #% description: Column number of y coordinates in input file
  100. #% answer: 2
  101. #% guisection: Input
  102. #%End
  103. #%Option
  104. #% key: z
  105. #% type: integer
  106. #% required: no
  107. #% multiple: no
  108. #% description: Column number of z coordinates in input file
  109. #% answer: 3
  110. #% guisection: Input
  111. #%End
  112. #%Option
  113. #% key: value_column
  114. #% type: integer
  115. #% required: no
  116. #% multiple: no
  117. #% label: Column number of data values in input file
  118. #% description: If not given or set to 0, the data points' z-values are used
  119. #% answer: 0
  120. #% guisection: Input
  121. #%End
  122. #%Option
  123. #% key: vrange
  124. #% type: double
  125. #% required: no
  126. #% key_desc: min,max
  127. #% description: Filter range for value column data (min,max)
  128. #%End
  129. #%option
  130. #% key: vscale
  131. #% type: double
  132. #% required: no
  133. #% multiple: no
  134. #% description: Scaling factor to apply to value column data
  135. #% answer: 1.0
  136. #%end
  137. #%Option
  138. #% key: percent
  139. #% type: integer
  140. #% required: no
  141. #% multiple: no
  142. #% options: 1-100
  143. #% description: Percent of map to keep in memory
  144. #% answer: 100
  145. #%End
  146. #%Option
  147. #% key: pth
  148. #% type: integer
  149. #% required: no
  150. #% multiple: no
  151. #% options: 1-100
  152. #% description: pth percentile of the values
  153. #% guisection: Statistic
  154. #%End
  155. #%Option
  156. #% key: trim
  157. #% type: double
  158. #% required: no
  159. #% multiple: no
  160. #% options: 0-50
  161. #% description: Discard <trim> percent of the smallest and <trim> percent of the largest observations
  162. #% guisection: Statistic
  163. #%End
  164. #%Option
  165. #% key: workers
  166. #% type: integer
  167. #% required: no
  168. #% multiple: no
  169. #% options: 1-256
  170. #% answer: 1
  171. #% description: Number of parallel processes to launch
  172. #%End
  173. import sys
  174. import os
  175. import atexit
  176. from grass.script import core as grass
  177. def cleanup():
  178. grass.run_command('g.mremove', flags = 'f',
  179. rast = 'tmp.r3xyz.%d.*' % os.getpid(),
  180. quiet = True)
  181. def main():
  182. infile = options['input']
  183. output = options['output']
  184. method = options['method']
  185. dtype = options['type']
  186. fs = options['fs']
  187. x = options['x']
  188. y = options['y']
  189. z = options['z']
  190. value_column = options['value_column']
  191. vrange = options['vrange']
  192. vscale = options['vscale']
  193. percent = options['percent']
  194. pth = options['pth']
  195. trim = options['trim']
  196. workers = int(options['workers'])
  197. scan_only = flags['s']
  198. shell_style = flags['g']
  199. ignore_broken = flags['i']
  200. if workers is 1 and "WORKERS" in os.environ:
  201. workers = int(os.environ["WORKERS"])
  202. if not os.path.exists(infile):
  203. grass.fatal(_("Unable to read input file <%s>") % infile)
  204. addl_opts = {}
  205. if pth:
  206. addl_opts['pth'] = '%s' % pth
  207. if trim:
  208. addl_opts['trim'] = '%s' % trim
  209. if value_column:
  210. addl_opts['value_column'] = '%s' % value_column
  211. if vrange:
  212. addl_opts['vrange'] = '%s' % vrange
  213. if vscale:
  214. addl_opts['vscale'] = '%s' % vscale
  215. if ignore_broken:
  216. addl_opts['flags'] = 'i'
  217. if scan_only or shell_style:
  218. if shell_style:
  219. doShell = 'g'
  220. else:
  221. doShell = ''
  222. grass.run_command('r.in.xyz', flags = 's' + doShell, input = infile,
  223. output = 'dummy', fs = fs, x = x, y = y, z = z,
  224. **addl_opts)
  225. sys.exit()
  226. if dtype is 'float':
  227. data_type = 'FCELL'
  228. else:
  229. data_type = 'DCELL'
  230. region = grass.region(region3d = True)
  231. if region['nsres'] != region['nsres3'] or region['ewres'] != region['ewres3']:
  232. grass.run_command('g.region', flags = '3p')
  233. grass.fatal(_("The 2D and 3D region settings are different. Can not continue."))
  234. grass.verbose(_("Region bottom=%.15g top=%.15g vertical_cell_res=%.15g (%d depths)")
  235. % (region['b'], region['t'], region['tbres'], region['depths']))
  236. grass.verbose(_("Creating slices ..."))
  237. # to avoid a point which falls exactly on a top bound from being
  238. # considered twice, we shrink the
  239. # For the top slice we keep it though, as someone scanning the bounds
  240. # may have set the bounds exactly to the data extent (a bad idea, but
  241. # it happens..)
  242. eps = 1.0e-15
  243. # if there are thousands of depths hopefully this array doesn't get too
  244. # large and so we don't have to worry much about storing/looping through
  245. # all the finished process infos.
  246. proc = {}
  247. pout = {}
  248. depths = range(1, 1 + region['depths'])
  249. for i in depths:
  250. tmp_layer_name = 'tmp.r3xyz.%d.%s' % (os.getpid(), '%05d' % i)
  251. zrange_min = region['b'] + (region['tbres'] * (i-1))
  252. if i < region['depths']:
  253. zrange_max = region['b'] + (region['tbres'] * i) - eps
  254. else:
  255. zrange_max = region['b'] + (region['tbres'] * i)
  256. # spawn depth layerimport job in the background
  257. #grass.debug("slice %d, <%s> %% %d" % (band, image[band], band % workers))
  258. grass.message(_("Processing horizontal slice %d of %d [%.15g,%.15g) ...")
  259. % (i, region['depths'], zrange_min, zrange_max))
  260. proc[i] = grass.start_command('r.in.xyz', input = infile, output = tmp_layer_name,
  261. fs = fs, method = method, x = x, y = y, z = z,
  262. percent = percent, type = data_type,
  263. zrange = '%.15g,%.15g' % (zrange_min, zrange_max),
  264. **addl_opts)
  265. grass.debug("i=%d, %%=%d (workers=%d)" % (i, i % workers, workers))
  266. #print sys.getsizeof(proc) # sizeof(proc array) [not so big]
  267. if i % workers is 0:
  268. # wait for the ones launched so far to finish
  269. for p_i in depths[:i]:
  270. pout[p_i] = proc[p_i].communicate()[0]
  271. if proc[p_i].wait() is not 0:
  272. grass.fatal(_("Trouble importing data. Aborting."))
  273. # wait for jSobs to finish, collect any stray output
  274. for i in depths:
  275. pout[i] = proc[i].communicate()[0]
  276. if proc[i].wait() is not 0:
  277. grass.fatal(_("Trouble importing data. Aborting."))
  278. del proc
  279. grass.verbose(_("Assembling 3D cube ..."))
  280. #input order: lower most strata first
  281. slices = grass.read_command('g.mlist', type = 'rast', fs = ',',
  282. pattern = 'tmp.r3xyz.%d.*' % os.getpid()).rstrip('\n')
  283. grass.debug(slices)
  284. if grass.run_command('r.to.rast3', input = slices, output = output) is 0:
  285. grass.message(_("Done. 3D raster map <%s> created.") % output)
  286. if __name__ == "__main__":
  287. options, flags = grass.parser()
  288. atexit.register(cleanup)
  289. main()