def GetCommandSeries(self, layerList, paramName): commands = [] if not self.task: return commands if len(layerList) > 1: raise GException(_("Please add only one layer in the list.")) return layer = layerList[0] if hasattr(layer, 'maps'): series = layer.maps else: raise GException( _("No map series nor space-time dataset is added.")) for value in series: self.task.set_param(paramName, value) # FIXME: we assume we want always default color map if paramName == 'elevation_map': self.task.set_param('color_map', '') if paramName == 'volume': self.task.set_param('isosurf_color_map', '') self.task.set_flag('overwrite', True) self.task.set_param('output', 'tobechanged') cmd = self.task.get_cmd(ignoreErrors=False, ignoreRequired=False, ignoreDefault=True) commands.append(cmd) return commands
def SaveToFile(self, settings=None): """Save settings to the file""" if settings is None: settings = self.userSettings dirPath = GetSettingsPath() if not os.path.exists(dirPath): try: os.mkdir(dirPath) except: GError(_('Unable to create settings directory')) return try: with open(self.filePath, 'w') as f: json.dump(settings, f, indent=2, cls=SettingsJSONEncoder) except IOError as e: raise GException(e) except Exception as e: raise GException( _('Writing settings to file <%(file)s> failed.' '\n\nDetails: %(detail)s') % { 'file': self.filePath, 'detail': e }) return self.filePath
def validateMapNames(names, etype): """Checks if maps exist and completes missing mapset. Input is list of map names. Raises GException if map doesn't exist. """ mapDict = grass.list_grouped(etype) newNames = [] for name in names: if name.find("@") >= 0: nameShort, mapset = name.split('@', 1) if nameShort in mapDict[mapset]: newNames.append(name) else: raise GException(_("Map <%s> not found.") % name) else: found = False for mapset, mapNames in mapDict.iteritems(): if name in mapNames: found = True newNames.append(name + "@" + mapset) if not found: raise GException(_("Map <%s> not found.") % name) return newNames
def Render(self): """Render layer to image :return: rendered image filename :return: None on error or if cmdfile is defined """ if not self.cmd: return None # ignore in 2D if self.type == '3d-raster': return None Debug.msg (3, "Layer.Render(): type=%s, name=%s" % \ (self.type, self.name)) # prepare command for each layer layertypes = utils.command2ltype.values() + ['overlay', 'command'] if self.type not in layertypes: raise GException(_("<%(name)s>: layer type <%(type)s> is not supported") % \ {'type' : self.type, 'name' : self.name}) if self.mapfile: self.environ["GRASS_PNGFILE"] = self.mapfile # execute command try: if self.type == 'command': read = False for c in self.cmd: ret, msg = self._runCommand(c) if ret != 0: break if not read: self.environ["GRASS_PNG_READ"] = "TRUE" self.environ["GRASS_PNG_READ"] = "FALSE" else: ret, msg = self._runCommand(self.cmd) if ret != 0: sys.stderr.write(_("Command '%s' failed\n") % self.GetCmd(string = True)) if msg: sys.stderr.write(_("Details: %s\n") % msg) raise GException() except GException: # clean up after problems for f in [self.mapfile, self.maskfile]: if not f: continue try_remove(f) f = None self.forceRender = False return self.mapfile
def SaveToFile(self, settings = None): """Save settings to the file""" if settings is None: settings = self.userSettings dirPath = GetSettingsPath() if not os.path.exists(dirPath): try: os.mkdir(dirPath) except: GError(_('Unable to create settings directory')) return try: file = open(self.filePath, "w") for group in settings.keys(): for key in settings[group].keys(): subkeys = settings[group][key].keys() file.write('%s%s%s%s' % (group, self.sep, key, self.sep)) for idx in range(len(subkeys)): value = settings[group][key][subkeys[idx]] if type(value) == types.DictType: if idx > 0: file.write('%s%s%s%s%s' % (os.linesep, group, self.sep, key, self.sep)) file.write('%s%s' % (subkeys[idx], self.sep)) kvalues = settings[group][key][subkeys[idx]].keys() srange = range(len(kvalues)) for sidx in srange: svalue = self._parseValue(settings[group][key][subkeys[idx]][kvalues[sidx]]) file.write('%s%s%s' % (kvalues[sidx], self.sep, svalue)) if sidx < len(kvalues) - 1: file.write('%s' % self.sep) else: if idx > 0 and \ type(settings[group][key][subkeys[idx - 1]]) == types.DictType: file.write('%s%s%s%s%s' % (os.linesep, group, self.sep, key, self.sep)) value = self._parseValue(settings[group][key][subkeys[idx]]) file.write('%s%s%s' % (subkeys[idx], self.sep, value)) if idx < len(subkeys) - 1 and \ type(settings[group][key][subkeys[idx + 1]]) != types.DictType: file.write('%s' % self.sep) file.write(os.linesep) except IOError as e: raise GException(e) except StandardError as e: raise GException(_('Writing settings to file <%(file)s> failed.' '\n\nDetails: %(detail)s') % { 'file' : self.filePath, 'detail' : e }) file.close() return self.filePath
def AddMapLayer(self, mlayer, render = False, pos = -1): wx.BeginBusyCursor() # opacity must be <0;1> if mlayer.opacity < 0: opacity = 0 elif mlayer.opacity > 1: opacity = 1 # add maplayer to the list of layers if pos > -1: self.layers.insert(pos, mlayer) else: self.layers.append(mlayer) Debug.msg (3, "Map.AddLayer(): layer=%s" % mlayer.name) if render: if not mlayer.Render(): raise GException(_("Unable to render map layer <%s>.") % mlayer.name) wx.EndBusyCursor() return mlayer
def AddOverlay(self, id, ltype, command, active = True, hidden = True, opacity = 1.0, render = False): """Adds overlay (grid, barscale, legend, etc.) to list of overlays :param id: overlay id (PseudoDC) :param ltype: overlay type (barscale, legend) :param command: GRASS command to render overlay :param active: overlay activated (True) or disabled (False) :param hidden: overlay is not shown in layer tree (if True) :param render: render an image (if True) :return: new layer on success :return: None on failure """ Debug.msg (2, "Map.AddOverlay(): cmd=%s, render=%d" % (command, render)) overlay = Overlay(id = id, ltype = ltype, cmd = command, Map = self, active = active, hidden = hidden, opacity = opacity) # add maplayer to the list of layers self.overlays.append(overlay) if render and command != '' and not overlay.Render(): raise GException(_("Unable to render overlay <%s>.") % ltype) return self.overlays[-1]
def Set(self, group, value, key=None, subkey=None, internal=False): """!Set value of key/subkey Raise KeyError if group/key is not found @param group settings group @param key key (value, None) @param subkey subkey (value, list or None) @param value value @param internal use internal settings instead """ if internal is True: settings = self.internalSettings else: settings = self.userSettings try: if subkey is None: if key is None: settings[group] = value else: settings[group][key] = value else: if type(subkey) == type(tuple()) or \ type(subkey) == type(list()): settings[group][key][subkey[0]][subkey[1]] = value else: settings[group][key][subkey] = value except KeyError: raise GException("%s '%s:%s:%s'" % (_("Unable to set "), group, key, subkey))
def _updateCatRast(self, bbox, areas_cats, updated_cats): rasterized_cats = [] for c in range(len(areas_cats)): if not areas_cats[c]: continue layer = list(areas_cats[c])[0] cat = areas_cats[c][layer][0] if cat in rasterized_cats: continue rasterized_cats.append(cat) updated_cats.append(cat) grass_region = self._create_grass_region_env(bbox) # TODO hack check if raster exists? patch_rast = "temp_scatt_patch_%d" % (os.getpid()) self._rasterize(grass_region, layer, cat, patch_rast) region = self.an_data.GetRegion() ret = UpdateCatRast(patch_rast, region, self.scatts_dt.GetCatRastCond(cat)) if ret < 0: GException( _("Patching category raster conditions file failed.")) RunCommand("g.remove", flags="f", type="raster", name=patch_rast)
def GetRasterInfo(rast): ret, out, msg = RunCommand("r.info", map=rast, flags="rg", getErrorMsg=True, read=True) if ret != 0: raise GException("r.info failed:\n%s" % msg) out = out.splitlines() raster_info = {} for b in out: if not b.strip(): continue k, v = b.split("=") if k == "datatype": if v != "CELL": return None pass elif k in ["rows", "cols", "cells", "min", "max"]: v = int(v) else: v = float(v) raster_info[k] = v raster_info["range"] = raster_info["max"] - raster_info["min"] + 1 return raster_info
def LoadOverlay(self, cmd): """Creates raster legend with d.legend :param cmd: d.legend command as a list :return: bitmap with legend """ Debug.msg(5, "BitmapProvider.LoadOverlay: cmd={c}".format(c=cmd)) fileHandler, filename = tempfile.mkstemp(suffix=".png") os.close(fileHandler) # Set the environment variables for this process _setEnvironment( self.imageWidth, self.imageHeight, filename, transparent=True, bgcolor=(0, 0, 0), ) Debug.msg(1, "Render raster legend " + str(filename)) cmdTuple = cmdlist_to_tuple(cmd) returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1]) if returncode == 0: return BitmapFromImage(autoCropImageFromFile(filename)) else: os.remove(filename) raise GException(messages)
def ComputeCatsScatts(self, cats_ids): requested_dt = {} requested_dt_conds = {} for c in cats_ids: requested_dt_conds[c] = self.scatt_conds_dt.GetCatScatts(c) requested_dt[c] = self.scatts_dt.GetCatScatts(c) scatt_conds = self.scatt_conds_dt.GetData(requested_dt_conds) scatts = self.scatts_dt.GetData(requested_dt) bands = self.an_data.GetBands() cats_rasts = self.scatts_dt.GetCatsRasts() cats_rasts_conds = self.scatts_dt.GetCatsRastsConds() returncode, scatts = ComputeScatts( self.an_data.GetRegion(), scatt_conds, bands, len(self.GetBands()), scatts, cats_rasts_conds, cats_rasts, ) if returncode < 0: GException(_("Computing of scatter plots failed."))
def Set(self, group, value, key=None, subkey=None, settings_type='user'): """Set value of key/subkey Raise KeyError if group/key is not found :param group: settings group :param key: key (value, None) :param subkey: subkey (value, list or None) :param value: value :param settings_type: 'user', 'internal', 'default' """ if settings_type == 'user': settings = self.userSettings elif settings_type == 'internal': settings = self.internalSettings else: settings = self.defaultSettings try: if subkey is None: if key is None: settings[group] = value else: settings[group][key] = value else: if isinstance(subkey, type(tuple())) or \ isinstance(subkey, type(list())): settings[group][key][subkey[0]][subkey[1]] = value else: settings[group][key][subkey] = value except KeyError: raise GException("%s '%s:%s:%s'" % (_("Unable to set "), group, key, subkey))
def Load(self, url, full=True): """Load list of extensions""" self._emptyTree() if full: flags = "g" else: flags = "l" retcode, ret, msg = RunCommand("g.extension", read=True, getErrorMsg=True, url=url, flags=flags, quiet=True) if retcode != 0: raise GException(_("Unable to load extensions. %s") % msg) currentNode = None for line in ret.splitlines(): if full: try: key, value = line.split("=", 1) except ValueError: key = "name" value = line if key == "name": try: prefix, name = value.split(".", 1) except ValueError: prefix = "" name = value mainNode = self.mainNodes[self._expandPrefix(prefix)] currentNode = self.model.AppendNode(parent=mainNode, label=value) currentNode.data = {"command": value} else: if currentNode is not None: currentNode.data[key] = value else: try: prefix, name = line.strip().split(".", 1) except ValueError: prefix = "" name = line.strip() if self._expandPrefix(prefix) == prefix: prefix = "" module = prefix + "." + name mainNode = self.mainNodes[self._expandPrefix(prefix)] currentNode = self.model.AppendNode(parent=mainNode, label=module) currentNode.data = { "command": module, "keywords": "", "description": "", }
def Load(self, url, full=True): """Load list of extensions""" self._emptyTree() if full: flags = 'g' else: flags = 'l' retcode, ret, msg = RunCommand('g.extension', read=True, getErrorMsg=True, url=url, flags=flags, quiet=True) if retcode != 0: raise GException(_("Unable to load extensions. %s") % msg) currentNode = None for line in ret.splitlines(): if full: try: key, value = line.split('=', 1) except ValueError: key = 'name' value = line if key == 'name': try: prefix, name = value.split('.', 1) except ValueError: prefix = '' name = value mainNode = self.mainNodes[self._expandPrefix(prefix)] currentNode = self.model.AppendNode(parent=mainNode, label=value) currentNode.data = {'command': value} else: if currentNode is not None: currentNode.data[key] = value else: try: prefix, name = line.strip().split('.', 1) except ValueError: prefix = '' name = line.strip() if self._expandPrefix(prefix) == prefix: prefix = '' module = prefix + '.' + name mainNode = self.mainNodes[self._expandPrefix(prefix)] currentNode = self.model.AppendNode(parent=mainNode, label=module) currentNode.data = { 'command': module, 'keywords': '', 'description': '' }
def SetType(self, type): """!Set layer type""" if type not in ('raster', '3d-raster', 'vector', 'overlay', 'command', 'shaded', 'rgb', 'his', 'rastarrow', 'rastnum', 'thememap', 'themechart', 'grid', 'labels', 'geodesic', 'rhumb'): raise GException(_("Unsupported map layer type '%s'") % type) self.type = type
def AddLayer( self, ltype, command, name=None, active=True, hidden=False, opacity=1.0, render=False, pos=-1, ): """!Adds generic map layer to list of layers @param ltype layer type ('raster', 'vector', etc.) @param command GRASS command given as list @param name layer name @param active layer render only if True @param hidden layer not displayed in layer tree if True @param opacity opacity level range from 0(transparent) - 1(not transparent) @param render render an image if True @param pos position in layer list (-1 for append) @return new layer on success @return None on failure """ wx.BeginBusyCursor() # opacity must be <0;1> if opacity < 0: opacity = 0 elif opacity > 1: opacity = 1 layer = MapLayer( ltype=ltype, name=name, cmd=command, Map=self, active=active, hidden=hidden, opacity=opacity, ) # add maplayer to the list of layers if pos > -1: self.layers.insert(pos, layer) else: self.layers.append(layer) Debug.msg(3, "Map.AddLayer(): layer=%s" % layer.name) if render: if not layer.Render(): raise GException(_("Unable to render map layer <%s>.") % name) wx.EndBusyCursor() return layer
def GetRegion(): ret, region, msg = RunCommand("g.region", flags="gp", getErrorMsg=True, read=True) if ret != 0: raise GException("g.region failed:\n%s" % msg) return _parseRegion(region)
def _rasterize(self, grass_region, layer, cat, out_rast): # TODO different thread may be problem when user edits map environs = os.environ.copy() environs["GRASS_VECTOR_TEMPORARY"] = "1" ret, text, msg = RunCommand( "v.category", input=self.vectMap, getErrorMsg=True, option="report", read=True, env=environs, ) ret, text, msg = RunCommand("v.build", map=self.vectMap, getErrorMsg=True, read=True, env=environs) if ret != 0: GException(_("v.build failed:\n%s" % msg)) environs = os.environ.copy() environs["GRASS_REGION"] = grass_region["GRASS_REGION"] environs["GRASS_VECTOR_TEMPORARY"] = "1" ret, text, msg = RunCommand( "v.to.rast", input=self.vectMap, use="cat", layer=str(layer), cat=str(cat), output=out_rast, getErrorMsg=True, read=True, overwrite=True, env=environs, ) if ret != 0: GException(_("v.to.rast failed:\n%s" % msg))
def MergeArrays(merged_arr, overlay_arr, alpha): if merged_arr.shape != overlay_arr.shape: GException("MergeArrays: merged_arr.shape != overlay_arr.shape") c_uint8_p = POINTER(c_uint8) merged_p = merged_arr.ctypes.data_as(c_uint8_p) overlay_p = overlay_arr.ctypes.data_as(c_uint8_p) I_merge_arrays(merged_p, overlay_p, merged_arr.shape[0], merged_arr.shape[1], alpha)
def OnRenderDone(self): """Rendering process done Make image composiotion, emits updateMap event. """ stopTime = time.time() maps = list() masks = list() opacities = list() for layer in self.layers: if layer.GetType() == 'overlay': continue if os.path.isfile(layer.mapfile): maps.append(layer.mapfile) masks.append(layer.maskfile) opacities.append(str(layer.opacity)) # run g.pngcomp to get composite image bgcolor = ':'.join( map( str, UserSettings.Get(group='display', key='bgcolor', subkey='color'))) startCompTime = time.time() if maps: ret, msg = RunCommand('g.pnmcomp', getErrorMsg=True, overwrite=True, input='%s' % ",".join(maps), mask='%s' % ",".join(masks), opacity='%s' % ",".join(opacities), bgcolor=bgcolor, width=self.Map.width, height=self.Map.height, output=self.Map.mapfile, env=self._env) if ret != 0: self._rendering = False if wx.IsBusy(): wx.EndBusyCursor() raise GException(_("Rendering failed: %s" % msg)) stop = time.time() Debug.msg (1, "RenderMapMgr.OnRenderDone() time=%f sec (comp: %f)" % \ (stop - self._startTime, stop - startCompTime)) self._rendering = False if wx.IsBusy(): wx.EndBusyCursor() self.updateMap.emit()
def Create(self, bands): self.bands = bands[:] self.region = None self.region = GetRegion() if self.region["rows"] * self.region["cols"] > MAX_NCELLS: GException("too big region") self.bands_info = {} for b in self.bands[:]: i = GetRasterInfo(b) if i is None: GException("raster %s is not CELL type" % (b)) self.bands_info[b] = i # TODO check size of raster return True
def validateTimeseriesName(timeseries, etype='strds'): """Checks if space time dataset exists and completes missing mapset. Raises GException if dataset doesn't exist. """ trastDict = tgis.tlist_grouped(etype) if timeseries.find("@") >= 0: nameShort, mapset = timeseries.split('@', 1) if nameShort in trastDict[mapset]: return timeseries else: raise GException( _("Space time dataset <%s> not found.") % timeseries) mapsets = tgis.get_tgis_c_library_interface().available_mapsets() for mapset in mapsets: if mapset in trastDict.keys(): if timeseries in trastDict[mapset]: return timeseries + "@" + mapset raise GException(_("Space time dataset <%s> not found.") % timeseries)
def Load(self, filename): self.task = gtask.grassTask("m.nviz.image") self.filename = filename try: gxwXml = ProcessWorkspaceFile(etree.parse(self.filename)) except Exception: raise GException(_("Reading workspace file <%s> failed.\n" "Invalid file, unable to parse XML document.") % filename) # for display in gxwXml.displays: # pprint(display) # for layer in gxwXml.layers: # pprint(layer) # pprint(gxwXml.nviz_state) if not gxwXml.nviz_state: raise GException( _("No 3d view information in workspace file <%s>.") % self.filename) self._getExtent(gxwXml) self._processState(gxwXml.nviz_state) self._processLayers(gxwXml.layers)
def SetType(self, ltype): """Set layer type""" if ltype not in utils.command2ltype.values() + ['overlay', 'command']: raise GException(_("Unsupported map layer type '%s'") % ltype) if ltype == 'wms' and not isinstance(self.renderMgr, RenderWMSMgr): self.renderMgr = RenderWMSMgr(layer=self, mapfile=self.mapfile, maskfile=self.maskfile) elif self.type == 'wms' and ltype != 'wms': self.renderMgr = None self.type = ltype
def Render(self, env=None): """Render layer to image :return: rendered image filename :return: None on error or if cmdfile is defined """ if not self.cmd: return None # ignore in 2D if self.type == 'raster_3d': return None Debug.msg (3, "Layer.Render(): type=%s, name=%s, file=%s" % \ (self.type, self.name, self.mapfile)) # prepare command for each layer layertypes = utils.command2ltype.values() + ['overlay', 'command'] if self.type not in layertypes: raise GException(_("<%(name)s>: layer type <%(type)s> is not supported") % \ {'type' : self.type, 'name' : self.name}) if not env: env = os.environ.copy() # render layers try: if self.type == 'command': first = True for c in self.cmd: self.renderMgr.Render(c, env) if first: env["GRASS_RENDER_FILE_READ"] = "TRUE" first = False else: self.renderMgr.Render(self.cmd, env) except GException: sys.stderr.write( _("Command '%s' failed\n") % self.GetCmd(string=True)) sys.stderr.write(_("Details: %s\n") % e) # clean up after problems for f in [self.mapfile, self.maskfile]: if not f: continue try_remove(f) f = None return self.mapfile
def SetEditCatData(self, cat_id, scatt_id, bbox, value): if cat_id not in self.scatts_dt.GetCategories(): raise GException(_("Select category for editing.")) if self.scatt_conds_dt.AddScattPlot(cat_id, scatt_id) < 0: return None arr = self.scatt_conds_dt.GetValuesArr(cat_id, scatt_id) for k, v in six.iteritems(bbox): bbox[k] = self._validExtend(v) arr[bbox["btm_y"]:bbox["up_y"], bbox["btm_x"]:bbox["up_x"]] = value self.ComputeCatsScatts([cat_id]) return cat_id
def SetType(self, ltype): """!Set layer type""" if ltype not in utils.command2ltype.values() + ["overlay", "command"]: raise GException(_("Unsupported map layer type '%s'") % ltype) if ltype == "wms" and not isinstance(self.renderMgr, RenderWMSMgr): self.renderMgr = RenderWMSMgr( receiver=self.Map.GetReceiver(), layer=self, Map=self.Map, mapfile=self.mapfile, maskfile=self.maskfile, ) elif self.type == "wms" and ltype != "wms": self.renderMgr = None self.type = ltype
def AddLayer(self, ltype, command, name = None, active = True, hidden = False, opacity = 1.0, render = False, pos = -1): """Adds generic map layer to list of layers :param ltype: layer type ('raster', 'vector', etc.) :param command: GRASS command given as list :param name: layer name :param active: layer render only if True :param hidden: layer not displayed in layer tree if True :param opacity: opacity level range from 0(transparent) - 1(not transparent) :param render: render an image if True :param pos: position in layer list (-1 for append) :return: new layer on success :return: None on failure """ wx.BeginBusyCursor() # opacity must be <0;1> if opacity < 0: opacity = 0 elif opacity > 1: opacity = 1 layer = MapLayer(ltype = ltype, name = name, cmd = command, Map = self, active = active, hidden = hidden, opacity = opacity) # add maplayer to the list of layers if pos > -1: self.layers.insert(pos, layer) else: self.layers.append(layer) Debug.msg (3, "Map.AddLayer(): layer=%s" % layer.name) if render: if not layer.Render(): raise GException(_("Unable to render map layer <%s>.") % name) renderMgr = layer.GetRenderMgr() if renderMgr: renderMgr.dataFetched.connect(self.layerChanged) renderMgr.updateProgress.connect(self.ReportProgress) wx.EndBusyCursor() return layer
def SetType(self, ltype): """Set layer type""" if ltype not in utils.command2ltype.values() + ['overlay', 'command']: raise GException(_("Unsupported map layer type '%s'") % ltype) if not self.renderMgr: env = {} if ltype == 'wms': renderMgr = RenderWMSMgr else: renderMgr = RenderLayerMgr env['GRASS_RENDER_FILE'] = self.mapfile if ltype == 'overlay': env['GRASS_RENDER_FILE_READ'] = 'FALSE' env['GRASS_RENDER_TRANSPARENT'] = 'TRUE' self.renderMgr = renderMgr(self, env) self.type = ltype