def GetLastModified(self): """Get modification time :return: MAP DATE time string from vector map head file """ mapValSpl = self.fullName.split("@") mapSet = mapValSpl[1] mapName = mapValSpl[0] headPath = os.path.join(grass.gisenv()['GISDBASE'], grass.gisenv()['LOCATION_NAME'], mapSet, "vector", mapName, "head") try: head = open(headPath, 'r') for line in head.readlines(): i = line.find('MAP DATE:', ) if i == 0: head.close() return line.split(':', 1)[1].strip() head.close() return "" except IOError: return ""
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 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 GetWindow(self): """Read WIND file and set up self.wind dictionary""" # FIXME: duplicated region WIND == g.region (at least some values) env = grass.gisenv() filename = os.path.join (env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], "WIND") try: windfile = open (filename, "r") except IOError as e: sys.exit(_("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") % \ { 'file' : filename, 'ret' : e}) for line in windfile.readlines(): line = line.strip() try: key, value = line.split(":", 1) except ValueError as e: sys.stderr.write(_("\nERROR: Unable to read WIND file: %s\n") % e) return None self.wind[key.strip()] = value.strip() windfile.close() return self.wind
def _readHistory(self): """Get list of commands from history file""" hist = list() env = grass.gisenv() try: fileHistory = codecs.open( os.path.join( env["GISDBASE"], env["LOCATION_NAME"], env["MAPSET"], ".bash_history", ), encoding="utf-8", mode="r", errors="replace", ) except IOError: return hist try: for line in fileHistory.readlines(): hist.append(line.replace("\n", "")) finally: fileHistory.close() return hist
def AddTmpMapAnalysisMsg(mapName, tmp_maps): #TODO """Wraped AddTmpVectMap""" msg = _("Temporary map %s already exists.\n" + "Do you want to continue in analysis and overwrite it?") \ % (mapName +'@' + grass.gisenv()['MAPSET']) tmpMap = tmp_maps.AddTmpVectMap(mapName, msg) return tmpMap
def GetWindow(self): """Read WIND file and set up self.wind dictionary""" # FIXME: duplicated region WIND == g.region (at least some values) env = grass.gisenv() filename = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], "WIND") try: windfile = open(filename, "r") except IOError as e: sys.exit(_("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") % \ { 'file' : filename, 'ret' : e}) for line in windfile.readlines(): line = line.strip() try: key, value = line.split(":", 1) except ValueError as e: sys.stderr.write( _("\nERROR: Unable to read WIND file: %s\n") % e) return None self.wind[key.strip()] = value.strip() windfile.close() return self.wind
def _renderCmdFile(self, force, windres): if not force: return ([self.mapfileCmd], [self.maskfileCmd], ['1.0']) region = os.environ["GRASS_REGION"] = self.SetRegion(windres) self._writeEnvFile({'GRASS_REGION' : region}) currMon = grass.gisenv()['MONITOR'] if currMon != self.monitor: gcmd.RunCommand('g.gisenv', set = 'MONITOR=%s' % self.monitor) grass.try_remove(self.mapfileCmd) # GRASS_PNG_READ is TRUE nlayers = self._parseCmdFile() if currMon != self.monitor: gcmd.RunCommand('g.gisenv', set = 'MONITOR=%s' % currMon) if nlayers > 0: return ([self.mapfileCmd], [self.maskfileCmd], ['1.0']) else: return ([], [], [])
def main(): env = grass.gisenv() mon = env.get('MONITOR', None) if not mon: grass.fatal(_("No monitor selected. Run `d.mon` to select monitor.")) monCmd = env.get('MONITOR_%s_CMDFILE' % mon.upper()) if not monCmd: grass.fatal(_("No cmd file found for monitor <%s>") % mon) try: fd = open(monCmd, 'r') cmdList = fd.readlines() grass.run_command('d.erase') for cmd in cmdList: grass.call(split(cmd)) except IOError as e: grass.fatal(_("Unable to open file '%s' for reading. Details: %s") % \ (monCmd, e)) fd.close() # restore cmd file try: fd = open(monCmd, "w") fd.writelines(cmdList) except IOError as e: grass.fatal(_("Unable to open file '%s' for writing. Details: %s") % \ (monCmd, e)) return 0
def _createNewMap(self, mapName, backgroundMap, mapType): name = mapName.split('@')[0] background = backgroundMap.split('@')[0] types = {'CELL': 'int', 'FCELL': 'float', 'DCELL': 'double'} if background: back = background else: back = 'null()' try: grast.mapcalc(exp="{name} = {mtype}({back})".format(name=name, mtype=types[mapType], back=back), overwrite=True, quiet=True) if background: self._backgroundRaster = backgroundMap if mapType == 'CELL': values = gcore.read_command('r.describe', flags='1n', map=backgroundMap, quiet=True).strip() if values: self.uploadMapCategories.emit(values=values.split('\n')) except CalledModuleError: raise ScriptError self._backupRaster(name) name = name + '@' + gcore.gisenv()['MAPSET'] self._editedRaster = name self.newRasterCreated.emit(name=name)
def main(): mon = grass.gisenv().get('MONITOR', None) if not mon: grass.fatal(_("No graphics device selected. Use d.mon to select graphics device.")) monCmd = grass.parse_command('d.mon', flags='g').get('cmd', None) if not monCmd or not os.path.isfile(monCmd): grass.fatal(_("Unable to open file '%s'") % monCmd) try: fd = open(monCmd, 'r') cmdList = fd.readlines() grass.run_command('d.erase') for cmd in cmdList: grass.call(split(cmd)) except IOError as e: grass.fatal(_("Unable to open file '%s' for reading. Details: %s") % (monCmd, e)) fd.close() # restore cmd file try: fd = open(monCmd, "w") fd.writelines(cmdList) except IOError as e: grass.fatal(_("Unable to open file '%s' for writing. Details: %s") % (monCmd, e)) return 0
def main(): env = grass.gisenv() mapset = env["MAPSET"] converted = 0 ret = 0 for vect in grass.list_grouped("oldvect")[mapset]: inmap = "%s@%s" % (vect, mapset) outmap = vect.replace(".", "_") try: grass.run_command("v.convert", input=inmap, output=outmap) except CalledModuleError: grass.warning( _("Error converting map <%s> to <%s>") % (inmap, outmap)) ret = 1 else: converted += 1 if converted < 1: grass.warning( _("No vector maps converted as no old vector maps present in current mapset." )) else: grass.message( _("Total %u vector maps in current mapset converted.") % converted) grass.message( _("Please verify new vector map(s) before deleting old vector map(s)." )) sys.exit(ret)
def OnSelectMap(self, event): """!Select vector map layer for editing If there is a vector map layer already edited, this action is firstly terminated. The map layer is closed. After this the selected map layer activated for editing. """ if event.GetSelection() == 0: # create new vector map layer if self.mapLayer: openVectorMap = self.mapLayer.GetName( fullyQualified=False)['name'] else: openVectorMap = None dlg = CreateNewVector(self.parent, exceptMap=openVectorMap, log=self.log, cmd=(('v.edit', { 'tool': 'create' }, 'map')), disableAdd=True) if dlg and dlg.GetName(): # add layer to map layer tree if self.layerTree: mapName = dlg.GetName() + '@' + grass.gisenv()['MAPSET'] self.layerTree.AddLayer( ltype='vector', lname=mapName, lcmd=['d.vect', 'map=%s' % mapName]) vectLayers = self.UpdateListOfLayers(updateTool=True) selection = vectLayers.index(mapName) # create table ? if dlg.IsChecked('table'): lmgr = self.parent.GetLayerManager() if lmgr: lmgr.OnShowAttributeTable(None, selection='table') dlg.Destroy() else: self.combo.SetValue(_('Select vector map')) if dlg: dlg.Destroy() return else: selection = event.GetSelection( ) - 1 # first option is 'New vector map' # skip currently selected map if self.layers[selection] == self.mapLayer: return if self.mapLayer: # deactive map layer for editing self.StopEditing() # select the given map layer for editing self.StartEditing(self.layers[selection]) event.Skip()
def check_monitor_file(monitor, ftype='env'): var = 'MONITOR_%s_%sFILE' % (monitor.upper(), ftype.upper()) mfile = gisenv().get(var, None) if mfile is None or not os.path.isfile(mfile): fatal(_("Unable to get monitor info (no %s found)") % var) return mfile
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 nowarp_import(self, file, map): """Import raster file into GRASS""" if grass.run_command('r.in.gdal', quiet = True, flags = 'o' + self.gdal_flags, input = file, output = map) != 0: grass.fatal(_('r.in.gdal failed')) # get a list of channels: pattern = map + '*' grass.debug("pattern: %s" % ','.join(pattern)) mapset = grass.gisenv()['MAPSET'] channel_list = grass.mlist_grouped(type = 'rast', pattern = pattern, 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 # ??? # add to the list of all suffixes: self.suffixes = self.suffixes + channel.suffixes self.suffixes.sort() for suffix in self.channel_suffixes: # 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)
def Update(self): if grass.find_file(name='MASK', element='cell', mapset=grass.gisenv()['MAPSET'])['name']: self.Show() else: self.Hide()
def main(): env = grass.gisenv() mapset = env['MAPSET'] ret = 0 vectors = grass.list_grouped('vect')[mapset] num_vectors = len(vectors) if grass.verbosity() < 2: quiet = True else: quiet = False i = 1 for vect in vectors: map = "%s@%s" % (vect, mapset) grass.message( _("%s\nBuilding topology for vector map <%s> (%d of %d)...\n%s") % ('-' * 80, map, i, num_vectors, '-' * 80)) grass.verbose(_("v.build map=%s") % map) try: grass.run_command("v.build", map=map, quiet=quiet) except CalledModuleError: grass.error( _("Building topology for vector map <%s> failed") % map) ret = 1 i += 1 return ret
def __init__(self, map, type): self.map = map self.type = type # function to check if map exist self.md_grass = {} self.md_abstract = '' self.md_vinfo_h = '' # v.info flag=h" - parse self.gisenv_grass = grass.gisenv() # dict with gisenv information # suffix of output xml file (variables) self.schema_type = '_basic.xml' self.profileName='GRASS BASIC' context=mdutil.StaticContext() self.dirpath = os.path.join(context.lib_path,'profiles') # metadata object from OWSLIB ( for define md values) self.md = mdutil.MD_MetadataMOD(md=None) self.profilePath = None # path to file with xml templates if self.type == "raster": self.isMapExist() self.parseRast() elif self.type == "vector": self.isMapExist() self.parseVect() elif self.type == "r3??": # TODO self.parseRast3D() elif self.type=='strds' or self.type=='stvds': self.parseTemporal()
def remove_vector(name): """Helper function to workaround problem with deleting vectors""" gisenv = gcore.gisenv() path_to_vector = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], gisenv['MAPSET'], 'vector', name) if os.path.exists(path_to_vector): shutil.rmtree(path_to_vector)
def writeEPSGtoPEMANENT(epsg): env = grass.gisenv() gisdbase = env['GISDBASE'] location = env['LOCATION_NAME'] path = os.path.join(gisdbase, location, "PERMANENT","PROJ_EPSG") if os.path.isfile(path): #if already file exist if os.getenv('GRASS_OVERWRITE', False): try: io = open(path,'w') io.write("epsg: %s"%epsg ) io.close() grass.message("EPSG code have been written to <%s>" % path) except IOError as e: grass.error("I/O error({0}): {1}".format(e.errno, e.strerror)) else: grass.message("EPSG file already exist <%s>" % path) else: try: io = open(path,'w') io.write("epsg: %s"%epsg) io.close() grass.message("EPSG code have been written to <%s>" % path) except IOError as e: grass.error("I/O error({0}): {1}".format(e.errno, e.strerror))
def main(): env = grass.gisenv() mapset = env['MAPSET'] ret = 0 vectors = grass.list_grouped('vect')[mapset] num_vectors = len(vectors) if grass.verbosity() < 2: quiet = True else: quiet = False i = 1 for vect in vectors: map = "%s@%s" % (vect, mapset) grass.message(_("%s\nBuilding topology for vector map <%s> (%d of %d)...\n%s") % \ ('-' * 80, map, i, num_vectors, '-' * 80)) grass.verbose(_("v.build map=%s") % map) if grass.run_command("v.build", map = map, quiet = quiet) != 0: grass.error(_("Building topology for vector map <%s> failed") % map) ret = 1 i += 1 return ret
def remove_temp_regions(regions): """!Removes temporary regions.""" gisenv = gcore.gisenv() path_to_regions = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], gisenv['MAPSET'], 'windows') for region in regions: os.remove(os.path.join(path_to_regions, region))
def endmembers_from_vector(vname,groupname): grouplist=gscript.read_command("i.group", group=groupname, flags="g" ).split() for rast in grouplist: band = rast.split("@")[0].split(".")[1] colname="b_"+str(band) gscript.run_command('v.db.addcolumn', map=vname, columns=colname + " DOUBLE") gscript.run_command('v.what.rast', map=vname, raster=rast, column=colname) dbp = os.path.join(gisenv()['GISDBASE'], gisenv()['LOCATION_NAME'],gisenv()['MAPSET'], 'sqlite', 'sqlite.db') con = sqlite3.connect(dbp) vatt = pandas.read_sql("SELECT * FROM "+vname, con) uqclasses = set(vatt["class"]) numclass=len(uqclasses) endarray = numpy.zeros(shape=(len(grouplist),numclass)) for ref_class in uqclasses: endarray[:,ref_class-1]=vatt.loc[vatt[vclasscol] == ref_class].mean()[2:] return(endarray)
def parseTemporal(self): env = grass.gisenv() mapset = env["MAPSET"] if self.map.find("@") < 0: self.map = "{}@{}".format(self.map, mapset) tinfo = Module("t.info", self.map, flags="g", type=self.type, stdout_=PIPE) self.md_grass = parse_key_val(tinfo.outputs.stdout) tinfoHist = Module( "t.info", input=self.map, quiet=True, flags="h", type=self.type, stdout_=PIPE, ) md_h_grass = tinfoHist.outputs.stdout buf = io.StringIO(md_h_grass) line = buf.readline().splitlines() while line: if str(line[0]).strip() != "": self.md_vinfo_h += line[0] + "\n" line = buf.readline().splitlines() buf.close()
def __init__(self, parent, id=wx.ID_ANY, title=_("Create new vector map"), disableAdd=False, showType=False, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs): """!Dialog for creating new vector map @param parent parent window @param id window id @param title window title @param disableAdd disable 'add layer' checkbox @param showType True to show feature type selector (used for creating new empty OGR layers) @param style window style @param kwargs other argumentes for ElementDialog @return dialog instance """ ElementDialog.__init__(self, parent, title, label=_("Name for new raster map:")) self.element = Select( parent=self.panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE, type="raster", mapsets=[ grass.gisenv()["MAPSET"], ], ) # determine output format if showType: self.ftype = GdalSelect(parent=self, panel=self.panel) else: self.ftype = None self.addbox = wx.CheckBox( parent=self.panel, label=_("Add created map into layer tree"), style=wx.NO_BORDER, ) if disableAdd: self.addbox.SetValue(True) self.addbox.Enable(False) else: self.addbox.SetValue( UserSettings.Get(group="cmd", key="addNewLayer", subkey="enabled")) self.PostInit() self._layout() self.SetMinSize(self.GetSize())
def AddLayers(self, returncode, cmd=None, userData=None): """Add imported/linked layers into layer tree""" if not self.add.IsChecked() or returncode != 0: return # TODO: if importing map creates more map the following does not work # * do nothing if map does not exist or # * try to determine names using regexp or # * persuade import tools to report map names self.commandId += 1 layer, output = self.list.GetLayers()[self.commandId][:2] if "@" not in output: name = output + "@" + grass.gisenv()["MAPSET"] else: name = output # add imported layers into layer tree # an alternative would be emit signal (mapCreated) and (optionally) # connect to this signal llist = self._giface.GetLayerList() if self.importType == "gdal": if userData: nBands = int(userData.get("nbands", 1)) else: nBands = 1 if UserSettings.Get(group="rasterLayer", key="opaque", subkey="enabled"): nFlag = True else: nFlag = False for i in range(1, nBands + 1): nameOrig = name if nBands > 1: mapName, mapsetName = name.split("@") mapName += ".%d" % i name = mapName + "@" + mapsetName cmd = ["d.rast", "map=%s" % name] if nFlag: cmd.append("-n") llist.AddLayer(ltype="raster", name=name, checked=True, cmd=cmd) name = nameOrig else: llist.AddLayer( ltype="vector", name=name, checked=True, cmd=["d.vect", "map=%s" % name] + GetDisplayVectSettings(), ) self._giface.GetMapWindow().ZoomToMap()
def setmaps(cost, output): """ Set the user maps in place """ if cost: if -1 == cost.find("@"): cost = cost + "@" + grass.gisenv()["MAPSET"] # set cost/penalty layer world.playground.setgrasslayer("COST", cost, True) else: raise error.DataError("r.agent.rand:", "The cost map is mandatory.") if output: if -1 == output.find("@"): output = output + "@" + grass.gisenv()["MAPSET"] world.playground.setgrasslayer("RESULT", output, True) else: raise error.DataError("r.agent.rand:", "The output map is mandatory.")
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 OnWizFinished(self): database = self.startpage.grassdatabase location = self.startpage.location global coordsys msg = '' # error message (empty on success) # location already exists? if os.path.isdir(os.path.join(database,location)): dlg = wx.MessageDialog(parent=self.wizard, message="%s <%s>: %s" % \ (_("Unable to create new location"), os.path.join(database, location), _("Location already exists in GRASS Database.")), caption=_("Error"), style=wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return False # current GISDbase or a new one? current_gdb = grass.gisenv()['GISDBASE'] if current_gdb != database: # change to new GISDbase or create new one if os.path.isdir(database) != True: # create new directory os.mkdir(database) # change to new GISDbase directory gcmd.RunCommand('g.gisenv', parent = self.wizard, set='GISDBASE=%s' % database) wx.MessageBox(parent=self.wizard, message=_("Location <%(loc)s> will be created " "in GIS data directory <%(dir)s>." "You will need to change the default GIS " "data directory in the GRASS startup screen.") % \ { 'loc' : location, 'dir' : database}, caption=_("New GIS data directory"), style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE) # location created in alternate GISDbase self.altdb = True if coordsys == "xy": msg = self.XYCreate() elif coordsys == "proj": proj4string = self.CreateProj4String() msg = self.Proj4Create(proj4string) elif coordsys == 'custom': msg = self.CustomCreate() elif coordsys == "epsg": msg = self.EPSGCreate() elif coordsys == "file": msg = self.FileCreate() elif coordsys == "wkt": msg = self.WKTCreate() return msg
def AddLayers(self, returncode, cmd=None, userData=None): """Add imported/linked layers into layer tree""" if not self.add.IsChecked() or returncode != 0: return # TODO: if importing map creates more map the following does not work # * do nothing if map does not exist or # * try to determine names using regexp or # * persuade import tools to report map names self.commandId += 1 layer, output = self.list.GetLayers()[self.commandId][:2] if '@' not in output: name = output + '@' + grass.gisenv()['MAPSET'] else: name = output # add imported layers into layer tree # an alternative would be emit signal (mapCreated) and (optionally) # connect to this signal llist = self._giface.GetLayerList() if self.importType == 'gdal': if userData: nBands = int(userData.get('nbands', 1)) else: nBands = 1 if UserSettings.Get(group='rasterLayer', key='opaque', subkey='enabled'): nFlag = True else: nFlag = False for i in range(1, nBands + 1): nameOrig = name if nBands > 1: mapName, mapsetName = name.split('@') mapName += '.%d' % i name = mapName + '@' + mapsetName cmd = ['d.rast', 'map=%s' % name] if nFlag: cmd.append('-n') llist.AddLayer(ltype='raster', name=name, checked=True, cmd=cmd) name = nameOrig else: llist.AddLayer(ltype='vector', name=name, checked=True, cmd=['d.vect', 'map=%s' % name] + GetDisplayVectSettings()) self._giface.GetMapWindow().ZoomToMap()
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 get_path(path): if "$" not in path: return path else: grassenv = core.gisenv() path = path.replace('$GISDBASE', grassenv['GISDBASE']) path = path.replace('$LOCATION_NAME', grassenv['LOCATION_NAME']) path = path.replace('$MAPSET', grassenv['MAPSET']) return path
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 AddLayers(self, returncode, cmd=None, userData=None): """Add imported/linked layers into layer tree""" if not self.add.IsChecked() or returncode != 0: return # TODO: if importing map creates more map the folowing does not work # * do nothing if map does not exist or # * try to determine names using regexp or # * persuade import tools to report map names self.commandId += 1 layer, output = self.list.GetLayers()[self.commandId][:2] if '@' not in output: name = output + '@' + grass.gisenv()['MAPSET'] else: name = output # add imported layers into layer tree # an alternative would be emit signal (mapCreated) and (optionally) # connect to this signal llist = self._giface.GetLayerList() if self.importType == 'gdal': if userData: nBands = int(userData.get('nbands', 1)) else: nBands = 1 if UserSettings.Get(group='rasterLayer', key='opaque', subkey='enabled'): nFlag = True else: nFlag = False for i in range(1, nBands + 1): nameOrig = name if nBands > 1: mapName, mapsetName = name.split('@') mapName += '.%d' % i name = mapName + '@' + mapsetName cmd = ['d.rast', 'map=%s' % name] if nFlag: cmd.append('-n') llist.AddLayer(ltype='raster', name=name, checked=True, cmd=cmd) name = nameOrig else: llist.AddLayer(ltype='vector', name=name, checked=True, cmd=['d.vect', 'map=%s' % name] + GetDisplayVectSettings()) self._giface.GetMapWindow().ZoomToMap()
def __init__(self, map, type): try: global CI_Date, CI_OnlineResource, CI_ResponsibleParty, \ DQ_DataQuality, Environment, etree, EX_Extent, \ EX_GeographicBoundingBox, FileSystemLoader, MD_Distribution, \ MD_ReferenceSystem, RunCommand from owslib.iso import ( CI_Date, CI_OnlineResource, CI_ResponsibleParty, DQ_DataQuality, EX_Extent, EX_GeographicBoundingBox, MD_Distribution, MD_ReferenceSystem, ) from jinja2 import Environment, FileSystemLoader from lxml import etree set_gui_path() from core.gcmd import RunCommand except ModuleNotFoundError as e: msg = e.msg sys.exit( globalvar.MODULE_NOT_FOUND.format(lib=msg.split("'")[-2], url=globalvar.MODULE_URL)) self.map = map self.type = type # function to check if map exist self.md_grass = {} self.md_abstract = '' self.md_vinfo_h = '' # v.info flag=h" - parse self.gisenv_grass = grass.gisenv() # dict with gisenv information # suffix of output xml file (variables) self.schema_type = '_basic.xml' self.profileName = 'GRASS BASIC' context = mdutil.StaticContext() self.dirpath = os.path.join(context.lib_path, 'profiles') # metadata object from OWSLIB ( for define md values) self.md = mdutil.MD_MetadataMOD(md=None) self.profilePath = None # path to file with xml templates if self.type == "raster": self.isMapExist() self.parseRast() elif self.type == "vector": self.isMapExist() self.parseVect() elif self.type == "r3??": # TODO self.parseRast3D() elif self.type == 'strds' or self.type == 'stvds': self.parseTemporal()
def OnSelectMap (self, event): """!Select vector map layer for editing If there is a vector map layer already edited, this action is firstly terminated. The map layer is closed. After this the selected map layer activated for editing. """ if event.GetSelection() == 0: # create new vector map layer if self.mapLayer: openVectorMap = self.mapLayer.GetName(fullyQualified = False)['name'] else: openVectorMap = None dlg = CreateNewVector(self.parent, exceptMap = openVectorMap, log = self.log, cmd = (('v.edit', { 'tool' : 'create' }, 'map')), disableAdd = True) if dlg and dlg.GetName(): # add layer to map layer tree if self.layerTree: mapName = dlg.GetName() + '@' + grass.gisenv()['MAPSET'] self.layerTree.AddLayer(ltype = 'vector', lname = mapName, lcmd = ['d.vect', 'map=%s' % mapName]) vectLayers = self.UpdateListOfLayers(updateTool = True) selection = vectLayers.index(mapName) # create table ? if dlg.IsChecked('table'): lmgr = self.parent.GetLayerManager() if lmgr: lmgr.OnShowAttributeTable(None, selection = 'table') dlg.Destroy() else: self.combo.SetValue(_('Select vector map')) if dlg: dlg.Destroy() return else: selection = event.GetSelection() - 1 # first option is 'New vector map' # skip currently selected map if self.layers[selection] == self.mapLayer: return if self.mapLayer: # deactive map layer for editing self.StopEditing() # select the given map layer for editing self.StartEditing(self.layers[selection]) event.Skip()
def main(): parser = argparse.ArgumentParser( description='Run test files in all testsuite directories starting' ' from the current one' ' (runs on active GRASS session)') parser.add_argument('--location', dest='location', action='store', help='Name of location where to perform test', required=True) parser.add_argument('--location-type', dest='location_type', action='store', default='nc', help='Type of tests which should be run' ' (tag corresponding to location)') parser.add_argument('--grassdata', dest='gisdbase', action='store', default=None, help='GRASS data(base) (GISDBASE) directory' ' (current GISDBASE by default)') parser.add_argument('--output', dest='output', action='store', default='testreport', help='Output directory') args = parser.parse_args() gisdbase = args.gisdbase if gisdbase is None: # here we already rely on being in GRASS session gisdbase = gcore.gisenv()['GISDBASE'] location = args.location location_type = args.location_type if not gisdbase: sys.stderr.write("GISDBASE (grassdata directory)" " cannot be empty string\n" % gisdbase) sys.exit(1) if not os.path.exists(gisdbase): sys.stderr.write("GISDBASE (grassdata directory) <%s>" " does not exist\n" % gisdbase) sys.exit(1) if not os.path.exists(os.path.join(gisdbase, location)): sys.stderr.write("GRASS Location <{loc}>" " does not exist in GRASS Database <{db}>\n".format( loc=location, db=gisdbase)) sys.exit(1) results_dir = args.output silent_rmtree(results_dir) # TODO: too brute force? start_dir = '.' abs_start_dir = os.path.abspath(start_dir) invoker = GrassTestFilesInvoker( start_dir=start_dir, file_anonymizer=FileAnonymizer(paths_to_remove=[abs_start_dir])) # TODO: remove also results dir from files # as an enhancemnt # we can just iterate over all locations available in database # but the we don't know the right location type (category, label, shortcut) invoker.run_in_location(gisdbase=gisdbase, location=location, location_type=location_type, results_dir=results_dir) return 0
def ParseMapStr(mapStr): """Create full map name (add current mapset if it is not present in name)""" mapValSpl = mapStr.strip().split("@") if len(mapValSpl) > 1: mapSet = mapValSpl[1] else: mapSet = grass.gisenv()['MAPSET'] mapName = mapValSpl[0] return mapName, mapSet
def get_shell_pid(env=None): """Get shell PID from the GIS environment or None""" try: shell_pid = int(grass.gisenv(env=env)["PID"]) return shell_pid except (KeyError, ValueError) as error: Debug.msg( 1, "No PID for GRASS shell (assuming no shell running): {}".format( error)) return None
def _createNewMap(self, mapName, backgroundMap, mapType): """Creates a new raster map based on specified background and type.""" name = mapName.split('@')[0] background = backgroundMap.split('@')[0] types = {'CELL': 'int', 'FCELL': 'float', 'DCELL': 'double'} if background: back = background else: back = 'null()' try: grast.mapcalc(exp="{name} = {mtype}({back})".format( name=name, mtype=types[mapType], back=back), overwrite=True, quiet=True) if background: self._backgroundRaster = backgroundMap gcore.run_command('r.colors', map=name, raster=self._backgroundRaster, quiet=True) if mapType == 'CELL': values = gcore.read_command('r.describe', flags='1n', map=name, quiet=True).strip() if values: self.uploadMapCategories.emit( values=values.split('\n')) except CalledModuleError: raise ScriptError self._backupRaster(name) name = name + '@' + gcore.gisenv()['MAPSET'] self._editedRaster = name self._mapType = mapType self.newRasterCreated.emit(name=name) gisenv = gcore.gisenv() self._giface.grassdbChanged.emit(grassdb=gisenv['GISDBASE'], location=gisenv['LOCATION_NAME'], mapset=gisenv['MAPSET'], action='new', map=name.split('@')[0], element='raster')
def registerPid(pid): """Register process id as GUI_PID GRASS variable :param: pid process id """ env = grass.gisenv() guiPid = [] if "GUI_PID" in env: guiPid = env["GUI_PID"].split(",") guiPid.append(str(pid)) grass.run_command("g.gisenv", set="GUI_PID={0}".format(",".join(guiPid)))
def registerPid(pid): """Register process id as GUI_PID GRASS variable :param: pid process id """ env = grass.gisenv() guiPid = [] if 'GUI_PID' in env: guiPid = env['GUI_PID'].split(',') guiPid.append(str(pid)) grass.run_command('g.gisenv', set='GUI_PID={}'.format(','.join(guiPid)))
def testRegionDef(): import sys import wx.lib.inspection import grass.script as grass app = wx.App() dlg = RegionDef(None, location = grass.gisenv()["LOCATION_NAME"]) dlg.Show() wx.lib.inspection.InspectionTool().Show() app.MainLoop()
def testRegionDef(): import sys import wx.lib.inspection import grass.script as grass app = wx.App() dlg = RegionDef(None, location=grass.gisenv()["LOCATION_NAME"]) dlg.Show() wx.lib.inspection.InspectionTool().Show() app.MainLoop()
def main(): options, flags = gcore.parser() gisenv = gcore.gisenv() if 'MONITOR' in gisenv: cmd_file = gcore.parse_command('d.mon', flags='g')['cmd'] dout_cmd = 'd.out.file' for param, val in options.items(): if val: dout_cmd += " {param}={val}".format(param=param, val=val) with open(cmd_file, "a") as file_: file_.write(dout_cmd) else: gcore.fatal(_("No graphics device selected. Use d.mon to select graphics device."))
def main(): options, flags = gcore.parser() gisenv = gcore.gisenv() if "MONITOR" in gisenv: cmd_file = gisenv["MONITOR_{monitor}_CMDFILE".format(monitor=gisenv["MONITOR"].upper())] dout_cmd = "d.what.vect" for param, val in options.iteritems(): if val: dout_cmd += " {param}={val}".format(param=param, val=val) with open(cmd_file, "a") as file_: file_.write(dout_cmd) else: gcore.fatal(_("No graphics device selected. Use d.mon to select graphics device."))
def remove_vector(name, deleteTable=False): """Helper function to workaround problem with deleting vectors""" gisenv = gcore.gisenv() path_to_vector = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], gisenv['MAPSET'], 'vector', name) if deleteTable: try: gcore.run_command('db.droptable', table=name, flags='f') except CalledModuleError: pass if os.path.exists(path_to_vector): try: shutil.rmtree(path_to_vector) except StandardError: pass
def unregisterPid(pid): """Unregister process id from GUI_PID GRASS variable :param: pid process id """ env = grass.gisenv() if 'GUI_PID' not in env: return guiPid = env['GUI_PID'].split(',') pid = str(os.getpid()) if pid in guiPid: guiPid.remove(pid) grass.run_command('g.gisenv', set='GUI_PID={}'.format(','.join(guiPid)))
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 view(rasters=None, vectors=None, pngfile=None, width=640, height=480, transparent=True, read_file=True, truecolor=True, engine='cairo', compression=9, rkw=None, vkw=None): """Return an IPython image object rendered by GRASS GIS. Parameters ----------- rasters: list List with the raster map name to be rendered vectors: list List with the vector map name to be rendered pngfile: path Path to the PNG file, default creates a temporary file width: int Width size of the image height: int Height size of the image """ def display(): for raster in rasters if rasters else []: d.rast(map=raster, **(rkw if rkw else {})) for vector in vectors if vectors else []: d.vect(map=vector, **(vkw if vkw else {})) pngfile = (tempfile.mkstemp(suffix='.png')[1] if pngfile is None else pngfile) # set the enviornmental variables os.environ['GRASS_RENDER_IMMEDIATE'] = engine os.environ['GRASS_RENDER_FILE'] = pngfile os.environ['GRASS_RENDER_FILE_COMPRESSION'] = str(compression) os.environ['GRASS_RENDER_WIDTH'] = str(width) os.environ['GRASS_RENDER_HEIGHT'] = str(height) os.environ['GRASS_RENDER_TRANSPARENT'] = 'TRUE' if transparent else None os.environ['GRASS_RENDER_READ_FILE'] = 'TRUE' if read_file else None os.environ['GRASS_RENDER_TRUECOLOR'] = 'TRUE' if truecolor else None os.environ['GRASS_RENDER_PNG_AUTO_WRITE'] = 'TRUE' monitor = gcore.gisenv().get('MONITOR', None) if monitor: g.gisenv(unset='MONITOR') display() g.gisenv(set='MONITOR=%s' % monitor) else: display() return Image(pngfile)
def main(): options, flags = gcore.parser() gisenv = gcore.gisenv() if 'MONITOR' in gisenv: cmd_file = gcore.parse_command('d.mon', flags='g').get('cmd', None) if not cmd_file: gcore.fatal(_("Unable to open file '%s'") % cmd_file) dout_cmd = 'd.what.vect' for param, val in options.iteritems(): if val: dout_cmd += " {param}={val}".format(param=param, val=val) with open(cmd_file, "a") as file_: file_.write(dout_cmd) else: gcore.fatal(_("No graphics device selected. Use d.mon to select graphics device."))
def watcher(self): """Redraw, if new layer appears (check's timestamp of cmdfile) """ try: # GISBASE and other sytem enviromental variables can not be used # since the process inherited them from GRASS # raises exception when vaiable does not exists grass.gisenv()['GISDBASE'] except KeyError: self.timer.Stop() return # todo: events try: currentCmdFileTime = os.path.getmtime(monFile['cmd']) if currentCmdFileTime > self.cmdTimeStamp: self.timer.Stop() self.cmdTimeStamp = currentCmdFileTime self.mapFrm.GetMap().GetLayersFromCmdFile() self.timer.Start(mtime) except OSError as e: grass.warning("%s" % e) self.timer.Stop()
def main(): options, flags = gcore.parser() print options, flags gisenv = gcore.gisenv() if 'MONITOR' in gisenv: cmd_file = gisenv['MONITOR_{monitor}_CMDFILE'.format(monitor=gisenv['MONITOR'].upper())] d_cmd = 'd.to.rast' for param, val in options.iteritems(): if val: d_cmd += " {param}={val}".format(param=param, val=val) if gcore.overwrite(): d_cmd += ' --overwrite' with open(cmd_file, "a") as file_: file_.write(d_cmd) else: gcore.fatal(_("No graphics device selected. Use d.mon to select graphics device."))
def LoadData(self): """Load data into list""" self.InsertColumn(0, 'Mapset') self.InsertColumn(1, 'Owner') ### self.InsertColumn(2, 'Group') gisenv = grass.gisenv() locationPath = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME']) self.curr_mapset = gisenv['MAPSET'] ret = grass.read_command('g.mapsets', quiet = True, flags = 'l', fs = 'newline') self.mapsets = [] if ret: self.mapsets = ret.splitlines() ret = grass.read_command('g.mapsets', quiet = True, flags = 'p', fs = 'newline') mapsets_access = [] if ret: mapsets_access = ret.splitlines() for mapset in self.mapsets: index = self.InsertStringItem(sys.maxint, mapset) mapsetPath = os.path.join(locationPath, mapset) stat_info = os.stat(mapsetPath) if os.name in ('posix', 'mac'): self.SetStringItem(index, 1, "%s" % pwd.getpwuid(stat_info.st_uid)[0]) # FIXME: get group name ### self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid) else: # FIXME: no pwd under MS Windows (owner: 0, group: 0) self.SetStringItem(index, 1, "%-8s" % stat_info.st_uid) ### self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid) if mapset in mapsets_access: self.CheckItem(self.mapsets.index(mapset), True) self.SetColumnWidth(col=0, width=wx.LIST_AUTOSIZE) self.SetColumnWidth(col=1, width=wx.LIST_AUTOSIZE)