m.proj.py 8.4 KB

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