def main(): # check if input file exists infile = options['input'] gfile = grass.find_file(infile, element='vector') if not gfile['name']: grass.fatal(_("Vector map <%s> not found") % infile) # create tempfile and write ascii file of input temp_in = grass.tempfile() try: grass.run_command('v.out.ascii', overwrite=True, input=gfile['name'], output=temp_in) except CalledModuleError: grass.fatal(_("Failed to export vector in a temporary file")) # x and y of median point medx, medy = point_med(temp_in) try_remove(temp_in) # prepare the output output = "%f|%f" % (medx, medy) map_name = options['output'] overwrite = os.getenv('GRASS_OVERWRITE') # if output is not set return to stdout if map_name == '-': grass.message(output) # else else: # output file goutfile = grass.find_file(name=map_name, element='vector', mapset='.') # output tempfile temp_out = grass.tempfile() file_out = open(temp_out, 'w') file_out.write(output) file_out.close() # output file exists and not overwrite if goutfile['file'] and overwrite != '1': grass.fatal(_("Vector map <%s> already exists") % map_name) # output file exists and overwrite elif goutfile['file'] and overwrite == '1': grass.warning( _("Vector map <%s> already exists and will be overwritten") % map_name) grass.run_command('v.in.ascii', overwrite=True, input=temp_out, output=map_name) # output file not exists else: grass.run_command('v.in.ascii', input=temp_out, output=map_name) try_remove(temp_out)
def AddTmpVectMap(self, mapName, msg): """New temporary map :return: instance of VectMap representing temporary map """ currMapSet = grass.gisenv()["MAPSET"] tmpMap = grass.find_file(name=mapName, element="vector", mapset=currMapSet) fullName = tmpMap["fullname"] # map already exists if fullName: # TODO move dialog out of class, AddTmpVectMap(self, mapName, # overvrite = False) dlg = wx.MessageDialog( parent=self.parent, message=msg, caption=_("Overwrite map layer"), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE, ) ret = dlg.ShowModal() dlg.Destroy() if ret == wx.ID_NO: return None else: fullName = mapName + "@" + currMapSet newVectMap = VectMap(self.mapWin, fullName) self.tmpMaps.append(newVectMap) return newVectMap
def GetVectorNumberOfLayers(vector): """Get list of all vector layers""" layers = list() if not vector: return layers fullname = grass.find_file(name=vector, element='vector')['fullname'] if not fullname: Debug.msg( 5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector) return layers ret, out, msg = RunCommand('v.category', getErrorMsg=True, read=True, input=fullname, option='layers') if ret != 0: sys.stderr.write( _("Vector map <%(map)s>: %(msg)s\n") % { 'map': fullname, 'msg': msg }) return layers else: Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret) for layer in out.splitlines(): layers.append(layer) Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \ (fullname, ','.join(layers))) return layers
def OnOK(self, event): mapName = self.GetMapName() if not mapName: GWarning(parent=self.GetParent(), message=_( "Please specify name for a new raster map")) else: found = gcore.find_file( name=mapName, mapset=gcore.gisenv()['MAPSET']) if found and found['mapset'] == gcore.gisenv()['MAPSET']: dlgOverwrite = wx.MessageDialog( self.GetParent(), message=_( "Raster map <%s> already exists " "in the current mapset. " "Do you want to overwrite it?") % mapName, caption=_("Overwrite?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION) if not dlgOverwrite.ShowModal() == wx.ID_YES: dlgOverwrite.Destroy() return else: dlgOverwrite.Destroy() self.EndModal(wx.ID_OK) else: self.EndModal(wx.ID_OK)
def firstConnect(): print_message("v.in.ogr") grass.run_command( "v.in.ogr", input="PG:", layer=layer, output=ogr, overwrite=True, flags="t", type=typ, quiet=True, ) # if vector already exits, remove dblink (original table) if grass.find_file(nat, element="vector")["fullname"]: grass.run_command("v.db.connect", map=nat, flags="d", layer="1", quiet=True) grass.run_command("v.db.connect", map=nat, flags="d", layer="2", quiet=True) grass.run_command( "v.category", input=ogr, output=nat, option="transfer", overwrite=True, layer="1,2", quiet=True, ) grass.run_command( "v.db.connect", map=nat, table=layer, key=key, layer="1", quiet=True )
def AddTmpVectMap(self, mapName, msg): """New temporary map :return: instance of VectMap representing temporary map """ currMapSet = grass.gisenv()['MAPSET'] tmpMap = grass.find_file(name=mapName, element='vector', mapset=currMapSet) fullName = tmpMap["fullname"] # map already exists if fullName: # TODO move dialog out of class, AddTmpVectMap(self, mapName, # overvrite = False) dlg = wx.MessageDialog(parent=self.parent, message=msg, caption=_("Overwrite map layer"), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE) ret = dlg.ShowModal() dlg.Destroy() if ret == wx.ID_NO: return None else: fullName = mapName + "@" + currMapSet newVectMap = VectMap(self.mapWin, fullName) self.tmpMaps.append(newVectMap) return newVectMap
def Update(self): if grass.find_file(name="MASK", element="cell", mapset=grass.gisenv()["MAPSET"])["name"]: self.Show() else: self.Hide()
def AddRenderLayer(self, cmd=None, colorsCmd=None): """Add map from map window layers to render """ if not self.mapWin: return False existsMap = grass.find_file(name=self.fullName, element='vector', mapset=grass.gisenv()['MAPSET']) if not existsMap["name"]: self.DeleteRenderLayer() return False if not cmd: cmd = [] cmd.insert(0, 'd.vect') cmd.append('map=%s' % self.fullName) if self.renderLayer: self.DeleteRenderLayer() if colorsCmd: colorsCmd.append('map=%s' % self.fullName) layerStyleVnetColors = cmdlist_to_tuple(colorsCmd) RunCommand(layerStyleVnetColors[0], **layerStyleVnetColors[1]) self.renderLayer = self.mapWin.Map.AddLayer( ltype="vector", command=cmd, name=self.fullName, active=True, opacity=1.0, render=False, pos=-1) return True
def GetVectorNumberOfLayers(vector): """Get list of all vector layers""" layers = list() if not vector: return layers fullname = grass.find_file(name=vector, element="vector")["fullname"] if not fullname: Debug.msg( 5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector ) return layers ret, out, msg = RunCommand( "v.category", getErrorMsg=True, read=True, input=fullname, option="layers" ) if ret != 0: sys.stderr.write( _("Vector map <%(map)s>: %(msg)s\n") % {"map": fullname, "msg": msg} ) return layers else: Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret) for layer in out.splitlines(): layers.append(layer) Debug.msg( 3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % (fullname, ",".join(layers)), ) return layers
def main(): options, flags = gcore.parser() if options['input']: map_name = gcore.find_file(name=options['input'], element='cell')['fullname'] if not map_name: gcore.fatal(_("Raster map <{raster}> not found").format(raster=options['input'])) # define display driver (avoid 'no graphics device selected' error at start up) driver = UserSettings.Get(group='display', key='driver', subkey='type') if driver == 'png': os.environ['GRASS_RENDER_IMMEDIATE'] = 'png' else: os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo' # launch application app = wx.App() if not CheckWxVersion([2, 9]): wx.InitAllImageHandlers() # show main frame giface = StandaloneGrassInterface() frame = ExampleMapFrame(parent=None, giface=giface) if options['input']: giface.WriteLog(_("Loading raster map <{raster}>...").format(raster=map_name)) frame.SetLayer(map_name) frame.Show() app.MainLoop()
def Update(self): if grass.find_file(name='MASK', element='cell', mapset=grass.gisenv()['MAPSET'])['name']: self.Show() else: self.Hide()
def GetAllVectorLayers(vector): """!Returns list of all vector layers as strings. @param vector name of vector map """ layers = [] if not vector: return layers fullname = grass.find_file(name = vector, element = 'vector')['fullname'] if not fullname: Debug.msg(3, "utils.GetAllVectorLayers(): vector map <%s> not found" % vector) return layers ret, out, msg = RunCommand('v.category', getErrorMsg = True, read = True, quiet = True, option = 'layers', input = fullname) if ret != 0: sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg }) return layers Debug.msg(1, "utils.GetAllVectorLayers(): ret %s" % ret) for layer in out.splitlines(): layers.append(layer) Debug.msg(3, "utils.GetAllVectorLayers(): vector=%s -> %s" % \ (fullname, ','.join(layers))) return layers
def SetName(self, name): """Sets name of the layer. It checks the name of the layer by g.findfile (raises ValueError if map does not exist). Therefore map type has to be set first. """ if not self.hidden: fullName = name.split('@') if len( fullName) == 1 and self._mapType != 'rgb': # skip checking rgb maps for now if self._mapType is None: raise ValueError( "To set layer name, the type of layer must be specified.") res = gcore.find_file( name=fullName, element=self._internalTypes[ self._mapType]) if not res['mapset']: raise ValueError( "Map <{name}> not found.".format( name=name)) self._name = name + '@' + res['mapset'] else: self._name = name self.label = name
def GetVectorNumberOfLayers(vector): """Get list of all vector layers""" layers = list() if not vector: return layers fullname = grass.find_file(name=vector, element='vector')['fullname'] if not fullname: Debug.msg( 5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector) return layers ret, out, msg = RunCommand('v.category', getErrorMsg=True, read=True, input=fullname, option='layers') if ret != 0: sys.stderr.write( _("Vector map <%(map)s>: %(msg)s\n") % {'map': fullname, 'msg': msg}) return layers else: Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret) for layer in out.splitlines(): layers.append(layer) Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % (fullname, ','.join(layers))) return layers
def SetName(self, name): """Sets name of the layer. It checks the name of the layer by g.findfile (raises ValueError if map does not exist). Therefore map type has to be set first. """ if not self.hidden: fullName = name.split('@') if len( fullName ) == 1 and self._mapType != 'rgb': # skip checking rgb maps for now if self._mapType is None: raise ValueError( "To set layer name, the type of layer must be specified." ) res = gcore.find_file( name=fullName, element=self._internalTypes[self._mapType]) if not res['mapset']: raise ValueError( "Map <{name}> not found.".format(name=name)) self._name = name + '@' + res['mapset'] else: self._name = name self.label = name
def main(): options, flags = gcore.parser() if options["input"]: map_name = gcore.find_file(name=options["input"], element="cell")["fullname"] if not map_name: gcore.fatal(_("Raster map <{raster}> not found").format(raster=options["input"])) # define display driver (avoid 'no graphics device selected' error at start up) driver = UserSettings.Get(group="display", key="driver", subkey="type") if driver == "png": os.environ["GRASS_RENDER_IMMEDIATE"] = "png" else: os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo" # launch application app = wx.App() if not CheckWxVersion([2, 9]): wx.InitAllImageHandlers() # show main frame giface = StandaloneGrassInterface() frame = ExampleMapFrame(parent=None, giface=giface) if options["input"]: giface.WriteLog(_("Loading raster map <{raster}>...").format(raster=map_name)) frame.SetLayer(map_name) frame.Show() app.MainLoop()
def check_map_name(name): # cell means any raster in this context # mapset needs to retrieved in very call, ok for here if gcore.find_file(name, element='cell', mapset=gcore.gisenv()['MAPSET'])['file']: gcore.fatal( _("Raster map <%s> already exists. " "Remove the existing map or allow overwrite.") % name)
def checkMapExists(name, typ='raster'): """Check if a map already exist in the working mapset""" env = grass.gisenv() mapset = env['MAPSET'] mapp = grass.find_file(name, typ, mapset) if mapp.name != '': return True else: return False
def checkMapExists(name, typ='rast'): """Check if a map already exist in the working mapset""" env = grass.gisenv() mapset = env['MAPSET'] mapp = grass.find_file(name, typ, mapset) if mapp.name != '': return True else: return False
def ImportFile(self, filePath): """Tries to import file as vector or raster. If successfull sets default region from imported map. """ RunCommand('db.connect', flags='c') mapName = os.path.splitext(os.path.basename(filePath))[0] vectors = RunCommand('v.in.ogr', dsn=filePath, flags='l', read=True) wx.BeginBusyCursor() wx.Yield() if mapName in vectors: # vector detected returncode, error = RunCommand('v.in.ogr', dsn=filePath, output=mapName, getErrorMsg=True) else: returncode, error = RunCommand('r.in.gdal', input=filePath, output=mapName, getErrorMsg=True) wx.EndBusyCursor() if returncode != 0: GError(parent=self, message=_("Import of <%(name)s> failed.\n" "Reason: %(msg)s") % ({ 'name': filePath, 'msg': error })) else: GMessage(message=_("Data file <%(name)s> imported successfully.") % {'name': filePath}, parent=self) if not grass.find_file(element = 'cell', name = mapName)['fullname'] and \ not grass.find_file(element = 'vector', name = mapName)['fullname']: GError(parent=self, message=_("Map <%s> not found.") % mapName) else: if mapName in vectors: args = {'vect': mapName} else: args = {'rast': mapName} RunCommand('g.region', flags='s', parent=self, **args)
def createVect(view_nat): grass.run_command('v.in.ogr', dsn="PG:", layer = layer, output = ogr, overwrite=True, flags='t', key=key, type=typ, quiet=True) # if vector already exits, remove dblink (original table) if grass.find_file(view_nat, element='vector')['fullname']: grass.run_command('v.db.connect', map=view_nat, flags='d', layer='1', quiet=True) grass.run_command('v.db.connect', map=view_nat, flags='d', layer='2', quiet=True) grass.run_command('v.category', input=ogr, output=view_nat, option="transfer", overwrite=True, layer="1,2", quiet=True) grass.run_command('v.db.connect', map=view_nat, table=layer, key=key, layer='1', quiet=True) grass.run_command('v.db.connect', map=view_nat, table=view, key=key, layer='2', quiet=True) if options['color']: setColor(view_nat)
def contours(scanned_elev, new, env, step=None): if not step: info = grast.raster_info(scanned_elev) step = (info['max'] - info['min']) / 12. try: if gcore.find_file(new, element='vector')['name']: gisenv = gcore.gisenv() path_to_vector = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], gisenv['MAPSET'], 'vector', new) shutil.rmtree(path_to_vector) gcore.run_command('r.contour', input=scanned_elev, output=new, step=step, flags='t', env=env) except: # catching exception when a vector is added to GUI in the same time pass
def ImportFile(self, filePath): """Tries to import file as vector or raster. If successfull sets default region from imported map. """ RunCommand('db.connect', flags='c') mapName = os.path.splitext(os.path.basename(filePath))[0] vectors = RunCommand('v.in.ogr', dsn = filePath, flags = 'l', read = True) wx.BeginBusyCursor() wx.Yield() if mapName in vectors: # vector detected returncode, error = RunCommand('v.in.ogr', dsn = filePath, output = mapName, getErrorMsg = True) else: returncode, error = RunCommand('r.in.gdal', input = filePath, output = mapName, getErrorMsg = True) wx.EndBusyCursor() if returncode != 0: GError(parent = self, message = _("Import of <%(name)s> failed.\n" "Reason: %(msg)s") % ({'name': filePath, 'msg': error})) else: GMessage(message = _("Data file <%(name)s> imported successfully.") % {'name': filePath}, parent = self) if not grass.find_file(element = 'cell', name = mapName)['fullname'] and \ not grass.find_file(element = 'vector', name = mapName)['fullname']: GError(parent = self, message = _("Map <%s> not found.") % mapName) else: if mapName in vectors: args = {'vect' : mapName} else: args = {'rast' : mapName} RunCommand('g.region', flags = 's', parent = self, **args)
def OnSelectRaster(self, event): """!Opens dialog to select raster map""" dlg = ExampleMapDialog(self) if dlg.ShowModal() == wx.ID_OK: raster = gcore.find_file(name=dlg.GetRasterMap(), element='cell') if raster['fullname']: self.SetLayer(name=raster['fullname']) else: # show user that the map name is incorrect GError(parent=self, message=_("Raster map <{raster}> not found").format(raster=dlg.GetRasterMap())) dlg.Destroy()
def main(): options, flags = gcore.parser() import wx from grass.script.setup import set_gui_path set_gui_path() from core.globalvar import CheckWxVersion, MAP_WINDOW_SIZE from core.giface import StandaloneGrassInterface from core.settings import UserSettings from example.frame import ExampleMapDisplay if options["input"]: map_name = gcore.find_file(name=options["input"], element="cell")["fullname"] if not map_name: gcore.fatal( _("Raster map <{raster}> not found").format( raster=options["input"])) # define display driver (avoid 'no graphics device selected' error at start up) driver = UserSettings.Get(group="display", key="driver", subkey="type") if driver == "png": os.environ["GRASS_RENDER_IMMEDIATE"] = "png" else: os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo" # launch application app = wx.App() if not CheckWxVersion([2, 9]): wx.InitAllImageHandlers() # show main frame frame = wx.Frame(parent=None, size=MAP_WINDOW_SIZE, title=_("Example Tool - GRASSGIS")) frame = ExampleMapDisplay( parent=frame, giface=StandaloneGrassInterface(), ) if options["input"]: frame.giface.WriteLog( _("Loading raster map <{raster}>...").format(raster=map_name)) frame.SetLayer(map_name) frame.Show() app.MainLoop()
def GetVectorNumberOfLayers(vector, parent=None): """!Get list of vector layers @param vector name of vector map @param parent parent window (to show dialog) or None """ layers = [] if not vector: return layers fullname = grass.find_file(name=vector, element='vector')['fullname'] if not fullname: Debug.msg( 5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector) return layers ret, out, msg = RunCommand('v.db.connect', getErrorMsg=True, read=True, flags='g', map=fullname, fs=';') if ret != 0: sys.stderr.write( _("Vector map <%(map)s>: %(msg)s\n") % { 'map': fullname, 'msg': msg }) return layers Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret) for line in out.splitlines(): try: layer = line.split(';')[0] if '/' in layer: layer = layer.split('/')[0] layers.append(layer) except IndexError: pass Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \ (fullname, ','.join(layers))) return layers
def OnRemoveMask(self, event): if grass.find_file(name="MASK", element="cell", mapset=grass.gisenv()["MAPSET"])["name"]: dlg = wx.MessageDialog( self.mapFrame, message=_("Are you sure that you want to remove the MASK?"), caption=_("Remove MASK"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, ) if dlg.ShowModal() != wx.ID_YES: dlg.Destroy() return RunCommand("r.mask", flags="r") self.Hide() self.mapFrame.OnRender(event=None)
def createVect(view_nat): grass.run_command( "v.in.ogr", input="PG:", layer=layer, output=ogr, overwrite=True, flags="t", key=key, type=typ, quiet=True, ) # if vector already exits, remove dblink (original table) if grass.find_file(view_nat, element="vector")["fullname"]: grass.run_command( "v.db.connect", map=view_nat, flags="d", layer="1", quiet=True ) grass.run_command( "v.db.connect", map=view_nat, flags="d", layer="2", quiet=True ) grass.run_command( "v.category", input=ogr, output=view_nat, option="transfer", overwrite=True, layer="1,2", quiet=True, ) grass.run_command( "v.db.connect", map=view_nat, table=layer, key=key, layer="1", quiet=True ) grass.run_command( "v.db.connect", map=view_nat, table=view, key=key, layer="2", quiet=True ) if options["color"]: setColor(view_nat)
def firstConnect(): print_message('v.in.ogr') grass.run_command('v.in.ogr', dsn="PG:", layer = layer, output = ogr, overwrite=True, flags='t', type=typ, quiet=True) # if vector already exits, remove dblink (original table) if grass.find_file(nat, element='vector')['fullname']: grass.run_command('v.db.connect', map=nat, flags='d', layer='1', quiet=True) grass.run_command('v.db.connect', map=nat, flags='d', layer='2', quiet=True) grass.run_command('v.category', input=ogr, output=nat, option="transfer", overwrite=True, layer="1,2", quiet=True) grass.run_command('v.db.connect', map=nat, table=layer, key=key, layer='1', quiet=True)
def GetVectorNumberOfLayers(vector, parent = None): """!Get list of vector layers @param vector name of vector map @param parent parent window (to show dialog) or None """ layers = [] if not vector: return layers fullname = grass.find_file(name = vector, element = 'vector')['fullname'] if not fullname: Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector) return layers ret, out, msg = RunCommand('v.db.connect', getErrorMsg = True, read = True, flags = 'g', map = fullname, fs = ';') if ret != 0: sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg }) return layers Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret) for line in out.splitlines(): try: layer = line.split(';')[0] if '/' in layer: layer = layer.split('/')[0] layers.append(layer) except IndexError: pass Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \ (fullname, ','.join(layers))) return layers
def GetAllVectorLayers(vector): """!Returns list of all vector layers as strings. @param vector name of vector map """ layers = [] if not vector: return layers fullname = grass.find_file(name=vector, element='vector')['fullname'] if not fullname: Debug.msg( 3, "utils.GetAllVectorLayers(): vector map <%s> not found" % vector) return layers ret, out, msg = RunCommand('v.category', getErrorMsg=True, read=True, quiet=True, option='layers', input=fullname) if ret != 0: sys.stderr.write( _("Vector map <%(map)s>: %(msg)s\n") % { 'map': fullname, 'msg': msg }) return layers Debug.msg(1, "utils.GetAllVectorLayers(): ret %s" % ret) for layer in out.splitlines(): layers.append(layer) Debug.msg(3, "utils.GetAllVectorLayers(): vector=%s -> %s" % \ (fullname, ','.join(layers))) return layers
def AddRenderLayer(self, cmd=None, colorsCmd=None): """Add map from map window layers to render """ if not self.mapWin: return False existsMap = grass.find_file( name=self.fullName, element="vector", mapset=grass.gisenv()["MAPSET"] ) if not existsMap["name"]: self.DeleteRenderLayer() return False if not cmd: cmd = [] cmd.insert(0, "d.vect") cmd.append("map=%s" % self.fullName) if self.renderLayer: self.DeleteRenderLayer() if colorsCmd: colorsCmd.append("map=%s" % self.fullName) layerStyleVnetColors = cmdlist_to_tuple(colorsCmd) RunCommand(layerStyleVnetColors[0], **layerStyleVnetColors[1]) self.renderLayer = self.mapWin.Map.AddLayer( ltype="vector", command=cmd, name=self.fullName, active=True, opacity=1.0, render=False, pos=-1, ) return True
def CreateTttb(self, params): outputMap = params["output"] mapName, mapSet = ParseMapStr(outputMap) if mapSet != grass.gisenv()["MAPSET"]: GMessage(parent=self, message=_("Map can be created only in current mapset")) return False existsMap = grass.find_file(name=mapName, element="vector", mapset=grass.gisenv()["MAPSET"]) if existsMap["name"]: dlg = wx.MessageDialog( parent=self.guiparent, message=_("Vector map %s already exists. " + "Do you want to overwrite it?") % (existsMap["fullname"]), caption=_("Overwrite vector map"), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE, ) ret = dlg.ShowModal() dlg.Destroy() if ret == wx.ID_NO: return False cmdTtb = [ "v.net.turntable", "input=" + params["input"], "output=" + params["output"], "arc_layer=" + params["arc_layer"], "turn_layer=" + params["turn_layer"], "turn_cat_layer=" + params["turn_cat_layer"], "--overwrite", ] self.goutput.RunCmd(command=cmdTtb, onDone=self._createTtbDone) return True
def CreateTttb(self, params): outputMap = params["output"] mapName, mapSet = ParseMapStr(outputMap) if mapSet != grass.gisenv()['MAPSET']: GMessage(parent = self, message = _("Map can be created only in current mapset")) return False existsMap = grass.find_file(name = mapName, element = 'vector', mapset = grass.gisenv()['MAPSET']) if existsMap["name"]: dlg = wx.MessageDialog(parent = self.guiparent, message = _("Vector map %s already exists. " + "Do you want to overwrite it?") % (existsMap["fullname"]), caption = _("Overwrite vector map"), style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE) ret = dlg.ShowModal() dlg.Destroy() if ret == wx.ID_NO: return False cmdTtb = [ "v.net.turntable", "input=" + params["input"], "output=" + params["output"], "alayer=" + params["alayer"], "tlayer=" + params["tlayer"], "tuclayer=" + params["tuclayer"], "--overwrite", ] self.goutput.RunCmd(command = cmdTtb, onDone = self._createTtbDone) return True
def main(): infile = options['input'] # create temporary directory global tmp_dir tmp_dir = grass.tempdir() grass.debug('tmp_dir = %s' % tmp_dir) # check if the input file exists if not os.path.exists(infile): grass.fatal(_("File <%s> not found") % infile) # copy the files to tmp dir input_base = os.path.basename(infile) shutil.copyfile(infile, os.path.join(tmp_dir, input_base)) os.chdir(tmp_dir) tar = tarfile.TarFile.open(name=input_base, mode='r') try: data_name = tar.getnames()[0] except: grass.fatal(_("Pack file unreadable")) if flags['p']: # print proj info and exit try: for fname in ['PROJ_INFO', 'PROJ_UNITS']: f = tar.extractfile(fname) sys.stdout.write(f.read()) except KeyError: grass.fatal( _("Pack file unreadable: file '{}' missing".format(fname))) tar.close() return 0 # set the output name if options['output']: map_name = options['output'] else: map_name = data_name # grass env gisenv = grass.gisenv() mset_dir = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], gisenv['MAPSET']) new_dir = os.path.join(mset_dir, 'vector', map_name) gfile = grass.find_file(name=map_name, element='vector', mapset='.') overwrite = os.getenv('GRASS_OVERWRITE') if gfile['file'] and overwrite != '1': grass.fatal(_("Vector map <%s> already exists") % map_name) elif overwrite == '1' and gfile['file']: grass.warning( _("Vector map <%s> already exists and will be overwritten") % map_name) grass.run_command('g.remove', flags='f', quiet=True, type='vector', name=map_name) shutil.rmtree(new_dir, True) # extract data tar.extractall() tar.close() if os.path.exists(os.path.join(data_name, 'coor')): pass elif os.path.exists(os.path.join(data_name, 'cell')): grass.fatal( _("This GRASS GIS pack file contains raster data. Use " "r.unpack to unpack <%s>" % map_name)) else: grass.fatal(_("Pack file unreadable")) # check projection compatibility in a rather crappy way loc_proj = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO') loc_proj_units = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_UNITS') skip_projection_check = False if not os.path.exists(os.path.join(tmp_dir, 'PROJ_INFO')): if os.path.exists(loc_proj): grass.fatal( _("PROJ_INFO file is missing, unpack vector map in XY (unprojected) location." )) skip_projection_check = True # XY location if not skip_projection_check: diff_result_1 = diff_result_2 = None if not grass.compare_key_value_text_files(filename_a=os.path.join( tmp_dir, 'PROJ_INFO'), filename_b=loc_proj, proj=True): diff_result_1 = diff_files(os.path.join(tmp_dir, 'PROJ_INFO'), loc_proj) if not grass.compare_key_value_text_files(filename_a=os.path.join( tmp_dir, 'PROJ_UNITS'), filename_b=loc_proj_units, units=True): diff_result_2 = diff_files(os.path.join(tmp_dir, 'PROJ_UNITS'), loc_proj_units) if diff_result_1 or diff_result_2: if flags['o']: grass.warning( _("Projection information does not match. Proceeding...")) else: if diff_result_1: grass.warning( _("Difference between PROJ_INFO file of packed map " "and of current location:\n{diff}").format( diff=''.join(diff_result_1))) if diff_result_2: grass.warning( _("Difference between PROJ_UNITS file of packed map " "and of current location:\n{diff}").format( diff=''.join(diff_result_2))) grass.fatal( _("Projection of dataset does not appear to match current location." " In case of no significant differences in the projection definitions," " use the -o flag to ignore them and use" " current location definition.")) # new db fromdb = os.path.join(tmp_dir, 'db.sqlite') # copy file shutil.copytree(data_name, new_dir) # exist fromdb if os.path.exists(fromdb): # the db connection in the output mapset dbconn = grassdb.db_connection(force=True) todb = dbconn['database'] # return all tables list_fromtable = grass.read_command('db.tables', driver='sqlite', database=fromdb).splitlines() # return the list of old connection for extract layer number and key dbln = open(os.path.join(new_dir, 'dbln'), 'r') dbnlist = dbln.readlines() dbln.close() # check if dbf or sqlite directory exists if dbconn['driver'] == 'dbf' and not os.path.exists( os.path.join(mset_dir, 'dbf')): os.mkdir(os.path.join(mset_dir, 'dbf')) elif dbconn['driver'] == 'sqlite' and not os.path.exists( os.path.join(mset_dir, 'sqlite')): os.mkdir(os.path.join(mset_dir, 'sqlite')) # for each old connection for t in dbnlist: # it split the line of each connection, to found layer number and key if len(t.split('|')) != 1: values = t.split('|') else: values = t.split(' ') from_table = values[1] layer = values[0].split('/')[0] # we need to take care about the table name in case of several layer if options["output"]: if len(dbnlist) > 1: to_table = "%s_%s" % (map_name, layer) else: to_table = map_name else: to_table = from_table grass.verbose( _("Coping table <%s> as table <%s>") % (from_table, to_table)) # copy the table in the default database try: grass.run_command('db.copy', to_driver=dbconn['driver'], to_database=todb, to_table=to_table, from_driver='sqlite', from_database=fromdb, from_table=from_table) except CalledModuleError: grass.fatal( _("Unable to copy table <%s> as table <%s>") % (from_table, to_table)) grass.verbose( _("Connect table <%s> to vector map <%s> at layer <%s>") % (to_table, map_name, layer)) # and connect the new tables with the right layer try: grass.run_command('v.db.connect', flags='o', quiet=True, driver=dbconn['driver'], database=todb, map=map_name, key=values[2], layer=layer, table=to_table) except CalledModuleError: grass.fatal( _("Unable to connect table <%s> to vector map <%s>") % (to_table, map_name)) grass.message(_("Vector map <%s> successfully unpacked") % map_name)
def main(): layers = options['map'].split(',') if len(layers) < 2: grass.error(_("At least 2 maps are required")) tmpfile = grass.tempfile() for map in layers: if not grass.find_file(map, element='cell')['file']: grass.fatal(_("Raster map <%s> not found") % map) grass.write_command('d.text', color='black', size=4, line=1, stdin="CORRELATION") os.environ['GRASS_PNG_READ'] = 'TRUE' colors = "red black blue green gray violet".split() line = 2 iloop = 0 jloop = 0 for iloop, i in enumerate(layers): for jloop, j in enumerate(layers): if i != j and iloop <= jloop: color = colors[0] colors = colors[1:] colors.append(color) grass.write_command('d.text', color=color, size=4, line=line, stdin="%s %s" % (i, j)) line += 1 ofile = file(tmpfile, 'w') grass.run_command('r.stats', flags='cnA', input=(i, j), stdout=ofile) ofile.close() ifile = file(tmpfile, 'r') first = True for l in ifile: f = l.rstrip('\r\n').split(' ') x = float(f[0]) y = float(f[1]) if first: minx = maxx = x miny = maxy = y first = False if minx > x: minx = x if maxx < x: maxx = x if miny > y: miny = y if maxy < y: maxy = y ifile.close() kx = 100.0 / (maxx - minx + 1) ky = 100.0 / (maxy - miny + 1) p = grass.feed_command('d.graph', color=color) ofile = p.stdin ifile = file(tmpfile, 'r') for l in ifile: f = l.rstrip('\r\n').split(' ') x = float(f[0]) y = float(f[1]) ofile.write("icon + 0.1 %f %f\n" % ((x - minx + 1) * kx, (y - miny + 1) * ky)) ifile.close() ofile.close() p.wait() try_remove(tmpfile)
def main(): infile = options['input'] # create temporary directory global tmp_dir tmp_dir = grass.tempdir() grass.debug('tmp_dir = %s' % tmp_dir) # check if the input file exists if not os.path.exists(infile): grass.fatal(_("File <%s> not found") % infile) # copy the files to tmp dir input_base = os.path.basename(infile) shutil.copyfile(infile, os.path.join(tmp_dir, input_base)) os.chdir(tmp_dir) tar = tarfile.TarFile.open(name=input_base, mode='r') try: data_name = tar.getnames()[0] except: grass.fatal(_("Pack file unreadable")) # set the output name if options['output']: map_name = options['output'] else: map_name = data_name # grass env gisenv = grass.gisenv() mset_dir = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], gisenv['MAPSET']) new_dir = os.path.join(mset_dir, 'vector', map_name) gfile = grass.find_file(name=map_name, element='vector', mapset='.') overwrite = os.getenv('GRASS_OVERWRITE') if gfile['file'] and overwrite != '1': grass.fatal(_("Vector map <%s> already exists") % map_name) elif overwrite == '1' and gfile['file']: grass.warning(_("Vector map <%s> already exists and will be overwritten") % map_name) grass.run_command('g.remove', flags='f', quiet=True, type='vector', name=map_name) shutil.rmtree(new_dir, True) # extract data tar.extractall() if os.path.exists(os.path.join(data_name, 'coor')): pass elif os.path.exists(os.path.join(data_name, 'cell')): grass.fatal(_("This GRASS GIS pack file contains raster data. Use " "r.unpack to unpack <%s>" % map_name)) else: grass.fatal(_("Pack file unreadable")) # check projection compatibility in a rather crappy way loc_proj = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO') loc_proj_units = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_UNITS') skip_projection_check = False if not os.path.exists(os.path.join(tmp_dir, 'PROJ_INFO')): if os.path.exists(loc_proj): grass.fatal( _("PROJ_INFO file is missing, unpack vector map in XY (unprojected) location.")) skip_projection_check = True # XY location if not skip_projection_check: diff_result_1 = diff_result_2 = None if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_INFO'), filename_b=loc_proj, proj=True): diff_result_1 = diff_files(os.path.join(tmp_dir, 'PROJ_INFO'), loc_proj) if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_UNITS'), filename_b=loc_proj_units, units=True): diff_result_2 = diff_files(os.path.join(tmp_dir, 'PROJ_UNITS'), loc_proj_units) if diff_result_1 or diff_result_2: if flags['o']: grass.warning(_("Projection information does not match. Proceeding...")) else: if diff_result_1: grass.warning(_("Difference between PROJ_INFO file of packed map " "and of current location:\n{diff}").format(diff=''.join(diff_result_1))) if diff_result_2: grass.warning(_("Difference between PROJ_UNITS file of packed map " "and of current location:\n{diff}").format(diff=''.join(diff_result_2))) grass.fatal(_("Projection of dataset does not appear to match current location." " In case of no significant differences in the projection definitions," " use the -o flag to ignore them and use" " current location definition.")) # new db fromdb = os.path.join(tmp_dir, 'db.sqlite') # copy file shutil.copytree(data_name, new_dir) # exist fromdb if os.path.exists(fromdb): # the db connection in the output mapset dbconn = grassdb.db_connection(force=True) todb = dbconn['database'] # return all tables list_fromtable = grass.read_command('db.tables', driver='sqlite', database=fromdb).splitlines() # return the list of old connection for extract layer number and key dbln = open(os.path.join(new_dir, 'dbln'), 'r') dbnlist = dbln.readlines() dbln.close() # check if dbf or sqlite directory exists if dbconn['driver'] == 'dbf' and not os.path.exists(os.path.join(mset_dir, 'dbf')): os.mkdir(os.path.join(mset_dir, 'dbf')) elif dbconn['driver'] == 'sqlite' and not os.path.exists(os.path.join(mset_dir, 'sqlite')): os.mkdir(os.path.join(mset_dir, 'sqlite')) # for each old connection for t in dbnlist: # it split the line of each connection, to found layer number and key if len(t.split('|')) != 1: values = t.split('|') else: values = t.split(' ') from_table = values[1] layer = values[0].split('/')[0] # we need to take care about the table name in case of several layer if options["output"]: if len(dbnlist) > 1: to_table = "%s_%s" % (map_name, layer) else: to_table = map_name else: to_table = from_table grass.verbose(_("Coping table <%s> as table <%s>") % (from_table, to_table)) # copy the table in the default database try: grass.run_command('db.copy', to_driver=dbconn['driver'], to_database=todb, to_table=to_table, from_driver='sqlite', from_database=fromdb, from_table=from_table) except CalledModuleError: grass.fatal(_("Unable to copy table <%s> as table <%s>") % (from_table, to_table)) grass.verbose(_("Connect table <%s> to vector map <%s> at layer <%s>") % (to_table, map_name, layer)) # and connect the new tables with the right layer try: grass.run_command('v.db.connect', flags='o', quiet=True, driver=dbconn['driver'], database=todb, map=map_name, key=values[2], layer=layer, table=to_table) except CalledModuleError: grass.fatal(_("Unable to connect table <%s> to vector map <%s>") % (to_table, map_name)) grass.message(_("Vector map <%s> successfully unpacked") % map_name)
def main(): infile = options['input'] compression_off = flags['c'] global basedir basedir = grass.tempdir() # check if vector map exists gfile = grass.find_file(infile, element = 'vector') if not gfile['name']: grass.fatal(_("Vector map <%s> not found") % infile) # check if input vector map is in the native format if vector.vector_info(gfile['fullname'])['format'] != 'native': grass.fatal(_("Unable to pack vector map <%s>. Only native format supported.") % \ gfile['fullname']) # split the name if there is the mapset name if infile.find('@'): infile = infile.split('@')[0] # output name if options['output']: outfile = options['output'] else: outfile = infile + '.pack' # check if exists the output file if os.path.exists(outfile): if os.getenv('GRASS_OVERWRITE'): grass.warning(_("Pack file <%s> already exists and will be overwritten") % outfile) try_remove(outfile) else: grass.fatal(_("option <%s>: <%s> exists.") % ("output", outfile)) # prepare for packing grass.verbose(_("Packing <%s>...") % (gfile['fullname'])) # write tar file, optional compression if compression_off: tar = tarfile.open(name = outfile, mode = 'w:') else: tar = tarfile.open(name = outfile, mode = 'w:gz') tar.add(gfile['file'], infile) # check if exist a db connection for the vector db_vect = vector.vector_db(gfile['fullname']) if not db_vect: grass.verbose(_('There is not database connected with vector map <%s>') % gfile['fullname']) else: # for each layer connection save a table in sqlite database sqlitedb = os.path.join(basedir, 'db.sqlite') for i, dbconn in db_vect.iteritems(): grass.run_command('db.copy', from_driver = dbconn['driver'], from_database = dbconn['database'], from_table = dbconn['table'], to_driver = 'sqlite', to_database = sqlitedb, to_table = dbconn['table']) tar.add(sqlitedb, 'db.sqlite') # add to the tar file the PROJ files to check when unpack file gisenv = grass.gisenv() for support in ['INFO', 'UNITS']: path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], 'PERMANENT', 'PROJ_' + support) if os.path.exists(path): tar.add(path, 'PROJ_' + support) tar.close() grass.message(_("Pack file <%s> created") % os.path.join(os.getcwd(), outfile))
def main(): infile = options['input'] compression_off = flags['c'] mapset = None if '@' in infile: infile, mapset = infile.split('@') if options['output']: outfile_path, outfile_base = os.path.split(os.path.abspath(options['output'])) else: outfile_path, outfile_base = os.path.split(os.path.abspath(infile + ".pack")) outfile = os.path.join(outfile_path, outfile_base) global tmp tmp = grass.tempdir() tmp_dir = os.path.join(tmp, infile) os.mkdir(tmp_dir) grass.debug('tmp_dir = %s' % tmp_dir) gfile = grass.find_file(name = infile, element = 'cell', mapset = mapset) if not gfile['name']: grass.fatal(_("Raster map <%s> not found") % infile) if os.path.exists(outfile): if os.getenv('GRASS_OVERWRITE'): grass.warning(_("Pack file <%s> already exists and will be overwritten") % outfile) try_remove(outfile) else: grass.fatal(_("option <output>: <%s> exists.") % outfile) grass.message(_("Packing <%s> to <%s>...") % (gfile['fullname'], outfile)) basedir = os.path.sep.join(os.path.normpath(gfile['file']).split(os.path.sep)[:-2]) olddir = os.getcwd() # copy elements for element in ['cats', 'cell', 'cellhd', 'colr', 'fcell', 'hist']: path = os.path.join(basedir, element, infile) if os.path.exists(path): grass.debug('copying %s' % path) shutil.copyfile(path, os.path.join(tmp_dir, element)) if os.path.exists(os.path.join(basedir, 'cell_misc', infile)): shutil.copytree(os.path.join(basedir, 'cell_misc', infile), os.path.join(tmp_dir, 'cell_misc')) if not os.listdir(tmp_dir): grass.fatal(_("No raster map components found")) # copy projection info # (would prefer to use g.proj*, but this way is 5.3 and 5.7 compat) gisenv = grass.gisenv() for support in ['INFO', 'UNITS', 'EPSG']: path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], 'PERMANENT', 'PROJ_' + support) if os.path.exists(path): shutil.copyfile(path, os.path.join(tmp_dir, 'PROJ_' + support)) # pack it all up os.chdir(tmp) if compression_off: tar = tarfile.TarFile.open(name = outfile_base, mode = 'w:') else: tar = tarfile.TarFile.open(name = outfile_base, mode = 'w:gz') tar.add(infile, recursive = True) tar.close() try: shutil.move(outfile_base, outfile) except shutil.Error as e: grass.fatal(e) os.chdir(olddir) grass.verbose(_("Raster map saved to '%s'" % outfile))
def warp_import(self, file, map): """Wrap raster file using gdalwarp and import wrapped file into GRASS""" warpfile = self.tmp + 'warped.geotiff' tmpmapname = map + '_tmp' t_srs = grass.read_command('g.proj', quiet = True, flags = 'jf').rstrip('\n') if not t_srs: grass.fatal(_('g.proj failed')) grass.debug("gdalwarp -s_srs '%s' -t_srs '%s' -r %s %s %s %s" % \ (self.options['srs'], t_srs, self.options['method'], self.options['warpoptions'], file, warpfile)) grass.verbose("Warping input file '%s'..." % os.path.basename(file)) if self.options['warpoptions']: ps = subprocess.Popen(['gdalwarp', '-s_srs', '%s' % self.options['srs'], '-t_srs', '%s' % t_srs, '-r', self.options['method'], self.options['warpoptions'], file, warpfile]) else: ps = subprocess.Popen(['gdalwarp', '-s_srs', '%s' % self.options['srs'], '-t_srs', '%s' % t_srs, '-r', self.options['method'], file, warpfile]) ps.wait() if ps.returncode != 0 or \ not os.path.exists(warpfile): grass.fatal(_('gdalwarp failed')) # import it into a temporary map grass.info(_('Importing raster map...')) if grass.run_command('r.in.gdal', quiet = True, flags = self.gdal_flags, input = warpfile, output = tmpmapname) != 0: grass.fatal(_('r.in.gdal failed')) os.remove(warpfile) # get list of channels pattern = tmpmapname + '*' grass.debug('Pattern: %s' % pattern) mapset = grass.gisenv()['MAPSET'] channel_list = grass.mlist_grouped(type = 'rast', pattern = pattern, mapset = mapset)[mapset] grass.debug('Channel list: %s' % ','.join(channel_list)) if len(channel_list) < 2: # test for single band data self.channel_suffixes = [] else: self.channel_suffixes = channel_list # ??? grass.debug('Channel suffixes: %s' % ','.join(self.channel_suffixes)) # add to the list of all suffixes self.suffixes = self.suffixes + self.channel_suffixes self.suffixes.sort() # get last suffix if len(self.channel_suffixes) > 0: last_suffix = self.channel_suffixes[-1] else: last_suffix = '' # find the alpha layer if self.flags['k']: alphalayer = tmpmapname + last_suffix else: alphalayer = tmpmapname + '.alpha' # test to see if the alpha map exists if not grass.find_file(element = 'cell', name = alphalayer)['name']: alphalayer = '' # calculate the new maps: for suffix in self.channel_suffixes: grass.debug("alpha=%s MAPsfx=%s%s tmpname=%s%s" % \ (alphalayer, map, suffix, tmpmapname, suffix)) if alphalayer: # Use alpha channel for nulls: problem: I've seen a map # where alpha was 1-255; 1 being transparent. what to do? # (Geosci Australia Gold layer, format=tiff) if grass.run_command('r.mapcalc', quiet = True, expression = "%s%s = if(%s, %s%s, null())" % \ (map, sfx, alphalayer, tmpmapname, sfx)) != 0: grass.fatal(_('r.mapcalc failed')) else: if grass.run_command('g.copy', quiet = True, rast = "%s%s,%s%s" % \ (tmpmapname, suffix, map, suffix)) != 0: grass.fatal(_('g.copy failed')) # copy the color tables if grass.run_command('r.colors', quiet = True, map = map + suffix, rast = tmpmapname + suffix) != 0: grass.fatal(_('g.copy failed')) # make patch lists suffix = suffix.replace('.', '_') # this is a hack to make the patch lists empty: if self.tiler == 0: self.patches = [] self.patches = self.patches.append(map + suffix) # if no suffix, processing is simple (e.g. elevation has only 1 # band) if len(channel_list) < 2: # run r.mapcalc to crop to region if grass.run_command('r.mapcalc', quiet = True, expression = "%s = %s" % \ (map, tmpmapname)) != 0: grass.fatal(_('r.mapcalc failed')) if grass.run_command('r.colors', quiet = True, map = map, rast = tmpmapname) != 0: grass.fatal(_('r.colors failed')) # remove the old channels if grass.run_command('g.remove', quiet = True, rast = ','.join(channel_list)) != 0: grass.fatal(_('g.remove failed'))
def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None, layerType = None): """!Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. @param dcmd GRASS command (given as list) @param fullyQualified change map name to be fully qualified @param param params directory @param layerType check also layer type ('raster', 'vector', '3d-raster', ...) @return tuple (name, found) """ mapname = '' found = True if len(dcmd) < 1: return mapname, False if 'd.grid' == dcmd[0]: mapname = 'grid' elif 'd.geodesic' in dcmd[0]: mapname = 'geodesic' elif 'd.rhumbline' in dcmd[0]: mapname = 'rhumb' elif 'labels=' in dcmd[0]: mapname = dcmd[idx].split('=')[1] + ' labels' else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split('=', 1) except ValueError: continue if p == param: params = [(idx, p, v)] break if p in ('map', 'input', 'red', 'blue', 'green', 'h_map', 's_map', 'i_map', 'reliefmap', 'labels'): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1: i = 1 while i < len(dcmd): if '=' not in dcmd[i] and not dcmd[i].startswith('-'): task = gtask.parse_interface(dcmd[0]) # this expects the first parameter to be the right one p = task.get_options()['params'][0].get('name', '') params.append((i, p, dcmd[i])) break i += 1 else: return mapname, False if len(params) < 1: return mapname, False # need to add mapset for all maps mapsets = {} for i, p, v in params: mapname = v mapset = '' if fullyQualified and '@' not in mapname: if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'): try: if layerType in ('raster', 'rgb', 'his'): findType = 'cell' else: findType = layerType mapset = grass.find_file(mapname, element = findType)['mapset'] except AttributeError, e: # not found return '', False if not mapset: found = False else: mapset = grass.gisenv()['MAPSET'] mapsets[i] = mapset # update dcmd for i, p, v in params: if p: dcmd[i] = p + '=' + v else: dcmd[i] = v if i in mapsets and mapsets[i]: dcmd[i] += '@' + mapsets[i] maps = list() for i, p, v in params: if not p: maps.append(v) else: maps.append(dcmd[i].split('=', 1)[1]) mapname = '\n'.join(maps)
def Update(self): if grass.find_file(name = 'MASK', element = 'cell', mapset = grass.gisenv()['MAPSET'])['name']: self.Show() else: self.Hide()
def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None, layerType=None): """Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. :param dcmd: GRASS command (given as list) :param fullyQualified: change map name to be fully qualified :param param: params directory :param str layerType: check also layer type ('raster', 'vector', 'raster_3d', ...) :return: tuple (name, found) """ mapname = '' found = True if len(dcmd) < 1: return mapname, False if 'd.grid' == dcmd[0]: mapname = 'grid' elif 'd.geodesic' in dcmd[0]: mapname = 'geodesic' elif 'd.rhumbline' in dcmd[0]: mapname = 'rhumb' elif 'd.graph' in dcmd[0]: mapname = 'graph' else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split('=', 1) except ValueError: continue if p == param: params = [(idx, p, v)] break # this does not use types, just some (incomplete subset of?) names if p in ('map', 'input', 'layer', 'red', 'blue', 'green', 'hue', 'saturation', 'intensity', 'shade', 'labels'): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1: i = 1 while i < len(dcmd): if '=' not in dcmd[i] and not dcmd[i].startswith('-'): task = gtask.parse_interface(dcmd[0]) # this expects the first parameter to be the right one p = task.get_options()['params'][0].get('name', '') params.append((i, p, dcmd[i])) break i += 1 else: return mapname, False if len(params) < 1: return mapname, False # need to add mapset for all maps mapsets = {} for i, p, v in params: if p == 'layer': continue mapname = v mapset = '' if fullyQualified and '@' not in mapname: if layerType in ('raster', 'vector', 'raster_3d', 'rgb', 'his'): try: if layerType in ('raster', 'rgb', 'his'): findType = 'cell' elif layerType == 'raster_3d': findType = 'grid3' else: findType = layerType mapset = grass.find_file( mapname, element=findType)['mapset'] except AttributeError: # not found return '', False if not mapset: found = False else: mapset = '' # grass.gisenv()['MAPSET'] mapsets[i] = mapset # update dcmd for i, p, v in params: if p == 'layer': continue dcmd[i] = p + '=' + v if i in mapsets and mapsets[i]: dcmd[i] += '@' + mapsets[i] maps = list() ogr = False for i, p, v in params: if v.lower().rfind('@ogr') > -1: ogr = True if p == 'layer' and not ogr: continue maps.append(dcmd[i].split('=', 1)[1]) mapname = '\n'.join(maps) return mapname, found
def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None, layerType = None): """!Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. @param dcmd GRASS command (given as list) @param fullyQualified change map name to be fully qualified @param param params directory @param layerType check also layer type ('raster', 'vector', '3d-raster', ...) @return tuple (name, found) """ mapname = '' found = True if len(dcmd) < 1: return mapname, False if 'd.grid' == dcmd[0]: mapname = 'grid' elif 'd.geodesic' in dcmd[0]: mapname = 'geodesic' elif 'd.rhumbline' in dcmd[0]: mapname = 'rhumb' else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split('=', 1) except ValueError: continue if p == param: params = [(idx, p, v)] break if p in ('map', 'input', 'layer', 'red', 'blue', 'green', 'h_map', 's_map', 'i_map', 'reliefmap', 'labels'): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1 and '=' not in dcmd[1]: task = gtask.parse_interface(dcmd[0]) p = task.get_options()['params'][0].get('name', '') params.append((1, p, dcmd[1])) else: return mapname, False mapname = params[0][2] mapset = '' if fullyQualified and '@' not in mapname: if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'): try: if layerType in ('raster', 'rgb', 'his'): findType = 'cell' else: findType = layerType mapset = grass.find_file(mapname, element = findType)['mapset'] except AttributeError, e: # not found return '', False if not mapset: found = False else: mapset = grass.gisenv()['MAPSET'] # update dcmd for i, p, v in params: if p == 'layer': continue dcmd[i] = p + '=' + v if mapset: dcmd[i] += '@' + mapset maps = list() ogr = False for i, p, v in params: if v.lower().rfind('@ogr') > -1: ogr = True if p == 'layer' and not ogr: continue maps.append(dcmd[i].split('=', 1)[1]) mapname = '\n'.join(maps)
def main(): infile = options['input'] compression_off = flags['c'] global basedir basedir = grass.tempdir() # check if vector map exists gfile = grass.find_file(infile, element='vector') if not gfile['name']: grass.fatal(_("Vector map <%s> not found") % infile) # check if input vector map is in the native format if vector.vector_info(gfile['fullname'])['format'] != 'native': grass.fatal( _("Unable to pack vector map <%s>. Only native format supported.") % gfile['fullname']) # split the name if there is the mapset name if infile.find('@'): infile = infile.split('@')[0] # output name if options['output']: outfile = options['output'] else: outfile = infile + '.pack' # check if exists the output file if os.path.exists(outfile): if os.getenv('GRASS_OVERWRITE'): grass.warning( _("Pack file <%s> already exists and will be overwritten") % outfile) try_remove(outfile) else: grass.fatal(_("option <%s>: <%s> exists.") % ("output", outfile)) # prepare for packing grass.verbose(_("Packing <%s>...") % (gfile['fullname'])) # write tar file, optional compression if compression_off: tar = tarfile.open(name=outfile, mode='w:') else: tar = tarfile.open(name=outfile, mode='w:gz') tar.add(gfile['file'], infile) # check if exist a db connection for the vector db_vect = vector.vector_db(gfile['fullname']) if not db_vect: grass.verbose( _('There is not database connected with vector map <%s>') % gfile['fullname']) else: # for each layer connection save a table in sqlite database sqlitedb = os.path.join(basedir, 'db.sqlite') for i, dbconn in db_vect.items(): grass.run_command('db.copy', from_driver=dbconn['driver'], from_database=dbconn['database'], from_table=dbconn['table'], to_driver='sqlite', to_database=sqlitedb, to_table=dbconn['table']) tar.add(sqlitedb, 'db.sqlite') # add to the tar file the PROJ files to check when unpack file gisenv = grass.gisenv() for support in ['INFO', 'UNITS', 'EPSG']: path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], 'PERMANENT', 'PROJ_' + support) if os.path.exists(path): tar.add(path, 'PROJ_' + support) tar.close() grass.message( _("Pack file <%s> created") % os.path.join(os.getcwd(), outfile))
def main(): infile = options['input'] global tmp_dir tmp_dir = grass.tempdir() grass.debug('tmp_dir = %s' % tmp_dir) if not os.path.exists(infile): grass.fatal(_("File <%s> not found" % infile)) gisenv = grass.gisenv() mset_dir = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], gisenv['MAPSET']) input_base = os.path.basename(infile) shutil.copyfile(infile, os.path.join(tmp_dir, input_base)) os.chdir(tmp_dir) tar = tarfile.TarFile.open(name = input_base, mode = 'r:gz') try: data_name = tar.getnames()[0] except: grass.fatal(_("Pack file unreadable")) if options['output']: map_name = options['output'] else: map_name = data_name gfile = grass.find_file(name = map_name, element = 'cell', mapset = '.') overwrite = os.getenv('GRASS_OVERWRITE') if gfile['file'] and overwrite != '1': grass.fatal(_("Raster map <%s> already exists") % map_name) # extract data tar.extractall() os.chdir(data_name) # check projection compatibility in a rather crappy way if not filecmp.cmp('PROJ_INFO', os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO')): if flags['o']: grass.warning(_("Projection information does not match. Proceeding...")) else: grass.fatal(_("Projection information does not match. Aborting.")) # install in $MAPSET for element in ['cats', 'cell', 'cellhd', 'cell_misc', 'colr', 'fcell', 'hist']: if not os.path.exists(element): continue path = os.path.join(mset_dir, element) if not os.path.exists(path): os.mkdir(path) if element == 'cell_misc': path = os.path.join(mset_dir, element, map_name) if os.path.exists(path): shutil.rmtree(path) shutil.copytree('cell_misc', path) else: shutil.copyfile(element, os.path.join(mset_dir, element, map_name)) grass.verbose(_("Raster map saved to <%s>") % map_name)
def SaveTmpLayer(self, layer_name): """Permanently saves temporary map of analysis result""" msg = _("Vector map with analysis result does not exist.") if not hasattr(self.results["vect_map"], "GetVectMapName"): GMessage(parent=self.guiparent, message=msg) return mapToAdd = self.results["vect_map"].GetVectMapName() mapToAddEx = grass.find_file(name=mapToAdd, element='vector', mapset=grass.gisenv()['MAPSET']) if not mapToAddEx["name"]: GMessage(parent=self.guiparent, message=msg) return addedMap = layer_name mapName, mapSet = ParseMapStr(addedMap) if mapSet != grass.gisenv()['MAPSET']: GMessage( parent=self.guiparent, message=_("Map can be saved only to currently set mapset")) return existsMap = grass.find_file(name=mapName, element='vector', mapset=grass.gisenv()['MAPSET']) if existsMap["name"]: dlg = wx.MessageDialog(parent=self.guiparent, message=_("Vector map %s already exists. " + "Do you want to overwrite it?") % (existsMap["fullname"]), caption=_("Overwrite vector map"), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE) ret = dlg.ShowModal() if ret == wx.ID_NO: dlg.Destroy() return dlg.Destroy() RunCommand("g.copy", overwrite=True, vector=[self.results["vect_map"].GetVectMapName(), mapName]) if len(self.giface.GetLayerList().GetLayersByName(mapName)) == 0: # TODO: get rid of insert cmd, cmd_colors = self.vnet_data.GetLayerStyle() cmd.insert(0, 'd.vect') cmd.append('map=%s' % mapName) self.giface.GetLayerList().AddLayer(ltype="vector", name=mapName, cmd=cmd, checked=True) if cmd_colors: layerStyleVnetColors = cmdlist_to_tuple(cmd_colors) RunCommand(layerStyleVnetColors[0], **layerStyleVnetColors[1]) else: self.giface.updateMap.emit(render=True, renderVector=True)
def SaveTmpLayer(self, layer_name): """Permanently saves temporary map of analysis result""" msg = _("Vector map with analysis result does not exist.") if not hasattr(self.results["vect_map"], "GetVectMapName"): GMessage(parent = self.guiparent, message = msg) return mapToAdd = self.results["vect_map"].GetVectMapName() mapToAddEx = grass.find_file(name = mapToAdd, element = 'vector', mapset = grass.gisenv()['MAPSET']) if not mapToAddEx["name"]: GMessage(parent = self.guiparent, message = msg) return addedMap = layer_name mapName, mapSet = ParseMapStr(addedMap) if mapSet != grass.gisenv()['MAPSET']: GMessage(parent = self.guiparent, message = _("Map can be saved only to currently set mapset")) return existsMap = grass.find_file(name = mapName, element = 'vector', mapset = grass.gisenv()['MAPSET']) if existsMap["name"]: dlg = wx.MessageDialog(parent = self.guiparent, message = _("Vector map %s already exists. " + "Do you want to overwrite it?") % (existsMap["fullname"]), caption = _("Overwrite vector map"), style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE) ret = dlg.ShowModal() if ret == wx.ID_NO: dlg.Destroy() return dlg.Destroy() RunCommand("g.copy", overwrite = True, vect = [self.results["vect_map"].GetVectMapName(), mapName]) if len(self.giface.GetLayerList().GetLayersByName(mapName)) == 0: # TODO: get rid of insert cmd, cmd_colors = self.vnet_data.GetLayerStyle() cmd.insert(0, 'd.vect') cmd.append('map=%s' % mapName) self.giface.GetLayerList().AddLayer(ltype="vector", name=mapName, cmd=cmd, checked=True) if cmd_colors: layerStyleVnetColors = utils.CmdToTuple(cmd_colors) RunCommand(layerStyleVnetColors[0], **layerStyleVnetColors[1]) else: self.giface.updateMap.emit(render=True, renderVector=True)
def main(): layers = options["map"].split(",") if len(layers) < 2: gcore.error(_("At least 2 maps are required")) tmpfile = gcore.tempfile() for map in layers: if not gcore.find_file(map, element="cell")["file"]: gcore.fatal(_("Raster map <%s> not found") % map) gcore.write_command("d.text", color="black", size=4, line=1, stdin="CORRELATION") os.environ["GRASS_RENDER_FILE_READ"] = "TRUE" colors = "red black blue green gray violet".split() line = 2 iloop = 0 jloop = 0 for iloop, i in enumerate(layers): for jloop, j in enumerate(layers): if i != j and iloop <= jloop: color = colors[0] colors = colors[1:] colors.append(color) gcore.write_command("d.text", color=color, size=4, line=line, stdin="%s %s" % (i, j)) line += 1 ofile = file(tmpfile, "w") gcore.run_command("r.stats", flags="cnA", input=(i, j), stdout=ofile) ofile.close() ifile = file(tmpfile, "r") first = True for l in ifile: f = l.rstrip("\r\n").split(" ") x = float(f[0]) y = float(f[1]) if first: minx = maxx = x miny = maxy = y first = False if minx > x: minx = x if maxx < x: maxx = x if miny > y: miny = y if maxy < y: maxy = y ifile.close() kx = 100.0 / (maxx - minx + 1) ky = 100.0 / (maxy - miny + 1) p = gcore.feed_command("d.graph", color=color) ofile = p.stdin ifile = file(tmpfile, "r") for l in ifile: f = l.rstrip("\r\n").split(" ") x = float(f[0]) y = float(f[1]) ofile.write("icon + 0.1 %f %f\n" % ((x - minx + 1) * kx, (y - miny + 1) * ky)) ifile.close() ofile.close() p.wait() try_remove(tmpfile)
def main(): layers = options['map'].split(',') if len(layers) < 2: grass.error(_("At least 2 maps are required")) tmpfile = grass.tempfile() for map in layers: if not grass.find_file(map, element = 'cell')['file']: grass.fatal(_("Raster map <%s> not found") % map) grass.write_command('d.text', color = 'black', size = 4, line = 1, stdin = "CORRELATION") os.environ['GRASS_PNG_READ'] = 'TRUE' colors = "red black blue green gray violet".split() line = 2 iloop = 0 jloop = 0 for iloop, i in enumerate(layers): for jloop, j in enumerate(layers): if i != j and iloop <= jloop: color = colors[0] colors = colors[1:] colors.append(color) grass.write_command('d.text', color = color, size = 4, line = line, stdin = "%s %s" % (i, j)) line += 1 ofile = file(tmpfile, 'w') grass.run_command('r.stats', flags = 'cnA', input = (i, j), stdout = ofile) ofile.close() ifile = file(tmpfile, 'r') first = True for l in ifile: f = l.rstrip('\r\n').split(' ') x = float(f[0]) y = float(f[1]) if first: minx = maxx = x miny = maxy = y first = False if minx > x: minx = x if maxx < x: maxx = x if miny > y: miny = y if maxy < y: maxy = y ifile.close() kx = 100.0/(maxx-minx+1) ky = 100.0/(maxy-miny+1) p = grass.feed_command('d.graph', color = color) ofile = p.stdin ifile = file(tmpfile, 'r') for l in ifile: f = l.rstrip('\r\n').split(' ') x = float(f[0]) y = float(f[1]) ofile.write("icon + 0.1 %f %f\n" % ((x-minx+1) * kx, (y-miny+1) * ky)) ifile.close() ofile.close() p.wait() grass.try_remove(tmpfile)
def main(): infile = options['input'] compression_off = flags['c'] mapset = None if '@' in infile: infile, mapset = infile.split('@') if options['output']: outfile_path, outfile_base = os.path.split( os.path.abspath(options['output'])) else: outfile_path, outfile_base = os.path.split( os.path.abspath(infile + ".pack")) outfile = os.path.join(outfile_path, outfile_base) global tmp tmp = grass.tempdir() tmp_dir = os.path.join(tmp, infile) os.mkdir(tmp_dir) grass.debug('tmp_dir = %s' % tmp_dir) gfile = grass.find_file(name=infile, element='cell', mapset=mapset) if not gfile['name']: grass.fatal(_("Raster map <%s> not found") % infile) if os.path.exists(outfile): if os.getenv('GRASS_OVERWRITE'): grass.warning( _("Pack file <%s> already exists and will be overwritten") % outfile) try_remove(outfile) else: grass.fatal(_("option <output>: <%s> exists.") % outfile) grass.message(_("Packing <%s> to <%s>...") % (gfile['fullname'], outfile)) basedir = os.path.sep.join( os.path.normpath(gfile['file']).split(os.path.sep)[:-2]) olddir = os.getcwd() # copy elements info = grass.parse_command('r.info', flags='e', map=infile) vrt_files = {} if info['maptype'] == 'virtual': map_file = grass.find_file( name=infile, element='cell_misc', ) if map_file['file']: vrt = os.path.join(map_file['file'], 'vrt') if os.path.exists(vrt): with open(vrt, 'r') as f: for r in f.readlines(): map, mapset = r.split('@') map_basedir = os.path.sep.join( os.path.normpath(map_file['file'], ).split( os.path.sep)[:-2], ) vrt_files[map] = map_basedir for element in [ 'cats', 'cell', 'cellhd', 'cell_misc', 'colr', 'fcell', 'hist', ]: path = os.path.join(basedir, element, infile) if os.path.exists(path): grass.debug('copying %s' % path) if os.path.isfile(path): shutil.copyfile( path, os.path.join(tmp_dir, element), ) else: shutil.copytree( path, os.path.join(tmp_dir, element), ) # Copy vrt files if vrt_files: for f in vrt_files.keys(): f_tmp_dir = os.path.join(tmp, f) if not os.path.exists(f_tmp_dir): os.mkdir(f_tmp_dir) path = os.path.join(vrt_files[f], element, f) if os.path.exists(path): grass.debug("copying vrt file {}".format(path)) if os.path.isfile(path): shutil.copyfile( path, os.path.join(f_tmp_dir, element), ) else: shutil.copytree( path, os.path.join(f_tmp_dir, element), ) if not os.listdir(tmp_dir): grass.fatal(_("No raster map components found")) # copy projection info # (would prefer to use g.proj*, but this way is 5.3 and 5.7 compat) gisenv = grass.gisenv() for support in ['INFO', 'UNITS', 'EPSG']: path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], 'PERMANENT', 'PROJ_' + support) if os.path.exists(path): shutil.copyfile(path, os.path.join(tmp_dir, 'PROJ_' + support)) # pack it all up os.chdir(tmp) if compression_off: tar = tarfile.TarFile.open(name=outfile_base, mode='w:') else: tar = tarfile.TarFile.open(name=outfile_base, mode='w:gz') tar.add(infile, recursive=True) if vrt_files: for f in vrt_files.keys(): tar.add(f, recursive=True) tar.close() try: shutil.move(outfile_base, outfile) except shutil.Error as e: grass.fatal(e) os.chdir(olddir) grass.verbose(_("Raster map saved to '%s'" % outfile))
def main(): infile = options['input'] global tmp_dir tmp_dir = grass.tempdir() grass.debug('tmp_dir = {tmpdir}'.format(tmpdir=tmp_dir)) if not os.path.exists(infile): grass.fatal(_('File {name} not found.'.format(name=infile))) gisenv = grass.gisenv() mset_dir = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], gisenv['MAPSET']) input_base = os.path.basename(infile) shutil.copyfile(infile, os.path.join(tmp_dir, input_base)) os.chdir(tmp_dir) tar = tarfile.TarFile.open(name=input_base, mode='r') try: data_name = tar.getnames()[0] except: grass.fatal(_("Pack file unreadable")) if options['output']: map_name = options['output'] else: map_name = data_name.split('@')[0] gfile = grass.find_file(name=map_name, element='cell', mapset='.') if gfile['file']: if os.environ.get('GRASS_OVERWRITE', '0') != '1': grass.fatal(_('Raster map <{name}> already exists'.format(name=map_name))) else: grass.warning(_('Raster map <{name}> already exists and will be overwritten'.format(name=map_name))) # extract data tar.extractall() os.chdir(data_name) if os.path.exists('cell'): pass elif os.path.exists('coor'): grass.fatal(_('This GRASS GIS pack file contains vector data. Use ' 'v.unpack to unpack <{name}>'.format(name=map_name))) else: grass.fatal(_("Pack file unreadable")) # check projection compatibility in a rather crappy way if flags['o']: grass.warning(_("Overriding projection check (using current location's projection).")) else: diff_result_1 = diff_result_2 = None proj_info_file_1 = 'PROJ_INFO' proj_info_file_2 = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO') skip_projection_check = False if not os.path.exists(proj_info_file_1): if os.path.exists(proj_info_file_2): grass.fatal(_("PROJ_INFO file is missing, unpack raster map in XY (unprojected) location.")) skip_projection_check = True # XY location if not skip_projection_check: if not grass.compare_key_value_text_files(filename_a=proj_info_file_1, filename_b=proj_info_file_2, proj=True): diff_result_1 = diff_files(proj_info_file_1, proj_info_file_2) proj_units_file_1 = 'PROJ_UNITS' proj_units_file_2 = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_UNITS') if not grass.compare_key_value_text_files(filename_a=proj_units_file_1, filename_b=proj_units_file_2, units=True): diff_result_2 = diff_files(proj_units_file_1, proj_units_file_2) if diff_result_1 or diff_result_2: if diff_result_1: grass.warning(_("Difference between PROJ_INFO file of packed map " "and of current location:\n{diff}").format(diff=''.join(diff_result_1))) if diff_result_2: grass.warning(_("Difference between PROJ_UNITS file of packed map " "and of current location:\n{diff}").format(diff=''.join(diff_result_2))) grass.fatal(_("Projection of dataset does not appear to match current location." " In case of no significant differences in the projection definitions," " use the -o flag to ignore them and use" " current location definition.")) # install in $MAPSET for element in ['cats', 'cell', 'cellhd', 'cell_misc', 'colr', 'fcell', 'hist']: if not os.path.exists(element): continue path = os.path.join(mset_dir, element) if not os.path.exists(path): os.mkdir(path) if element == 'cell_misc': path = os.path.join(mset_dir, element, map_name) if os.path.exists(path): shutil.rmtree(path) shutil.copytree('cell_misc', path) else: shutil.copyfile(element, os.path.join(mset_dir, element, map_name)) grass.message(_('Raster map <{name}> unpacked'.format(name=map_name)))