def test_write_labels_unicode(self): """This tests if Python module works""" find_program("ls", "--version") write_command( "r.category", map=self.raster, rules="-", stdin="1:kůň\n2:kráva\n3:ovečka\n4:býk", separator=":", ) res = read_command("r.category", map=self.raster, separator=":").strip() self.assertEquals(res, "1:kůň\n2:kráva\n3:ovečka\n4:býk") self.assertIsInstance(res, str)
def _projInfo(self): """!Return region projection and map units information""" projinfo = dict() if not grass.find_program("g.proj", "--help"): sys.exit( _("GRASS module '%s' not found. Unable to start map " "display window.") % "g.proj" ) ret = self._runCommand(RunCommand, prog="g.proj", read=True, flags="p") if not ret: return projinfo for line in ret.splitlines(): if ":" in line: key, val = map(lambda x: x.strip(), line.split(":")) if key in ["units"]: val = val.lower() projinfo[key] = val elif "XY location (unprojected)" in line: projinfo["proj"] = "xy" projinfo["units"] = "" break return projinfo
def start_browser(entry): if browser != 'xdg-open' and not grass.find_program(browser): grass.fatal(_("Browser '%s' not found") % browser) if flags['o']: major, minor, patch = grass.version()['version'].split('.') url_path = 'http://grass.osgeo.org/grass%s%s/manuals/%s.html' % ( major, minor, entry) if urllib.urlopen(url_path).getcode() != 200: url_path = 'http://grass.osgeo.org/grass%s%s/manuals/addons/%s.html' % ( major, minor, entry) else: path = os.path.join(gisbase, 'docs', 'html', entry + '.html') if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'): path = os.path.join(os.getenv('GRASS_ADDON_BASE'), 'docs', 'html', entry + '.html') if not os.path.exists(path): grass.fatal(_("No HTML manual page entry for '%s'") % entry) url_path = 'file://' + path grass.verbose( _("Starting browser '%(browser)s' for manual" " entry '%(entry)s'...") % dict(browser=browser_name, entry=entry)) try: os.execlp(browser, browser_name, url_path) except OSError: grass.fatal( _("Error starting browser '%(browser)s' for HTML file" " '%(path)s'") % dict(browser=browser, path=path))
def OnConnect(self, event): """!Button 'Connect' pressed""" # 'r.in.wms -l' output changes depending on the parser used. # the parsing below depends on the cleaner `xml2` version. if not find_program('xml2'): GError(_("The 'xml2' parser is required, please install it " "first. You may also try running r.in.wms directly " "from the command line.")) return server = self.server.GetValue() if not server: self.btn_import.Enable(False) return # not reachable layers = {} ret = RunCommand('r.in.wms', quiet = True, parent = self, read = True, flags = 'l', mapserver = server) if not ret: self.list.LoadData() self.btn_import.Enable(False) return # no layers found lastLayer = lastStyle = '' for line in ret.splitlines(): try: key, value = line.split(':', 1) except ValueError: continue key = key.strip().lower() value = value.strip() if key == 'layer': layers[value] = {} lastLayer = value elif key == 'title': if lastLayer and 'title' not in layers[lastLayer]: layers[lastLayer][key] = value.decode('utf8') elif key == 'style': if lastLayer: if 'style' not in layers[lastLayer]: layers[lastLayer]['style'] = {} layers[lastLayer]['style'][value] = '' lastStyle = value elif key == 'style title': if lastLayer: layers[lastLayer]['style'][lastStyle] = value # update list of layers self.list.LoadData(layers) if len(layers.keys()) > 0: self.btn_import.Enable(True) else: self.btn_import.Enable(False)
def start_browser(entry): if browser and \ browser not in ('xdg-open', 'start') and \ not grass.find_program(browser): grass.fatal(_("Browser '%s' not found") % browser) if flags['o']: major,minor,patch = grass.version()['version'].split('.') url_path = 'http://grass.osgeo.org/grass%s%s/manuals/%s.html' % (major,minor,entry) if urllib.urlopen(url_path).getcode() != 200: url_path = 'http://grass.osgeo.org/grass%s%s/manuals/addons/%s.html' % (major,minor,entry) else: path = os.path.join(gisbase, 'docs', 'html', entry + '.html') if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'): path = os.path.join(os.getenv('GRASS_ADDON_BASE'), 'docs', 'html', entry + '.html') if not os.path.exists(path): grass.fatal(_("No HTML manual page entry for '%s'") % entry) url_path = 'file://' + path if browser and browser not in ('xdg-open', 'start'): webbrowser.register(browser_name, None) grass.verbose(_("Starting browser '%(browser)s' for manual" " entry '%(entry)s'...") % \ dict(browser=browser_name, entry=entry)) try: webbrowser.open(url_path) except: grass.fatal(_("Error starting browser '%(browser)s' for HTML file" " '%(path)s'") % dict(browser=browser, path=path))
def _projInfo(self): """!Return region projection and map units information """ projinfo = dict() if not grass.find_program('g.proj', ['--help']): sys.exit(_("GRASS module '%s' not found. Unable to start map " "display window.") % 'g.proj') ret = self._runCommand(gcmd.RunCommand, prog = 'g.proj', read = True, flags = 'p') if not ret: return projinfo for line in ret.splitlines(): if ':' in line: key, val = map(lambda x: x.strip(), line.split(':')) if key in ['units']: val = val.lower() projinfo[key] = val elif "XY location (unprojected)" in line: projinfo['proj'] = 'xy' projinfo['units'] = '' break return projinfo
def _projInfo(self): """!Return region projection and map units information """ projinfo = dict() if not grass.find_program('g.proj', ['--help']): sys.exit( _("GRASS module '%s' not found. Unable to start map " "display window.") % 'g.proj') ret = self._runCommand(RunCommand, prog='g.proj', read=True, flags='p') if not ret: return projinfo for line in ret.splitlines(): if ':' in line: key, val = map(lambda x: x.strip(), line.split(':')) if key in ['units']: val = val.lower() projinfo[key] = val elif "XY location (unprojected)" in line: projinfo['proj'] = 'xy' projinfo['units'] = '' break return projinfo
def main(): group = options['group'] raster = options['raster'] output = options['output'] coords = options['coordinates'] img_fmt = options['format'] coord_legend = flags['c'] gnuplot = flags['g'] global tmp_dir tmp_dir = grass.tempdir() if not group and not raster: grass.fatal(_("Either group= or raster= is required")) if group and raster: grass.fatal(_("group= and raster= are mutually exclusive")) # check if gnuplot is present if gnuplot and not grass.find_program('gnuplot', '-V'): grass.fatal(_("gnuplot required, please install first")) # get data from group listing and set the x-axis labels if group: # Parse the group list output s = grass.read_command('i.group', flags='g', group=group, quiet=True) rastermaps = s.splitlines() else: # get data from list of files and set the x-axis labels rastermaps = raster.split(',') xlabels = ["'%s' %d" % (n, i + 1) for i, n in enumerate(rastermaps)] xlabels = ','.join(xlabels) # get y-data for gnuplot-data file what = [] s = grass.read_command('r.what', map=rastermaps, coordinates=coords, null='0', quiet=True) if len(s) == 0: grass.fatal(_('No data returned from query')) for l in s.splitlines(): f = l.split('|') for i, v in enumerate(f): if v in ['', '*']: f[i] = 0 else: f[i] = float(v) what.append(f) # build data files if gnuplot: draw_gnuplot(what, xlabels, output, img_fmt, coord_legend) else: draw_linegraph(what)
def _initMap(self, Map): """Initialize map display, set dimensions and map region """ if not grass.find_program('g.region', '--help'): sys.exit(_("GRASS module '%s' not found. Unable to start map " "display window.") % 'g.region') Debug.msg(2, "MapFrame._initMap():") Map.ChangeMapSize(self.GetClientSize()) Map.region = Map.GetRegion() # g.region -upgc
def _initMap(self, Map): """Initialize map display, set dimensions and map region""" if not grass.find_program("g.region", "--help"): sys.exit( _("GRASS module '%s' not found. Unable to start map " "display window.") % "g.region") Debug.msg(2, "MapPanel._initMap():") Map.ChangeMapSize(self.GetClientSize()) Map.region = Map.GetRegion() # g.region -upgc
def main(): group = options['group'] raster = options['raster'] output = options['output'] coords = options['east_north'] label = flags['c'] gnuplot = flags['g'] if not group and not raster: grass.fatal(_("Either group= or raster= is required")) if group and raster: grass.fatal(_("group= and raster= are mutually exclusive")) #check if present if gnuplot and not grass.find_program('gnuplot', ['-V']): grass.fatal(_("gnuplot required, please install first")) tmp1 = grass.tempfile() tmp2 = grass.tempfile() # get y-data for gnuplot-data file # get data from group files and set the x-axis labels if group: # ## PARSES THE GROUP FILES - gets rid of ugly header info from group list output s = grass.read_command('i.group', flags='g', group = group, quiet = True) rastermaps = s.splitlines() else: # ## get data from list of files and set the x-axis labels rastermaps = raster.split(',') xlabels = ["'%s' %d" % (n, i + 1) for i, n in enumerate(rastermaps)] xlabels = ','.join(xlabels) numbands = len(rastermaps) what = [] s = grass.read_command('r.what', input = rastermaps, east_north = coords, quiet = True) for l in s.splitlines(): f = l.split('|') for i, v in enumerate(f): if v in ['', '*']: f[i] = 0 else: f[i] = float(v) what.append(f) # build data files if gnuplot: draw_gnuplot(what, xlabels, output, label) else: draw_linegraph(what)
def _initMap(self, map): """!Initialize map display, set dimensions and map region """ if not grass.find_program('g.region', ['--help']): sys.exit( _("GRASS module '%s' not found. Unable to start map " "display window.") % 'g.region') self.width, self.height = self.GetClientSize() Debug.msg(2, "MapFrame._initMap():") map.ChangeMapSize(self.GetClientSize()) map.region = map.GetRegion() # g.region -upgc
def start_browser(entry): if browser != "xdg-open" and not grass.find_program(browser): grass.fatal(_("Browser <%s> not found") % browser) path = os.path.join(gisbase, "docs", "html", entry + ".html") if not os.path.exists(path) and os.getenv("GRASS_ADDON_PATH"): path = os.path.join(os.getenv("GRASS_ADDON_PATH"), "docs", "html", entry + ".html") if not os.path.exists(path): grass.fatal(_("No HTML manual page entry for <%s>") % entry) grass.verbose(_("Starting browser <%s> for module %s...") % (browser_name, entry)) os.execlp(browser, browser_name, "file://%s" % (path)) grass.fatal(_("Error starting browser <%s> for HTML file <%s>") % (browser, entry))
def start_browser(entry): if ( browser and browser not in ("xdg-open", "start") and not grass.find_program(browser) ): grass.fatal(_("Browser '%s' not found") % browser) if flags["o"]: major, minor, patch = grass.version()["version"].split(".") url_path = "https://grass.osgeo.org/grass%s%s/manuals/%s.html" % ( major, minor, entry, ) if urlopen(url_path).getcode() != 200: url_path = "https://grass.osgeo.org/grass%s%s/manuals/addons/%s.html" % ( major, minor, entry, ) else: path = os.path.join(gisbase, "docs", "html", entry + ".html") if not os.path.exists(path) and os.getenv("GRASS_ADDON_BASE"): path = os.path.join( os.getenv("GRASS_ADDON_BASE"), "docs", "html", entry + ".html" ) if not os.path.exists(path): grass.fatal(_("No HTML manual page entry for '%s'") % entry) url_path = "file://" + path if browser and browser not in ("xdg-open", "start"): webbrowser.register(browser_name, None) grass.verbose( _("Starting browser '%(browser)s' for manual" " entry '%(entry)s'...") % dict(browser=browser_name, entry=entry) ) try: webbrowser.open(url_path) except: grass.fatal( _("Error starting browser '%(browser)s' for HTML file" " '%(path)s'") % dict(browser=browser, path=path) )
def sortfile(infile, outfile): inf = file(infile, 'r') outf = file(outfile, 'w') if grass.find_program('sort', '--help'): grass.run_command('sort', flags='n', stdin=inf, stdout=outf) else: # FIXME: we need a large-file sorting function grass.warning(_("'sort' not found: sorting in memory")) lines = inf.readlines() for i in range(len(lines)): lines[i] = float(lines[i].rstrip('\r\n')) lines.sort() for line in lines: outf.write(str(line) + '\n') inf.close() outf.close()
def sortfile(infile, outfile): inf = file(infile, 'r') outf = file(outfile, 'w') if grass.find_program('sort', '--help'): grass.run_command('sort', flags = 'n', stdin = inf, stdout = outf) else: # FIXME: we need a large-file sorting function grass.warning(_("'sort' not found: sorting in memory")) lines = inf.readlines() for i in range(len(lines)): lines[i] = float(lines[i].rstrip('\r\n')) lines.sort() for line in lines: outf.write(str(line) + '\n') inf.close() outf.close()
def check_addon_installed(addon, fatal=True): if not gcore.find_program(addon, '--help'): call = gcore.fatal if fatal else gcore.warning call(_("Addon {a} is not installed." " Please install it using g.extension.").format(a=addon))
def main(): filename = options['input'] type = options['type'] vect = options['output'] e00tmp = str(os.getpid()) # check for avcimport if not gcore.find_program('avcimport'): gcore.fatal( _("'avcimport' program not found, install it first") + "\n" + "http://avce00.maptools.org") # check for e00conv if not gcore.find_program('e00conv'): gcore.fatal( _("'e00conv' program not found, install it first") + "\n" + "http://avce00.maptools.org") # check that the user didn't use all three, which gets past the parser. if type not in ['point', 'line', 'area']: gcore.fatal(_('Must specify one of "point", "line", or "area".')) e00name = basename(filename, 'e00') # avcimport only accepts 13 chars: e00shortname = e00name[:13] # check if this is a split E00 file (.e01, .e02 ...): merging = False if os.path.exists(e00name + '.e01') or os.path.exists(e00name + '.E01'): gcore.message( _("Found that E00 file is split into pieces (.e01, ...)." " Merging...")) merging = True if vect: name = vect else: name = e00name # do import # make a temporary directory tmpdir = gcore.tempfile() try_remove(tmpdir) os.mkdir(tmpdir) files = glob.glob(e00name + '.e[0-9][0-9]') + glob.glob(e00name + '.E[0-9][0-9]') for f in files: shutil.copy(f, tmpdir) # change to temporary directory to later avoid removal problems (rm -r ...) os.chdir(tmpdir) # check for binay E00 file (we can just check if import fails): # avcimport doesn't set exist status :-( if merging: files.sort() filename = "%s.cat.%s.e00" % (e00name, e00tmp) outf = file(filename, 'wb') for f in files: inf = file(f, 'rb') shutil.copyfileobj(inf, outf) inf.close() outf.close() nuldev = file(os.devnull, 'w+') gcore.message(_("An error may appear next which will be ignored...")) if gcore.call(['avcimport', filename, e00shortname], stdout=nuldev, stderr=nuldev) == 1: gcore.message( _("E00 ASCII found and converted to Arc Coverage in " "current directory")) else: gcore.message( _("E00 Compressed ASCII found. Will uncompress first...")) try_remove(e00shortname) gcore.call(['e00conv', filename, e00tmp + '.e00']) gcore.message(_("...converted to Arc Coverage in current directory")) gcore.call(['avcimport', e00tmp + '.e00', e00shortname], stderr=nuldev) # SQL name fix: name = name.replace('-', '_') # let's import... gcore.message(_("Importing %ss...") % type) layer = dict(point='LAB', line='ARC', area=['LAB', 'ARC']) itype = dict(point='point', line='line', area='centroid') try: gcore.run_command('v.in.ogr', flags='o', input=e00shortname, layer=layer[type], type=itype[type], output=name) except CalledModuleError: gcore.fatal(_("An error occurred while running v.in.ogr")) gcore.message(_("Imported <%s> vector map <%s>.") % (type, name)) # clean up the mess for root, dirs, files in os.walk('.', False): for f in files: path = os.path.join(root, f) try_remove(path) for d in dirs: path = os.path.join(root, d) try_rmdir(path) os.chdir('..') os.rmdir(tmpdir) # end gcore.message(_("Done.")) # write cmd history: gvect.vector_history(name)
def main(): coords = options["coordinates"] input = options["input"] output = options["output"] fs = options["separator"] proj_in = options["proj_in"] proj_out = options["proj_out"] ll_in = flags["i"] ll_out = flags["o"] decimal = flags["d"] copy_input = flags["e"] include_header = flags["c"] # check for cs2cs if not gcore.find_program("cs2cs"): gcore.fatal( _("cs2cs program not found, install PROJ first: \ https://proj.org")) # parse field separator # FIXME: input_x,y needs to split on multiple whitespace between them if fs == ",": ifs = ofs = "," else: try: ifs, ofs = fs.split(",") except ValueError: ifs = ofs = fs ifs = separator(ifs) ofs = separator(ofs) # set up projection params s = gcore.read_command("g.proj", flags="j") kv = parse_key_val(s) if "XY location" in kv["+proj"] and (ll_in or ll_out): gcore.fatal(_("Unable to project to or from a XY location")) in_proj = None if ll_in: in_proj = "+proj=longlat +datum=WGS84" gcore.verbose( "Assuming LL WGS84 as input, current projection as output ") if ll_out: in_proj = gcore.read_command("g.proj", flags="jf") if proj_in: if "+" in proj_in: in_proj = proj_in else: gcore.fatal(_("Invalid PROJ.4 input specification")) if not in_proj: gcore.verbose("Assuming current location as input") in_proj = gcore.read_command("g.proj", flags="jf") in_proj = in_proj.strip() gcore.verbose("Input parameters: '%s'" % in_proj) out_proj = None if ll_out: out_proj = "+proj=longlat +datum=WGS84" gcore.verbose( "Assuming current projection as input, LL WGS84 as output ") if ll_in: out_proj = gcore.read_command("g.proj", flags="jf") if proj_out: if "+" in proj_out: out_proj = proj_out else: gcore.fatal(_("Invalid PROJ.4 output specification")) if not out_proj: gcore.fatal(_("Missing output projection parameters ")) out_proj = out_proj.strip() gcore.verbose("Output parameters: '%s'" % out_proj) # set up input file if coords: x, y = coords.split(",") tmpfile = gcore.tempfile() fd = open(tmpfile, "w") fd.write("%s%s%s\n" % (x, ifs, y)) fd.close() inf = open(tmpfile) else: if input == "-": infile = None inf = sys.stdin else: infile = input if not os.path.exists(infile): gcore.fatal(_("Unable to read input data")) inf = open(infile) gcore.debug("input file=[%s]" % infile) # set up output file if not output: outfile = None outf = sys.stdout else: outfile = output outf = open(outfile, "w") gcore.debug("output file=[%s]" % outfile) # set up output style if not decimal: outfmt = ["-w5"] else: outfmt = ["-f", "%.8f"] if not copy_input: copyinp = [] else: copyinp = ["-E"] # do the conversion # Convert cs2cs DMS format to GRASS DMS format: # cs2cs | sed -e 's/d/:/g' -e "s/'/:/g" -e 's/"//g' cmd = ["cs2cs" ] + copyinp + outfmt + in_proj.split() + ["+to"] + out_proj.split() p = gcore.Popen(cmd, stdin=gcore.PIPE, stdout=gcore.PIPE) tr = TrThread(ifs, inf, p.stdin) tr.start() if not copy_input: if include_header: outf.write("x%sy%sz\n" % (ofs, ofs)) for line in p.stdout: try: xy, z = decode(line).split(" ", 1) x, y = xy.split("\t") except ValueError: gcore.fatal(line) outf.write("%s%s%s%s%s\n" % (x.strip(), ofs, y.strip(), ofs, z.strip())) else: if include_header: outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs)) for line in p.stdout: inXYZ, x, rest = decode(line).split("\t") inX, inY = inXYZ.split(" ")[:2] y, z = rest.split(" ", 1) outf.write("%s%s%s%s%s%s%s%s%s\n" % ( inX.strip(), ofs, inY.strip(), ofs, x.strip(), ofs, y.strip(), ofs, z.strip(), )) p.wait() if p.returncode != 0: gcore.warning( _("Projection transform probably failed, please investigate"))
def main(): coords = options['coordinates'] input = options['input'] output = options['output'] fs = options['separator'] proj_in = options['proj_in'] proj_out = options['proj_out'] ll_in = flags['i'] ll_out = flags['o'] decimal = flags['d'] copy_input = flags['e'] include_header = flags['c'] #### check for cs2cs if not grass.find_program('cs2cs'): grass.fatal(_("cs2cs program not found, install PROJ.4 first: http://proj.maptools.org")) #### check for overenthusiasm if proj_in and ll_in: grass.fatal(_("Choose only one input parameter method")) if proj_out and ll_out: grass.fatal(_("Choose only one output parameter method")) if ll_in and ll_out: grass.fatal(_("Choise only one auto-projection parameter method")) if output and not grass.overwrite() and os.path.exists(output): grass.fatal(_("Output file already exists")) if not coords and not input: grass.fatal(_("One of <coordinates> and <input> must be given")) if coords and input: grass.fatal(_("Options <coordinates> and <input> are mutually exclusive")) #### parse field separator # FIXME: input_x,y needs to split on multiple whitespace between them if fs == ',': ifs = ofs = ',' else: try: ifs, ofs = fs.split(',') except ValueError: ifs = ofs = fs ifs = separator(ifs) ofs = separator(ofs) #### set up projection params s = grass.read_command("g.proj", flags='j') kv = parse_key_val(s) if "XY location" in kv['+proj'] and (ll_in or ll_out): grass.fatal(_("Unable to project to or from a XY location")) in_proj = None if ll_in: in_proj = "+proj=longlat +datum=WGS84" grass.verbose("Assuming LL WGS84 as input, current projection as output ") if ll_out: in_proj = grass.read_command('g.proj', flags = 'jf') if proj_in: in_proj = proj_in if not in_proj: grass.verbose("Assuming current location as input") in_proj = grass.read_command('g.proj', flags = 'jf') in_proj = in_proj.strip() grass.verbose("Input parameters: '%s'" % in_proj) out_proj = None if ll_out: out_proj = "+proj=longlat +datum=WGS84" grass.verbose("Assuming current projection as input, LL WGS84 as output ") if ll_in: out_proj = grass.read_command('g.proj', flags = 'jf') if proj_out: out_proj = proj_out if not out_proj: grass.fatal(_("Missing output projection parameters ")) out_proj = out_proj.strip() grass.verbose("Output parameters: '%s'" % out_proj) #### set up input file if coords: x, y = coords.split(',') tmpfile = grass.tempfile() fd = open(tmpfile, "w") fd.write("%s%s%s\n" % (x, ifs, y)) fd.close() inf = file(tmpfile) else: if input == '-': infile = None inf = sys.stdin else: infile = input if not os.path.exists(infile): grass.fatal(_("Unable to read input data")) inf = file(infile) grass.debug("input file=[%s]" % infile) #### set up output file if not output: outfile = None outf = sys.stdout else: outfile = output outf = open(outfile, 'w') grass.debug("output file=[%s]" % outfile) #### set up output style if not decimal: outfmt = ["-w5"] else: outfmt = ["-f", "%.8f"] if not copy_input: copyinp = [] else: copyinp = ["-E"] #### do the conversion # Convert cs2cs DMS format to GRASS DMS format: # cs2cs | sed -e 's/d/:/g' -e "s/'/:/g" -e 's/"//g' cmd = ['cs2cs'] + copyinp + outfmt + in_proj.split() + ['+to'] + out_proj.split() p = grass.Popen(cmd, stdin = grass.PIPE, stdout = grass.PIPE) tr = TrThread(ifs, inf, p.stdin) tr.start() if not copy_input: if include_header: outf.write("x%sy%sz\n" % (ofs, ofs)) for line in p.stdout: try: xy, z = line.split(' ', 1) x, y = xy.split('\t') except ValueError: grass.fatal(line) outf.write('%s%s%s%s%s\n' % \ (x.strip(), ofs, y.strip(), ofs, z.strip())) else: if include_header: outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs)) for line in p.stdout: inXYZ, x, rest = line.split('\t') inX, inY = inXYZ.split(' ')[:2] y, z = rest.split(' ', 1) outf.write('%s%s%s%s%s%s%s%s%s\n' % \ (inX.strip(), ofs, inY.strip(), ofs, x.strip(), \ ofs, y.strip(), ofs, z.strip())) p.wait() if p.returncode != 0: grass.warning(_("Projection transform probably failed, please investigate"))
def main(): export_shifted = flags["s"] currmapset = grass.gisenv()["MAPSET"] #### check for v.in.ply, v.out.ply if not grass.find_program("v.in.ply", "--help"): grass.fatal( _("The GRASS addon v.in.ply was not found, please install it first.\n" )) if not grass.find_program("v.out.ply", "--help"): grass.fatal( _("The GRASS addon v.out.ply was not found, please install it first.\n" )) # import input PLY file infile = options["input"] if not os.path.exists(infile): grass.fatal(_("Unable to read input file <%s>") % infile) grass.debug("input file=[%s]" % infile) if not infile[-4:].lower() == ".ply": grass.fatal(_("Input file must end with .ply or .PLY")) gcpfile = infile[:-4] + ".txt" srcdir, ply = os.path.split(infile) ply = ply[:-4] if not os.path.exists(gcpfile): gcpfile = infile[:-4] + ".TXT" if not os.path.exists(gcpfile): grass.fatal( _("Input file with GCPs must be <%s> or <%s>") % ply + ".txt", ply + ".TXT", ) if options["output"] is not None and options["output"] != "": ply = options["output"] clist = list() plydesc = grass.read_command("v.in.ply", flags="p", input=infile, output=ply) # remember column names for vertices currname = "" currprop = "" for l in plydesc.splitlines(): f = l.split(":") if f[0] == "element name": # new element currname = f[1].strip() currprop = "" if f[0] == "property name": currprop = f[1].strip() if currname == "vertex" and currprop not in ["x", "y", "z"]: clist.append(currprop) columns = ",".join(clist) grass.run_command("v.in.ply", flags="b", input=infile, output=ply) # import vector exists? found = grass.find_file(ply, element="vector", mapset=currmapset) if found["name"] != ply: grass.fatal(_("PLY import failed!")) # detach table table = gvector.vector_layer_db(map=ply, layer=1)["table"] grass.run_command("v.db.connect", map=ply, layer=1, flags="d") # print RMS rmsfile = os.path.join(srcdir, ply + "_rms.csv") grass.run_command( "v.rectify", input=ply, output=ply + "_georef", points=gcpfile, flags="3bor", separator=";", rmsfile=rmsfile, ) # georectify ply_georef = ply + "_georef" grass.run_command("v.rectify", input=ply, output=ply_georef, points=gcpfile, flags="3bo") # output vector exists? found = grass.find_file(ply_georef, element="vector", mapset=currmapset) if found["name"] != ply_georef: grass.run_command("v.db.connect", map=ply, layer=1, table=table, key="cat") grass.fatal("PLY import failed!") grass.run_command("v.db.connect", map=ply_georef, layer=1, table=table, key="cat") output = os.path.join(srcdir, ply_georef + ".ply") grass.run_command("v.out.ply", input=ply_georef, output=output, columns=columns) grass.run_command("v.db.connect", map=ply_georef, layer=1, flags="d") if export_shifted: vinfo = gvector.vector_info(map=ply_georef) north_center = (float(vinfo["north"]) + float(vinfo["south"])) / -2.0 east_center = (float(vinfo["east"]) + float(vinfo["west"])) / -2.0 height_center = (float(vinfo["top"]) + float(vinfo["bottom"])) / -2.0 ply_shifted = ply_georef + "_shifted" grass.run_command( "v.transform", input=ply_georef, layer=-1, output=ply_shifted, xshift=east_center, yshift=north_center, zshift=height_center, xscale=1.0, yscale=1.0, zscale=1.0, zrot=0.0, flags="b", ) # output vector exists? found = grass.find_file(ply_shifted, element="vector", mapset=currmapset) if found["name"] != ply_shifted: grass.run_command("v.db.connect", map=ply, layer=1, table=table, key="cat") grass.fatal("PLY import failed!") grass.run_command("v.db.connect", map=ply_shifted, layer=1, table=table, key="cat") output = os.path.join(srcdir, ply_shifted + ".ply") grass.run_command("v.out.ply", input=ply_shifted, output=output, columns=columns) grass.run_command("v.db.connect", map=ply_shifted, layer=1, flags="d") grass.run_command("v.db.connect", map=ply, layer=1, table=table, key="cat") grass.message( _("Done: Pointcloud '%s' has been successfully imported, georeferenced, and exported" ) % ply)
def main(): handler = options["handler"] if options["tempfile"]: img_tmp = options["tempfile"] # TODO: add option for GRASS_RENDER_FILE_COMPRESSION=0,1-9 else: img_tmp = grass.tempfile() os.remove(img_tmp) img_tmp += ".bmp" if flags["b"]: print('GRASS_RENDER_FILE="%s"' % img_tmp) if "GRASS_RENDER_WIDTH" not in os.environ: print("GRASS_RENDER_WIDTH=%s" % options["width"]) if "GRASS_RENDER_HEIGHT" not in os.environ: print("GRASS_RENDER_HEIGHT=%s" % options["height"]) if flags["c"]: print("GRASS_RENDER_IMMEDIATE=cairo") else: print("GRASS_RENDER_IMMEDIATE=PNG") print("GRASS_RENDER_FILE_MAPPED=TRUE") print("GRASS_RENDER_FILE_READ=TRUE") print( "export GRASS_RENDER_FILE GRASS_RENDER_WIDTH GRASS_RENDER_HEIGHT GRASS_RENDER_IMMEDIATE GRASS_RENDER_FILE_MAPPED GRASS_RENDER_FILE_READ;" ) print("d.erase bgcolor=%s;" % options["color"]) if handler == "none": grass.message("Image file is '%s'" % img_tmp) elif handler == "qiv": print('qiv -e -T "%s" &' % img_tmp) # add --center ? else: print('%s image="%s" percent=%s &' % (handler, img_tmp, options["percent"])) sys.exit(0) if flags["d"]: print("rem DOS export not yet implemented") sys.exit(0) ## rest of this won't work, as parent can't inherit from the child.. ## (unless we do some ugly g.gisenv) ## ... any ideas? end by running grass.call(['bash'])? if not grass.find_program(handler, "--help"): grass.fatal(_("'%s' not found.") % handler) os.environ["GRASS_RENDER_FILE"] = img_tmp if "GRASS_RENDER_WIDTH" not in os.environ: os.environ["GRASS_RENDER_WIDTH"] = options["width"] if "GRASS_RENDER_HEIGHT" not in os.environ: os.environ["GRASS_RENDER_HEIGHT"] = options["height"] if flags["c"]: os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo" os.environ["GRASS_RENDER_FILE_MAPPED"] = "TRUE" os.environ["GRASS_RENDER_FILE_READ"] = "TRUE" # ? os.environ['GRASS_PNG_AUTO_WRITE'] = 'FALSE' grass.run_command("d.erase", bgcolor=options["color"]) if handler == "qiv": ret = grass.call(["qiv", "-e", "-T", img_tmp]) else: ret = grass.exec_command(handler, image=img_tmp, percent=options["percent"]) os.remove(img_tmp) sys.exit(ret)
def main(): filename = options["input"] type = options["type"] vect = options["output"] e00tmp = str(os.getpid()) # check for avcimport if not gcore.find_program("avcimport"): gcore.fatal(_("'avcimport' program not found, install it first") + "\n" + "http://avce00.maptools.org") # check for e00conv if not gcore.find_program("e00conv"): gcore.fatal(_("'e00conv' program not found, install it first") + "\n" + "http://avce00.maptools.org") # check that the user didn't use all three, which gets past the parser. if type not in ["point", "line", "area"]: gcore.fatal(_('Must specify one of "point", "line", or "area".')) e00name = basename(filename, "e00") # avcimport only accepts 13 chars: e00shortname = e00name[:13] # check if this is a split E00 file (.e01, .e02 ...): merging = False if os.path.exists(e00name + ".e01") or os.path.exists(e00name + ".E01"): gcore.message(_("Found that E00 file is split into pieces (.e01, ...)." " Merging...")) merging = True if vect: name = vect else: name = e00name # do import # make a temporary directory tmpdir = gcore.tempfile() try_remove(tmpdir) os.mkdir(tmpdir) files = glob.glob(e00name + ".e[0-9][0-9]") + glob.glob(e00name + ".E[0-9][0-9]") for f in files: shutil.copy(f, tmpdir) # change to temporary directory to later avoid removal problems (rm -r ...) os.chdir(tmpdir) # check for binay E00 file (we can just check if import fails): # avcimport doesn't set exist status :-( if merging: files.sort() filename = "%s.cat.%s.e00" % (e00name, e00tmp) outf = file(filename, "wb") for f in files: inf = file(f, "rb") shutil.copyfileobj(inf, outf) inf.close() outf.close() nuldev = file(os.devnull, "w+") gcore.message(_("An error may appear next which will be ignored...")) if gcore.call(["avcimport", filename, e00shortname], stdout=nuldev, stderr=nuldev) == 1: gcore.message(_("E00 ASCII found and converted to Arc Coverage in " "current directory")) else: gcore.message(_("E00 Compressed ASCII found. Will uncompress first...")) try_remove(e00shortname) gcore.call(["e00conv", filename, e00tmp + ".e00"]) gcore.message(_("...converted to Arc Coverage in current directory")) gcore.call(["avcimport", e00tmp + ".e00", e00shortname], stderr=nuldev) # SQL name fix: name = name.replace("-", "_") # let's import... gcore.message(_("Importing %ss...") % type) layer = dict(point="LAB", line="ARC", area=["LAB", "ARC"]) itype = dict(point="point", line="line", area="centroid") try: gcore.run_command("v.in.ogr", flags="o", input=e00shortname, layer=layer[type], type=itype[type], output=name) except CalledModuleError: gcore.fatal(_("An error occurred while running v.in.ogr")) gcore.message(_("Imported <%s> vector map <%s>.") % (type, name)) # clean up the mess for root, dirs, files in os.walk(".", False): for f in files: path = os.path.join(root, f) try_remove(path) for d in dirs: path = os.path.join(root, d) try_rmdir(path) os.chdir("..") os.rmdir(tmpdir) # end gcore.message(_("Done.")) # write cmd history: gvect.vector_history(name)
def install_extension(): gisbase = os.getenv('GISBASE') if not gisbase: grass.fatal(_('$GISBASE not defined')) if grass.find_program(options['extension'], ['--help']): grass.warning(_("Extension '%s' already installed. Will be updated...") % options['extension']) gui_list = list_wxgui_extensions(print_module = False) if options['extension'] not in gui_list: classchar = options['extension'].split('.', 1)[0] moduleclass = expand_module_class_name(classchar) url = options['svnurl'] + '/' + moduleclass + '/' + options['extension'] else: url = options['svnurl'] + '/gui/wxpython/' + options['extension'] if not flags['s']: grass.fatal(_("Installation of wxGUI extension requires -%s flag.") % 's') grass.message(_("Fetching '%s' from GRASS-Addons SVN (be patient)...") % options['extension']) os.chdir(tmpdir) if grass.verbosity() == 0: outdev = open(os.devnull, 'w') else: outdev = sys.stdout if grass.call(['svn', 'checkout', url], stdout = outdev) != 0: grass.fatal(_("GRASS Addons '%s' not found in repository") % options['extension']) dirs = { 'bin' : os.path.join(tmpdir, options['extension'], 'bin'), 'docs' : os.path.join(tmpdir, options['extension'], 'docs'), 'html' : os.path.join(tmpdir, options['extension'], 'docs', 'html'), 'man' : os.path.join(tmpdir, options['extension'], 'man'), 'man1' : os.path.join(tmpdir, options['extension'], 'man', 'man1'), 'scripts' : os.path.join(tmpdir, options['extension'], 'scripts'), 'etc' : os.path.join(tmpdir, options['extension'], 'etc'), } makeCmd = ['make', 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ '), 'BIN=%s' % dirs['bin'], 'HTMLDIR=%s' % dirs['html'], 'MANDIR=%s' % dirs['man1'], 'SCRIPTDIR=%s' % dirs['scripts'], 'ETC=%s' % dirs['etc'] ] installCmd = ['make', 'MODULE_TOPDIR=%s' % gisbase, 'ARCH_DISTDIR=%s' % os.path.join(tmpdir, options['extension']), 'INST_DIR=%s' % options['prefix'], 'install' ] if flags['d']: grass.message(_("To compile run:")) sys.stderr.write(' '.join(makeCmd) + '\n') grass.message(_("To install run:\n\n")) sys.stderr.write(' '.join(installCmd) + '\n') return os.chdir(os.path.join(tmpdir, options['extension'])) grass.message(_("Compiling '%s'...") % options['extension']) if options['extension'] not in gui_list: for d in dirs.itervalues(): if not os.path.exists(d): os.makedirs(d) ret = grass.call(makeCmd, stdout = outdev) else: ret = grass.call(['make', 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ ')], stdout = outdev) if ret != 0: grass.fatal(_('Compilation failed, sorry. Please check above error messages.')) if flags['i'] or options['extension'] in gui_list: return grass.message(_("Installing '%s'...") % options['extension']) ret = grass.call(installCmd, stdout = outdev) if ret != 0: grass.warning(_('Installation failed, sorry. Please check above error messages.')) else: grass.message(_("Installation of '%s' successfully finished.") % options['extension']) # manual page: fix href if os.getenv('GRASS_ADDON_PATH'): html_man = os.path.join(os.getenv('GRASS_ADDON_PATH'), 'docs', 'html', options['extension'] + '.html') if os.path.exists(html_man): fd = open(html_man) html_str = '\n'.join(fd.readlines()) fd.close() for rep in ('grassdocs.css', 'grass_logo.png'): patt = re.compile(rep, re.IGNORECASE) html_str = patt.sub(os.path.join(gisbase, 'docs', 'html', rep), html_str) patt = re.compile(r'(<a href=")(d|db|g|i|m|p|ps|r|r3|s|v|wxGUI)(\.)(.+)(.html">)', re.IGNORECASE) while True: m = patt.search(html_str) if not m: break html_str = patt.sub(m.group(1) + os.path.join(gisbase, 'docs', 'html', m.group(2) + m.group(3) + m.group(4)) + m.group(5), html_str, count = 1) fd = open(html_man, "w") fd.write(html_str) fd.close() if not os.environ.has_key('GRASS_ADDON_PATH') or \ not os.environ['GRASS_ADDON_PATH']: grass.warning(_('This add-on module will not function until you set the ' 'GRASS_ADDON_PATH environment variable (see "g.manual variables")'))
def check_progs(): for prog in ('svn', 'make', 'gcc'): if not grass.find_program(prog, ['--help']): grass.fatal(_("'%s' required. Please install '%s' first.") % (prog, prog))
def main(): global tmp global sine_cosine_replic, outercircle, vector global totalvalidnumber, totalnumber, maxradius map = options['map'] undef = options['undef'] eps = options['eps'] xgraph = flags['x'] tmp = grass.tempfile() if eps and xgraph: grass.fatal(_("Please select only one output method")) #### check if we have xgraph (if no EPS output requested) if xgraph and not grass.find_program('xgraph'): grass.fatal(_("xgraph required, please install first (www.xgraph.org)")) ################################# # this file contains everthing: rawfile = tmp + "_raw" rawf = file(rawfile, 'w') grass.run_command('r.stats', flags = '1', input = map, stdout = rawf) rawf.close() rawf = file(rawfile) totalnumber = 0 for line in rawf: totalnumber += 1 rawf.close() grass.message(_("Calculating statistics for polar diagram... (be patient)")) #wipe out NULL data and undef data if defined by user # - generate degree binned to integer, eliminate NO DATA (NULL): # change 360 to 0 to close polar diagram: rawf = file(rawfile) nvals = 0 sumcos = 0 sumsin = 0 freq = {} for line in rawf: line = line.rstrip('\r\n') if line in ['*', undef]: continue nvals += 1 x = float(line) rx = math.radians(x) sumcos += math.cos(rx) sumsin += math.sin(rx) ix = round(x) if ix == 360: ix = 0 if ix in freq: freq[ix] += 1 else: freq[ix] = 1 rawf.close() totalvalidnumber = nvals if totalvalidnumber == 0: grass.fatal(_("No data pixel found")) ################################# # unit vector on raw data converted to radians without no data: unitvector = (sumcos / nvals, sumsin / nvals) ################################# # how many are there?: occurrences = [(math.radians(x), freq[x]) for x in freq] occurrences.sort() # find the maximum value maxradius = max([f for a, f in occurrences]) # now do cos() sin() sine_cosine = [(math.cos(a) * f, math.sin(a) * f) for a, f in occurrences] sine_cosine_replic = ['"Real data angles'] + sine_cosine + sine_cosine[0:1] if eps or xgraph: outercircle = [] outercircle.append('"All Data incl. NULLs') scale = 1.0 * totalnumber / totalvalidnumber * maxradius for i in range(0, 361): a = math.radians(i) x = math.cos(a) * scale y = math.sin(a) * scale outercircle.append((x, y)) # fix vector length to become visible (x? of $MAXRADIUS): vector = [] vector.append('"Avg. Direction\n') vector.append((0, 0)) vector.append((unitvector[0] * maxradius, unitvector[1] * maxradius)) ########################################################### # Now output: if eps: psout = basename(eps, 'eps') + '.eps' plot_eps(psout) elif xgraph: plot_xgraph() else: plot_dgraph() grass.message(_("Average vector:")) grass.message(_("direction: %.1f degrees CCW from East") % math.degrees(math.atan2(unitvector[1], unitvector[0]))) grass.message(_("magnitude: %.1f percent of fullscale") % (100 * math.hypot(unitvector[0], unitvector[1])))
def main(): group = options["group"] subgroup = options["subgroup"] raster = options["raster"] output = options["output"] coords = options["coordinates"] img_fmt = options["format"] coord_legend = flags["c"] gnuplot = flags["g"] textfile = flags["t"] global tmp_dir tmp_dir = gcore.tempdir() if not group and not raster: gcore.fatal(_("Either group= or raster= is required")) if group and raster: gcore.fatal(_("group= and raster= are mutually exclusive")) # -t needs an output filename if textfile and not output: gcore.fatal(_("Writing to text file requires output=filename")) # check if gnuplot is present if gnuplot and not gcore.find_program("gnuplot", "-V"): gcore.fatal(_("gnuplot required, please install first")) # get data from group listing and set the x-axis labels if group: # Parse the group list output if subgroup: s = gcore.read_command("i.group", flags="g", group=group, subgroup=subgroup, quiet=True) else: s = gcore.read_command("i.group", flags="g", group=group, quiet=True) rastermaps = s.splitlines() else: # get data from list of files and set the x-axis labels rastermaps = raster.split(",") xlabels = ["'%s' %d" % (n, i + 1) for i, n in enumerate(rastermaps)] xlabels = ",".join(xlabels) # get y-data for gnuplot-data file what = [] s = gcore.read_command("r.what", map=rastermaps, coordinates=coords, null="0", quiet=True) if len(s) == 0: gcore.fatal(_("No data returned from query")) for l in s.splitlines(): f = l.split("|") for i, v in enumerate(f): if v in ["", "*"]: f[i] = 0 else: f[i] = float(v) what.append(f) # build data files if gnuplot: draw_gnuplot(what, xlabels, output, img_fmt, coord_legend) elif textfile: write2textf(what, output) else: draw_linegraph(what)
def main(): coords = options['coordinates'] input = options['input'] output = options['output'] fs = options['separator'] proj_in = options['proj_in'] proj_out = options['proj_out'] ll_in = flags['i'] ll_out = flags['o'] decimal = flags['d'] copy_input = flags['e'] include_header = flags['c'] # check for cs2cs if not gcore.find_program('cs2cs'): gcore.fatal( _("cs2cs program not found, install PROJ.4 first: \ http://proj.maptools.org")) # check for overenthusiasm if proj_in and ll_in: gcore.fatal(_("Choose only one input parameter method")) if proj_out and ll_out: gcore.fatal(_("Choose only one output parameter method")) if ll_in and ll_out: gcore.fatal(_("Choose only one auto-projection parameter method")) if output and not gcore.overwrite() and os.path.exists(output): gcore.fatal(_("Output file already exists")) if not coords and not input: gcore.fatal(_("One of <coordinates> and <input> must be given")) if coords and input: gcore.fatal( _("Options <coordinates> and <input> are mutually exclusive")) # parse field separator # FIXME: input_x,y needs to split on multiple whitespace between them if fs == ',': ifs = ofs = ',' else: try: ifs, ofs = fs.split(',') except ValueError: ifs = ofs = fs ifs = separator(ifs) ofs = separator(ofs) # set up projection params s = gcore.read_command("g.proj", flags='j') kv = parse_key_val(s) if "XY location" in kv['+proj'] and (ll_in or ll_out): gcore.fatal(_("Unable to project to or from a XY location")) in_proj = None if ll_in: in_proj = "+proj=longlat +datum=WGS84" gcore.verbose( "Assuming LL WGS84 as input, current projection as output ") if ll_out: in_proj = gcore.read_command('g.proj', flags='jf') if proj_in: if '+' in proj_in: in_proj = proj_in else: gcore.fatal(_("Invalid PROJ.4 input specification")) if not in_proj: gcore.verbose("Assuming current location as input") in_proj = gcore.read_command('g.proj', flags='jf') in_proj = in_proj.strip() gcore.verbose("Input parameters: '%s'" % in_proj) out_proj = None if ll_out: out_proj = "+proj=longlat +datum=WGS84" gcore.verbose( "Assuming current projection as input, LL WGS84 as output ") if ll_in: out_proj = gcore.read_command('g.proj', flags='jf') if proj_out: if '+' in proj_out: out_proj = proj_out else: gcore.fatal(_("Invalid PROJ.4 output specification")) if not out_proj: gcore.fatal(_("Missing output projection parameters ")) out_proj = out_proj.strip() gcore.verbose("Output parameters: '%s'" % out_proj) # set up input file if coords: x, y = coords.split(',') tmpfile = gcore.tempfile() fd = open(tmpfile, "w") fd.write("%s%s%s\n" % (x, ifs, y)) fd.close() inf = file(tmpfile) else: if input == '-': infile = None inf = sys.stdin else: infile = input if not os.path.exists(infile): gcore.fatal(_("Unable to read input data")) inf = file(infile) gcore.debug("input file=[%s]" % infile) # set up output file if not output: outfile = None outf = sys.stdout else: outfile = output outf = open(outfile, 'w') gcore.debug("output file=[%s]" % outfile) # set up output style if not decimal: outfmt = ["-w5"] else: outfmt = ["-f", "%.8f"] if not copy_input: copyinp = [] else: copyinp = ["-E"] # do the conversion # Convert cs2cs DMS format to GRASS DMS format: # cs2cs | sed -e 's/d/:/g' -e "s/'/:/g" -e 's/"//g' cmd = ['cs2cs'] + copyinp + outfmt + \ in_proj.split() + ['+to'] + out_proj.split() p = gcore.Popen(cmd, stdin=gcore.PIPE, stdout=gcore.PIPE) tr = TrThread(ifs, inf, p.stdin) tr.start() if not copy_input: if include_header: outf.write("x%sy%sz\n" % (ofs, ofs)) for line in p.stdout: try: xy, z = line.split(' ', 1) x, y = xy.split('\t') except ValueError: gcore.fatal(line) outf.write('%s%s%s%s%s\n' % (x.strip(), ofs, y.strip(), ofs, z.strip())) else: if include_header: outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs)) for line in p.stdout: inXYZ, x, rest = line.split('\t') inX, inY = inXYZ.split(' ')[:2] y, z = rest.split(' ', 1) outf.write('%s%s%s%s%s%s%s%s%s\n' % (inX.strip(), ofs, inY.strip(), ofs, x.strip(), ofs, y.strip(), ofs, z.strip())) p.wait() if p.returncode != 0: gcore.warning( _("Projection transform probably failed, please investigate"))
def main(): filename = options['file'] type = options['type'] vect = options['vect'] e00tmp = str(os.getpid()) #### check for avcimport if not grass.find_program('avcimport'): grass.fatal(_("'avcimport' program not found, install it first") + "\n" + "http://avce00.maptools.org") #### check for e00conv if not grass.find_program('e00conv'): grass.fatal(_("'e00conv' program not found, install it first") + "\n" + "http://avce00.maptools.org") # check that the user didn't use all three, which gets past the parser. if type not in ['point','line','area']: grass.fatal(_('Must specify one of "point", "line", or "area".')) e00name = grass.basename(filename, 'e00') # avcimport only accepts 13 chars: e00shortname = e00name[:13] #check if this is a split E00 file (.e01, .e02 ...): merging = False if os.path.exists(e00name + '.e01') or os.path.exists(e00name + '.E01'): grass.message(_("Found that E00 file is split into pieces (.e01, ...). Merging...")) merging = True if vect: name = vect else: name = e00name ### do import #make a temporary directory tmpdir = grass.tempfile() grass.try_remove(tmpdir) os.mkdir(tmpdir) files = glob.glob(e00name + '.e[0-9][0-9]') + glob.glob(e00name + '.E[0-9][0-9]') for f in files: shutil.copy(f, tmpdir) #change to temporary directory to later avoid removal problems (rm -r ...) os.chdir(tmpdir) #check for binay E00 file (we can just check if import fails): #avcimport doesn't set exist status :-( if merging: files.sort() filename = "%s.cat.%s.e00" % (e00name, e00tmp) outf = file(filename, 'wb') for f in files: inf = file(f, 'rb') shutil.copyfileobj(inf, outf) inf.close() outf.close() nuldev = file(os.devnull, 'w+') grass.message(_("An error may appear next which will be ignored...")) if grass.call(['avcimport', filename, e00shortname], stdout = nuldev, stderr = nuldev) == 1: grass.message(_("E00 ASCII found and converted to Arc Coverage in current directory")) else: grass.message(_("E00 Compressed ASCII found. Will uncompress first...")) grass.try_remove(e00shortname) grass.try_remove(info) grass.call(['e00conv', filename, e00tmp + '.e00']) grass.message(_("...converted to Arc Coverage in current directory")) grass.call(['avcimport', e00tmp + '.e00', e00shortname], stderr = nuldev) #SQL name fix: name = name.replace('-', '_') ## let's import... grass.message(_("Importing %ss...") % type) layer = dict(point = 'LAB', line = 'ARC', area = ['LAB','ARC']) itype = dict(point = 'point', line = 'line', area = 'centroid') if grass.run_command('v.in.ogr', flags = 'o', dsn = e00shortname, layer = layer[type], type = itype[type], output = name) != 0: grass.fatal(_("An error occurred while running v.in.ogr")) grass.message(_("Imported <%s> vector map <%s>.") % (type, name)) #### clean up the mess for root, dirs, files in os.walk('.', False): for f in files: path = os.path.join(root, f) grass.try_remove(path) for d in dirs: path = os.path.join(root, d) grass.try_rmdir(path) os.chdir('..') os.rmdir(tmpdir) #### end grass.message(_("Done.")) # write cmd history: grass.vector_history(name)
def main(): input = options["input"] output = options["output"] fs = options["fs"] proj_in = options["proj_input"] proj_out = options["proj_output"] ll_in = flags["i"] ll_out = flags["o"] decimal = flags["d"] copy_input = flags["e"] include_header = flags["c"] #### check for cs2cs if not grass.find_program("cs2cs"): grass.fatal(_("cs2cs program not found, install PROJ.4 first: http://proj.maptools.org")) #### check for overenthusiasm if proj_in and ll_in: grass.fatal(_("Choose only one input parameter method")) if proj_out and ll_out: grass.fatal(_("Choose only one output parameter method")) if ll_in and ll_out: grass.fatal(_("Choise only one auto-projection parameter method")) if output and not grass.overwrite() and os.path.exists(output): grass.fatal(_("Output file already exists")) #### parse field separator # FIXME: input_x,y needs to split on multiple whitespace between them if fs == ",": ifs = ofs = "," else: try: ifs, ofs = fs.split(",") except ValueError: ifs = ofs = fs ifs = ifs.lower() ofs = ofs.lower() if ifs in ("space", "tab"): ifs = " " elif ifs == "comma": ifs = "," else: if len(ifs) > 1: grass.warning(_("Invalid field separator, using '%s'") % ifs[0]) try: ifs = ifs[0] except IndexError: grass.fatal(_("Invalid field separator '%s'") % ifs) if ofs.lower() == "space": ofs = " " elif ofs.lower() == "tab": ofs = "\t" elif ofs.lower() == "comma": ofs = "," else: if len(ofs) > 1: grass.warning(_("Invalid field separator, using '%s'") % ofs[0]) try: ofs = ofs[0] except IndexError: grass.fatal(_("Invalid field separator '%s'") % ifs) #### set up projection params s = grass.read_command("g.proj", flags="j") kv = grass.parse_key_val(s) if "XY location" in kv["+proj"] and (ll_in or ll_out): grass.fatal(_("Unable to project to or from a XY location")) in_proj = None if ll_in: in_proj = "+proj=longlat +datum=WGS84" grass.verbose("Assuming LL WGS84 as input, current projection as output ") if ll_out: in_proj = grass.read_command("g.proj", flags="jf") if proj_in: in_proj = proj_in if not in_proj: grass.verbose("Assuming current location as input") in_proj = grass.read_command("g.proj", flags="jf") in_proj = in_proj.strip() grass.verbose("Input parameters: '%s'" % in_proj) out_proj = None if ll_out: out_proj = "+proj=longlat +datum=WGS84" grass.verbose("Assuming current projection as input, LL WGS84 as output ") if ll_in: out_proj = grass.read_command("g.proj", flags="jf") if proj_out: out_proj = proj_out if not out_proj: grass.fatal(_("Missing output projection parameters ")) out_proj = out_proj.strip() grass.verbose("Output parameters: '%s'" % out_proj) #### set up input file if input == "-": infile = None inf = sys.stdin else: infile = input if not os.path.exists(infile): grass.fatal(_("Unable to read input data")) inf = file(infile) grass.debug("input file=[%s]" % infile) #### set up output file if not output: outfile = None outf = sys.stdout else: outfile = output outf = open(outfile, "w") grass.debug("output file=[%s]" % outfile) #### set up output style if not decimal: outfmt = ["-w5"] else: outfmt = ["-f", "%.8f"] if not copy_input: copyinp = [] else: copyinp = ["-E"] #### do the conversion # Convert cs2cs DMS format to GRASS DMS format: # cs2cs | sed -e 's/d/:/g' -e "s/'/:/g" -e 's/"//g' cmd = ["cs2cs"] + copyinp + outfmt + in_proj.split() + ["+to"] + out_proj.split() p = grass.Popen(cmd, stdin=grass.PIPE, stdout=grass.PIPE) tr = TrThread(ifs, inf, p.stdin) tr.start() if not copy_input: if include_header: outf.write("x%sy%sz\n" % (ofs, ofs)) for line in p.stdout: xy, z = line.split(" ", 1) x, y = xy.split("\t") outf.write("%s%s%s%s%s\n" % (x.strip(), ofs, y.strip(), ofs, z.strip())) else: if include_header: outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs)) for line in p.stdout: inXYZ, x, rest = line.split("\t") inX, inY = inXYZ.split(" ")[:2] y, z = rest.split(" ", 1) outf.write( "%s%s%s%s%s%s%s%s%s\n" % (inX.strip(), ofs, inY.strip(), ofs, x.strip(), ofs, y.strip(), ofs, z.strip()) ) p.wait() if p.returncode != 0: grass.warning(_("Projection transform probably failed, please investigate"))
def main(): export_shifted = flags['s'] currmapset = grass.gisenv()['MAPSET'] #### check for v.in.ply, v.out.ply if not grass.find_program("v.in.ply", '--help'): grass.fatal( _("The GRASS addon v.in.ply was not found, please install it first.\n" )) if not grass.find_program("v.out.ply", '--help'): grass.fatal( _("The GRASS addon v.out.ply was not found, please install it first.\n" )) # import input PLY file infile = options['input'] if not os.path.exists(infile): grass.fatal(_("Unable to read input file <%s>") % infile) grass.debug("input file=[%s]" % infile) if not infile[-4:].lower() == '.ply': grass.fatal(_("Input file must end with .ply or .PLY")) gcpfile = infile[:-4] + ".txt" srcdir, ply = os.path.split(infile) ply = ply[:-4] if not os.path.exists(gcpfile): gcpfile = infile[:-4] + ".TXT" if not os.path.exists(gcpfile): grass.fatal( _("Input file with GCPs must be <%s> or <%s>") % ply + ".txt", ply + ".TXT") if options['output'] is not None and options['output'] != '': ply = options['output'] clist = list() plydesc = grass.read_command('v.in.ply', flags='p', input=infile, output=ply) # remember column names for vertices currname = '' currprop = '' for l in plydesc.splitlines(): f = l.split(':') if f[0] == 'element name': # new element currname = f[1].strip() currprop = '' if f[0] == 'property name': currprop = f[1].strip() if currname == 'vertex' and currprop not in ['x', 'y', 'z']: clist.append(currprop) columns = ','.join(clist) grass.run_command('v.in.ply', flags='b', input=infile, output=ply) # import vector exists? found = grass.find_file(ply, element='vector', mapset=currmapset) if found['name'] != ply: grass.fatal(_('PLY import failed!')) # detach table table = gvector.vector_layer_db(map=ply, layer=1)['table'] grass.run_command('v.db.connect', map=ply, layer=1, flags='d') # print RMS rmsfile = os.path.join(srcdir, ply + "_rms.csv") grass.run_command('v.rectify', input=ply, output=ply + '_georef', points=gcpfile, flags='3bor', separator=';', rmsfile=rmsfile) # georectify ply_georef = ply + '_georef' grass.run_command('v.rectify', input=ply, output=ply_georef, points=gcpfile, flags='3bo') # output vector exists? found = grass.find_file(ply_georef, element='vector', mapset=currmapset) if found['name'] != ply_georef: grass.run_command('v.db.connect', map=ply, layer=1, table=table, key='cat') grass.fatal('PLY import failed!') grass.run_command('v.db.connect', map=ply_georef, layer=1, table=table, key='cat') output = os.path.join(srcdir, ply_georef + '.ply') grass.run_command('v.out.ply', input=ply_georef, output=output, columns=columns) grass.run_command('v.db.connect', map=ply_georef, layer=1, flags='d') if export_shifted: vinfo = gvector.vector_info(map=ply_georef) north_center = (float(vinfo['north']) + float(vinfo['south'])) / -2.0 east_center = (float(vinfo['east']) + float(vinfo['west'])) / -2.0 height_center = (float(vinfo['top']) + float(vinfo['bottom'])) / -2.0 ply_shifted = ply_georef + '_shifted' grass.run_command('v.transform', input=ply_georef, layer=-1, output=ply_shifted, xshift=east_center, yshift=north_center, zshift=height_center, xscale=1.0, yscale=1.0, zscale=1.0, zrot=0.0, flags='b') # output vector exists? found = grass.find_file(ply_shifted, element='vector', mapset=currmapset) if found['name'] != ply_shifted: grass.run_command('v.db.connect', map=ply, layer=1, table=table, key='cat') grass.fatal('PLY import failed!') grass.run_command('v.db.connect', map=ply_shifted, layer=1, table=table, key='cat') output = os.path.join(srcdir, ply_shifted + '.ply') grass.run_command('v.out.ply', input=ply_shifted, output=output, columns=columns) grass.run_command('v.db.connect', map=ply_shifted, layer=1, flags='d') grass.run_command('v.db.connect', map=ply, layer=1, table=table, key='cat') grass.message( _("Done: Pointcloud '%s' has been successfully imported, georeferenced, and exported" ) % ply)
def main(): global tmp global sine_cosine_replic, outercircle, vector global totalvalidnumber, totalnumber, maxradius map = options['map'] undef = options['undef'] eps = options['output'] xgraph = flags['x'] tmp = gcore.tempfile() if eps and xgraph: gcore.fatal(_("Please select only one output method")) # check if we have xgraph (if no EPS output requested) if xgraph and not gcore.find_program('xgraph'): gcore.fatal( _("xgraph required, please install first (www.xgraph.org)")) raster_map_required(map) ################################# # this file contains everything: rawfile = tmp + "_raw" rawf = file(rawfile, 'w') gcore.run_command('r.stats', flags='1', input=map, stdout=rawf) rawf.close() rawf = file(rawfile) totalnumber = 0 for line in rawf: totalnumber += 1 rawf.close() gcore.message( _("Calculating statistics for polar diagram... (be patient)")) # wipe out NULL data and undef data if defined by user # - generate degree binned to integer, eliminate NO DATA (NULL): # change 360 to 0 to close polar diagram: rawf = file(rawfile) nvals = 0 sumcos = 0 sumsin = 0 freq = {} for line in rawf: line = line.rstrip('\r\n') if line in ['*', undef]: continue nvals += 1 x = float(line) rx = math.radians(x) sumcos += math.cos(rx) sumsin += math.sin(rx) ix = round(x) if ix == 360: ix = 0 if ix in freq: freq[ix] += 1 else: freq[ix] = 1 rawf.close() totalvalidnumber = nvals if totalvalidnumber == 0: gcore.fatal(_("No data pixel found")) ################################# # unit vector on raw data converted to radians without no data: unitvector = (sumcos / nvals, sumsin / nvals) ################################# # how many are there?: occurrences = sorted([(math.radians(x), freq[x]) for x in freq]) # find the maximum value maxradius = max([f for a, f in occurrences]) # now do cos() sin() sine_cosine = [(math.cos(a) * f, math.sin(a) * f) for a, f in occurrences] sine_cosine_replic = ['"Real data angles'] + sine_cosine + sine_cosine[0:1] if eps or xgraph: outercircle = [] outercircle.append('"All Data incl. NULLs') scale = 1.0 * totalnumber / totalvalidnumber * maxradius for i in range(0, 361): a = math.radians(i) x = math.cos(a) * scale y = math.sin(a) * scale outercircle.append((x, y)) # fix vector length to become visible (x? of $MAXRADIUS): vector = [] vector.append('"Avg. Direction\n') vector.append((0, 0)) vector.append((unitvector[0] * maxradius, unitvector[1] * maxradius)) ########################################################### # Now output: if eps: psout = basename(eps, 'eps') + '.eps' plot_eps(psout) elif xgraph: plot_xgraph() else: plot_dgraph() gcore.message(_("Average vector:")) gcore.message( _("direction: %.1f degrees CCW from East") % math.degrees(math.atan2(unitvector[1], unitvector[0]))) gcore.message( _("magnitude: %.1f percent of fullscale") % (100 * math.hypot(unitvector[0], unitvector[1])))
def main(): handler = options['handler'] if options['tempfile']: img_tmp = options['tempfile'] #TODO: add option for GRASS_RENDER_FILE_COMPRESSION=0,1-9 else: img_tmp = grass.tempfile() os.remove(img_tmp) img_tmp += ".bmp" if flags['b']: print('GRASS_RENDER_FILE="%s"' % img_tmp) if not os.environ.has_key("GRASS_RENDER_WIDTH"): print('GRASS_RENDER_WIDTH=%s' % options['width']) if not os.environ.has_key("GRASS_RENDER_HEIGHT"): print('GRASS_RENDER_HEIGHT=%s' % options['height']) if flags['c']: print('GRASS_RENDER_IMMEDIATE=cairo') else: print('GRASS_RENDER_IMMEDIATE=PNG') print('GRASS_RENDER_FILE_MAPPED=TRUE') print('GRASS_RENDER_FILE_READ=TRUE') print( 'export GRASS_RENDER_FILE GRASS_RENDER_WIDTH GRASS_RENDER_HEIGHT GRASS_RENDER_IMMEDIATE GRASS_RENDER_FILE_MAPPED GRASS_RENDER_FILE_READ;' ) print('d.erase bgcolor=%s;' % options['color']) if handler == "none": grass.message("Image file is '%s'" % img_tmp) elif handler == "qiv": print('qiv -e -T "%s" &' % img_tmp) # add --center ? else: print('%s image="%s" percent=%s &' % (handler, img_tmp, options['percent'])) sys.exit(0) if flags['d']: print('rem DOS export not yet implemented') sys.exit(0) ## rest of this won't work, as parent can't inherit from the child.. ## (unless we do some ugly g.gisenv) ## ... any ideas? end by running grass.call(['bash'])? if not grass.find_program(handler, '--help'): grass.fatal(_("'%s' not found.") % handler) os.environ['GRASS_RENDER_FILE'] = img_tmp if not os.environ.has_key("GRASS_RENDER_WIDTH"): os.environ['GRASS_RENDER_WIDTH'] = options['width'] if not os.environ.has_key("GRASS_RENDER_HEIGHT"): os.environ['GRASS_RENDER_HEIGHT'] = options['height'] if flags['c']: os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo' os.environ['GRASS_RENDER_FILE_MAPPED'] = 'TRUE' os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE' #? os.environ['GRASS_PNG_AUTO_WRITE'] = 'FALSE' grass.run_command('d.erase', bgcolor=options['color']) if handler == "qiv": ret = grass.call(['qiv', '-e', '-T', img_tmp]) else: ret = grass.exec_command(handler, image=img_tmp, percent=options['percent']) os.remove(img_tmp) sys.exit(ret)