r3.in.xyz.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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
  25. #% keywords: import
  26. #% keywords: voxel
  27. #% keywords: 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. def cleanup():
  176. grass.run_command('g.mremove', flags = 'f',
  177. type = "rast", pattern = 'tmp.r3xyz.%d.*' % os.getpid(),
  178. quiet = True)
  179. def main():
  180. infile = options['input']
  181. output = options['output']
  182. method = options['method']
  183. dtype = options['type']
  184. fs = options['separator']
  185. x = options['x']
  186. y = options['y']
  187. z = options['z']
  188. value_column = options['value_column']
  189. vrange = options['vrange']
  190. vscale = options['vscale']
  191. percent = options['percent']
  192. pth = options['pth']
  193. trim = options['trim']
  194. workers = int(options['workers'])
  195. scan_only = flags['s']
  196. shell_style = flags['g']
  197. ignore_broken = flags['i']
  198. if workers is 1 and "WORKERS" in os.environ:
  199. workers = int(os.environ["WORKERS"])
  200. if not os.path.exists(infile):
  201. grass.fatal(_("Unable to read input file <%s>") % infile)
  202. addl_opts = {}
  203. if pth:
  204. addl_opts['pth'] = '%s' % pth
  205. if trim:
  206. addl_opts['trim'] = '%s' % trim
  207. if value_column:
  208. addl_opts['value_column'] = '%s' % value_column
  209. if vrange:
  210. addl_opts['vrange'] = '%s' % vrange
  211. if vscale:
  212. addl_opts['vscale'] = '%s' % vscale
  213. if ignore_broken:
  214. addl_opts['flags'] = 'i'
  215. if scan_only or shell_style:
  216. if shell_style:
  217. doShell = 'g'
  218. else:
  219. doShell = ''
  220. grass.run_command('r.in.xyz', flags = 's' + doShell, input = infile,
  221. output = 'dummy', sep = fs, x = x, y = y, z = z,
  222. **addl_opts)
  223. sys.exit()
  224. if dtype is 'float':
  225. data_type = 'FCELL'
  226. else:
  227. data_type = 'DCELL'
  228. region = grass.region(region3d = True)
  229. if region['nsres'] != region['nsres3'] or region['ewres'] != region['ewres3']:
  230. grass.run_command('g.region', flags = '3p')
  231. grass.fatal(_("The 2D and 3D region settings are different. Can not continue."))
  232. grass.verbose(_("Region bottom=%.15g top=%.15g vertical_cell_res=%.15g (%d depths)")
  233. % (region['b'], region['t'], region['tbres'], region['depths']))
  234. grass.verbose(_("Creating slices ..."))
  235. # to avoid a point which falls exactly on a top bound from being
  236. # considered twice, we shrink the
  237. # For the top slice we keep it though, as someone scanning the bounds
  238. # may have set the bounds exactly to the data extent (a bad idea, but
  239. # it happens..)
  240. eps = 1.0e-15
  241. # if there are thousands of depths hopefully this array doesn't get too
  242. # large and so we don't have to worry much about storing/looping through
  243. # all the finished process infos.
  244. proc = {}
  245. pout = {}
  246. depths = range(1, 1 + region['depths'])
  247. for i in depths:
  248. tmp_layer_name = 'tmp.r3xyz.%d.%s' % (os.getpid(), '%05d' % i)
  249. zrange_min = region['b'] + (region['tbres'] * (i-1))
  250. if i < region['depths']:
  251. zrange_max = region['b'] + (region['tbres'] * i) - eps
  252. else:
  253. zrange_max = region['b'] + (region['tbres'] * i)
  254. # spawn depth layer import job in the background
  255. #grass.debug("slice %d, <%s> %% %d" % (band, image[band], band % workers))
  256. grass.message(_("Processing horizontal slice %d of %d [%.15g,%.15g) ...")
  257. % (i, region['depths'], zrange_min, zrange_max))
  258. proc[i] = grass.start_command('r.in.xyz', input = infile, output = tmp_layer_name,
  259. sep = fs, method = method, x = x, y = y, z = z,
  260. percent = percent, type = data_type,
  261. zrange = '%.15g,%.15g' % (zrange_min, zrange_max),
  262. **addl_opts)
  263. grass.debug("i=%d, %%=%d (workers=%d)" % (i, i % workers, workers))
  264. #print sys.getsizeof(proc) # sizeof(proc array) [not so big]
  265. if i % workers is 0:
  266. # wait for the ones launched so far to finish
  267. for p_i in depths[:i]:
  268. pout[p_i] = proc[p_i].communicate()[0]
  269. if proc[p_i].wait() is not 0:
  270. grass.fatal(_("Trouble importing data. Aborting."))
  271. # wait for jSobs to finish, collect any stray output
  272. for i in depths:
  273. pout[i] = proc[i].communicate()[0]
  274. if proc[i].wait() is not 0:
  275. grass.fatal(_("Trouble importing data. Aborting."))
  276. del proc
  277. grass.verbose(_("Assembling 3D cube ..."))
  278. #input order: lower most strata first
  279. slices = grass.read_command('g.mlist', type = 'rast', sep = ',',
  280. pattern = 'tmp.r3xyz.%d.*' % os.getpid()).rstrip('\n')
  281. grass.debug(slices)
  282. if grass.run_command('r.to.rast3', input = slices, output = output) is 0:
  283. grass.message(_("Done. 3D raster map <%s> created.") % output)
  284. if __name__ == "__main__":
  285. options, flags = grass.parser()
  286. atexit.register(cleanup)
  287. main()