r3.in.xyz.py 8.8 KB

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