r3.in.xyz.py 8.9 KB

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