m.proj.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: m.proj
  5. # AUTHOR: M. Hamish Bowman, Dept. Marine Science, Otago Univeristy,
  6. # New Zealand
  7. # Converted to Python by Glynn Clements
  8. # PURPOSE: cs2cs reprojection frontend for a list of coordinates.
  9. # Replacement for m.proj2 from GRASS 5
  10. # COPYRIGHT: (c) 2006-2009 Hamish Bowman, and the GRASS Development Team
  11. # This program is free software under the GNU General Public
  12. # License (>=v2). Read the file COPYING that comes with GRASS
  13. # for details.
  14. #
  15. #############################################################################
  16. # notes:
  17. # - cs2cs expects "x y" data so be sure to send it "lon lat" not "lat lon"
  18. # - if you send cs2cs a third data column, beware it might be treated as "z"
  19. # todo:
  20. # - `cut` away x,y columns into a temp file, feed to cs2cs, then `paste`
  21. # back to input file. see method in v.in.garmin.sh. that way additional
  22. # numeric and string columns would survive the trip, and 3rd column would
  23. # not be modified as z.
  24. #%module
  25. #% description: Converts coordinates from one projection to another (cs2cs frontend).
  26. #% keywords: miscellaneous
  27. #% keywords: projection
  28. #%end
  29. #%option G_OPT_F_INPUT
  30. #% description: Name of input coordinate file ('-' to read from stdin)
  31. #% answer: -
  32. #% guisection: Files & format
  33. #%end
  34. #%option G_OPT_F_OUTPUT
  35. #% description: Name for output coordinate file (omit to send to stdout)
  36. #% required : no
  37. #% guisection: Files & format
  38. #%end
  39. #%option G_OPT_F_SEP
  40. #% label: Field separator (format: input[,output])
  41. #% description: Valid field separators are also "space", "tab", or "comma"
  42. #% required : no
  43. #% guisection: Files & format
  44. #%end
  45. #%option
  46. #% key: proj_in
  47. #% type: string
  48. #% description: Input projection parameters (PROJ.4 style)
  49. #% required : no
  50. #% guisection: Projections
  51. #%end
  52. #%option
  53. #% key: proj_out
  54. #% type: string
  55. #% description: Output projection parameters (PROJ.4 style)
  56. #% required : no
  57. #% guisection: Projections
  58. #%end
  59. #%flag
  60. #% key: i
  61. #% description: Use LL WGS84 as input and current location as output projection
  62. #% guisection: Projections
  63. #%end
  64. #%flag
  65. #% key: o
  66. #% description: Use current location as input and LL WGS84 as output projection
  67. #% guisection: Projections
  68. #%end
  69. #%flag
  70. #% key: d
  71. #% description: Output long/lat in decimal degrees, or other projections with many decimal places
  72. #% guisection: Files & format
  73. #%end
  74. #%flag
  75. #% key: e
  76. #% description: Include input coordinates in output file
  77. #% guisection: Files & format
  78. #%end
  79. #%flag
  80. #% key: c
  81. #% description: Include column names in output file
  82. #% guisection: Files & format
  83. #%end
  84. import sys
  85. import os
  86. import threading
  87. from grass.script import core as grass
  88. class TrThread(threading.Thread):
  89. def __init__(self, ifs, inf, outf):
  90. threading.Thread.__init__(self)
  91. self.ifs = ifs
  92. self.inf = inf
  93. self.outf = outf
  94. def run(self):
  95. while True:
  96. line = self.inf.readline()
  97. if not line:
  98. break
  99. line = line.replace(self.ifs, ' ')
  100. self.outf.write(line)
  101. self.outf.flush()
  102. self.outf.close()
  103. def main():
  104. input = options['input']
  105. output = options['output']
  106. fs = options['separator']
  107. proj_in = options['proj_in']
  108. proj_out = options['proj_out']
  109. ll_in = flags['i']
  110. ll_out = flags['o']
  111. decimal = flags['d']
  112. copy_input = flags['e']
  113. include_header = flags['c']
  114. #### check for cs2cs
  115. if not grass.find_program('cs2cs'):
  116. grass.fatal(_("cs2cs program not found, install PROJ.4 first: http://proj.maptools.org"))
  117. #### check for overenthusiasm
  118. if proj_in and ll_in:
  119. grass.fatal(_("Choose only one input parameter method"))
  120. if proj_out and ll_out:
  121. grass.fatal(_("Choose only one output parameter method"))
  122. if ll_in and ll_out:
  123. grass.fatal(_("Choise only one auto-projection parameter method"))
  124. if output and not grass.overwrite() and os.path.exists(output):
  125. grass.fatal(_("Output file already exists"))
  126. #### parse field separator
  127. # FIXME: input_x,y needs to split on multiple whitespace between them
  128. if fs == ',':
  129. ifs = ofs = ','
  130. else:
  131. try:
  132. ifs, ofs = fs.split(',')
  133. except ValueError:
  134. ifs = ofs = fs
  135. ifs = ifs.lower()
  136. ofs = ofs.lower()
  137. if ifs in ('space', 'tab'):
  138. ifs = ' '
  139. elif ifs == 'comma':
  140. ifs = ','
  141. else:
  142. if len(ifs) > 1:
  143. grass.warning(_("Invalid field separator, using '%s'") % ifs[0])
  144. try:
  145. ifs = ifs[0]
  146. except IndexError:
  147. grass.fatal(_("Invalid field separator '%s'") % ifs)
  148. if ofs.lower() == 'space':
  149. ofs = ' '
  150. elif ofs.lower() == 'tab':
  151. ofs = '\t'
  152. elif ofs.lower() == 'comma':
  153. ofs = ','
  154. else:
  155. if len(ofs) > 1:
  156. grass.warning(_("Invalid field separator, using '%s'") % ofs[0])
  157. try:
  158. ofs = ofs[0]
  159. except IndexError:
  160. grass.fatal(_("Invalid field separator '%s'") % ifs)
  161. #### set up projection params
  162. s = grass.read_command("g.proj", flags='j')
  163. kv = grass.parse_key_val(s)
  164. if "XY location" in kv['+proj'] and (ll_in or ll_out):
  165. grass.fatal(_("Unable to project to or from a XY location"))
  166. in_proj = None
  167. if ll_in:
  168. in_proj = "+proj=longlat +datum=WGS84"
  169. grass.verbose("Assuming LL WGS84 as input, current projection as output ")
  170. if ll_out:
  171. in_proj = grass.read_command('g.proj', flags = 'jf')
  172. if proj_in:
  173. in_proj = proj_in
  174. if not in_proj:
  175. grass.verbose("Assuming current location as input")
  176. in_proj = grass.read_command('g.proj', flags = 'jf')
  177. in_proj = in_proj.strip()
  178. grass.verbose("Input parameters: '%s'" % in_proj)
  179. out_proj = None
  180. if ll_out:
  181. out_proj = "+proj=longlat +datum=WGS84"
  182. grass.verbose("Assuming current projection as input, LL WGS84 as output ")
  183. if ll_in:
  184. out_proj = grass.read_command('g.proj', flags = 'jf')
  185. if proj_out:
  186. out_proj = proj_out
  187. if not out_proj:
  188. grass.fatal(_("Missing output projection parameters "))
  189. out_proj = out_proj.strip()
  190. grass.verbose("Output parameters: '%s'" % out_proj)
  191. #### set up input file
  192. if input == '-':
  193. infile = None
  194. inf = sys.stdin
  195. else:
  196. infile = input
  197. if not os.path.exists(infile):
  198. grass.fatal(_("Unable to read input data"))
  199. inf = file(infile)
  200. grass.debug("input file=[%s]" % infile)
  201. #### set up output file
  202. if not output:
  203. outfile = None
  204. outf = sys.stdout
  205. else:
  206. outfile = output
  207. outf = open(outfile, 'w')
  208. grass.debug("output file=[%s]" % outfile)
  209. #### set up output style
  210. if not decimal:
  211. outfmt = ["-w5"]
  212. else:
  213. outfmt = ["-f", "%.8f"]
  214. if not copy_input:
  215. copyinp = []
  216. else:
  217. copyinp = ["-E"]
  218. #### do the conversion
  219. # Convert cs2cs DMS format to GRASS DMS format:
  220. # cs2cs | sed -e 's/d/:/g' -e "s/'/:/g" -e 's/"//g'
  221. cmd = ['cs2cs'] + copyinp + outfmt + in_proj.split() + ['+to'] + out_proj.split()
  222. p = grass.Popen(cmd, stdin = grass.PIPE, stdout = grass.PIPE)
  223. tr = TrThread(ifs, inf, p.stdin)
  224. tr.start()
  225. if not copy_input:
  226. if include_header:
  227. outf.write("x%sy%sz\n" % (ofs, ofs))
  228. for line in p.stdout:
  229. xy, z = line.split(' ', 1)
  230. x, y = xy.split('\t')
  231. outf.write('%s%s%s%s%s\n' % \
  232. (x.strip(), ofs, y.strip(), ofs, z.strip()))
  233. else:
  234. if include_header:
  235. outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs))
  236. for line in p.stdout:
  237. inXYZ, x, rest = line.split('\t')
  238. inX, inY = inXYZ.split(' ')[:2]
  239. y, z = rest.split(' ', 1)
  240. outf.write('%s%s%s%s%s%s%s%s%s\n' % \
  241. (inX.strip(), ofs, inY.strip(), ofs, x.strip(), \
  242. ofs, y.strip(), ofs, z.strip()))
  243. p.wait()
  244. if p.returncode != 0:
  245. grass.warning(_("Projection transform probably failed, please investigate"))
  246. if __name__ == "__main__":
  247. options, flags = grass.parser()
  248. main()