Exemplo n.º 1
0
    def CheckBands(self, b_1, b_2):
        bands = self.core.GetBands()
        added_scatts_ids = self.plots.keys()

        b_1_id = self.all_bands_to_bands[self.all_bands[b_1]]
        b_2_id = self.all_bands_to_bands[self.all_bands[b_1]]

        scatt_id = idBandsToidScatt(b_1_id, b_2_id, len(bands))

        if scatt_id in added_scatts_ids:
            GWarning(
                parent=self.guiparent, message=_(
                    "Scatter plot with same band combination (regardless x y order) "
                    "is already displayed."))
            return False

        b_1_name = self.all_bands[b_1]
        b_2_name = self.all_bands[b_2]

        b_1_i = self.bands_info[b_1_name]
        b_2_i = self.bands_info[b_2_name]

        err = ""
        for b in [b_1_name, b_2_name]:
            if self.bands_info[b] is None:
                err += _("Band <%s> is not CELL (integer) type.\n" % b)
        if err:
            GMessage(parent=self.guiparent,
                     message=_("Scatter plot cannot be added.\n" + err))
            return False

        mrange = b_1_i['range'] * b_2_i['range']
        if mrange > MAX_SCATT_SIZE:
            GWarning(parent=self.guiparent,
                     message=_("Scatter plot cannot be added.\n"
                               "Multiple of bands ranges <%s:%d * %s:%d = %d> "
                               "is higher than maximum limit <%d>.\n"
                               % (b_1_name, b_1_i['range'], b_1_name, b_2_i['range'],
                                  mrange, MAX_SCATT_SIZE)))
            return False
        elif mrange > WARN_SCATT_SIZE:
            dlg = wx.MessageDialog(
                parent=self.guiparent,
                message=_(
                    "Multiple of bands ranges <%s:%d * %s:%d = %d> "
                    "is higher than recommended limit <%d>.\n"
                    "It is strongly advised to reduce range extend of bands"
                    "(e. g. using r.rescale) below recommended threshold.\n\n"
                    "Do you really want to add this scatter plot?" %
                    (b_1_name, b_1_i['range'],
                     b_1_name, b_2_i['range'],
                     mrange, WARN_SCATT_SIZE)),
                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING)
            ret = dlg.ShowModal()
            if ret != wx.ID_YES:
                return False

        return True
Exemplo n.º 2
0
    def GetSelectedMap(self):
        """Return name of selected map in layer tree"""
        layerList = self._giface.GetLayerList()
        layerSelected = layerList.GetSelectedLayer()
        if layerSelected is None:
            return None

        if not layerSelected.maplayer.IsActive():
            GWarning(_("Selected map <%s> has been disabled for rendering. "
                       "Operation canceled.") % str(layerSelected),
                     parent=self.mapWin)
            return None

        if layerSelected:
            if layerSelected.type != 'vector':
                mapName = None
                self.UnregisterMapEvtHandler()
                GError(_("No vector map layer selected. Operation canceled."))
            else:
                mapName = str(layerSelected)
                if self.mapName is not None:
                    if self.mapName != mapName:
                        self.Reset()
        else:
            mapName = None
            self.UnregisterMapEvtHandler()
            GError(_("No map layer selected. Operation canceled."))
        return mapName
Exemplo n.º 3
0
 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)
Exemplo n.º 4
0
 def OnCmdOutput(self, event):
     """Handle cmd output according to debug level."""
     if Debug.GetLevel() == 0:
         if event.type == "error":
             msg = _("Unable to fetch data.\n")
             msg += event.text
             GWarning(parent=self, message=msg)
     else:
         Debug.msg(1, event.text)
Exemplo n.º 5
0
    def _onLeftDown(self, event):
        action = self.toolbar.GetAction()
        if not action:
            return

        region = grass.region()
        e, n = self.Pixel2Cell(event.GetPosition())
        if not ((region["s"] <= n <= region["n"]) and
                (region["w"] <= e <= region["e"])):
            GWarning(
                parent=self.parent,
                message=_(
                    "You are trying to create a training area "
                    "outside the computational region. "
                    "Please, use g.region to set the appropriate region first."
                ),
            )
            return

        cat = self.GetCurrentCategory()

        if cat is None and action == "addLine":
            dlg = wx.MessageDialog(
                parent=self.parent,
                message=_("In order to create a training area, "
                          "you have to select class first.\n\n"
                          "There is no class yet, "
                          "do you want to create one?"),
                caption=_("No class selected"),
                style=wx.YES_NO,
            )
            if dlg.ShowModal() == wx.ID_YES:
                self.parent.OnCategoryManager(None)

            dlg.Destroy()
            event.Skip()
            return

        super(IClassVDigitWindow, self)._onLeftDown(event)
Exemplo n.º 6
0
    def SetupProfile(self):
        """Create coordinate string for profiling. Create segment
           list for transect segment markers.
        """
        # create list of coordinate points for r.profile
        dist = 0
        cumdist = 0
        self.coordstr = ''
        lasteast = lastnorth = None

        region = grass.region()
        insideRegion = True
        if len(self.transect) > 0:
            for point in self.transect:
                if not (region['w'] <= point[0] <= region['e']
                        and region['s'] <= point[1] <= region['n']):
                    insideRegion = False
                # build string of coordinate points for r.profile
                if self.coordstr == '':
                    self.coordstr = '%f,%f' % (point[0], point[1])
                else:
                    self.coordstr = '%s,%f,%f' % (self.coordstr, point[0],
                                                  point[1])

        if not insideRegion:
            GWarning(message=_(
                "Not all points of profile lie inside computational region."),
                     parent=self)

        if len(self.rasterList) == 0:
            return

        # title of window
        self.ptitle = _('Profile of')

        # create list of coordinates for transect segment markers
        if len(self.transect) > 0:
            self.seglist = []
            for point in self.transect:
                # get value of raster cell at coordinate point
                ret = RunCommand('r.what',
                                 parent=self,
                                 read=True,
                                 map=self.rasterList[0],
                                 coordinates='%f,%f' % (point[0], point[1]))

                val = ret.splitlines()[0].split('|')[3]
                if val is None or val == '*':
                    continue
                val = float(val)

                # calculate distance between coordinate points
                if lasteast and lastnorth:
                    dist = math.sqrt(
                        math.pow((lasteast - point[0]), 2) +
                        math.pow((lastnorth - point[1]), 2))
                cumdist += dist

                # store total transect length
                self.transect_length = cumdist

                # build a list of distance,value pairs for each segment of
                # transect
                self.seglist.append((cumdist, val))
                lasteast = point[0]
                lastnorth = point[1]

            # delete extra first segment point
            try:
                self.seglist.pop(0)
            except:
                pass

        #
        # create datalist of dist/value pairs and y labels for each raster map
        #
        self.ylabel = ''
        i = 0

        for r in six.iterkeys(self.raster):
            self.raster[r]['datalist'] = []
            datalist = self.CreateDatalist(r, self.coordstr)
            if len(datalist) > 0:
                self.raster[r]['datalist'] = datalist

                # update ylabel to match units if they exist
                if self.raster[r]['units'] != '':
                    self.ylabel += '%s (%d),' % (self.raster[r]['units'], i)
                i += 1

                # update title
                self.ptitle += ' %s ,' % r.split('@')[0]

        self.ptitle = self.ptitle.rstrip(',')

        if self.ylabel == '':
            self.ylabel = _('Raster values')
        else:
            self.ylabel = self.ylabel.rstrip(',')
Exemplo n.º 7
0
    def OnSave(self, event):
        """Import WMS raster data into GRASS as raster layer."""
        self.thread.abort(abortall=True)
        currmapset = grass.gisenv()["MAPSET"]

        self.output = self.params["output"].GetValue().strip()
        l_spl = self.output.strip().split("@")

        # check output layer
        msg = None
        if not self.output:
            msg = _("Missing output raster.")

        elif len(l_spl) > 1 and l_spl[1] != currmapset:
            msg = _("Output map can be added only to current mapset.")

        elif (not self.overwrite.IsChecked()
              and grass.find_file(self.output, "cell", ".")["fullname"]):
            msg = _("Output map <%s> already exists" % self.output)

        if msg:
            GMessage(parent=self, message=msg)
            return

        self.output = l_spl[0]

        # check region
        region = self.params["region"].GetValue().strip()
        reg_spl = region.strip().split("@")

        reg_mapset = "."
        if len(reg_spl) > 1:
            reg_mapset = reg_spl[1]

        if self.region_types["named"].GetValue():
            if not grass.find_file(reg_spl[0], "windows",
                                   reg_mapset)["fullname"]:
                msg = _("Region <%s> does not exist." %
                        self.params["region"].GetValue())
                GWarning(parent=self, message=msg)
                return

        # create r.in.wms command
        cmd = ("r.in.wms", deepcopy(self.cmd[1]))

        if "map" in cmd[1]:
            del cmd[1]["map"]

        cmd[1]["output"] = self.output

        if self.overwrite.IsChecked():
            cmd[1]["overwrite"] = True

        env = os.environ.copy()
        if self.region_types["named"].GetValue():
            cmd[1]["region"] = region
        elif self.region_types["display"].GetValue():
            region = self._giface.GetMapWindow().GetMap().SetRegion()
            env["GRASS_REGION"] = region

        cmdList = cmdtuple_to_list(cmd)
        self.currentPid = self.thread.GetId()

        self.thread.RunCmd(cmdList, env=env, stderr=self.cmdStdErr)

        self.statusbar.SetStatusText(_("Downloading data..."))
Exemplo n.º 8
0
    def OnSave(self, event):
        """Import WMS raster data into GRASS as raster layer.
        """
        self.thread.abort(abortall=True)
        currmapset = grass.gisenv()['MAPSET']

        self.output = self.params['output'].GetValue().strip()
        l_spl = self.output.strip().split("@")

        # check output layer
        msg = None
        if not self.output:
            msg = _('Missing output raster.')

        elif len(l_spl) > 1 and \
                l_spl[1] != currmapset:
            msg = _('Output map can be added only to current mapset.')

        elif not self.overwrite.IsChecked() and\
                grass.find_file(self.output, 'cell', '.')['fullname']:
            msg = _('Output map <%s> already exists' % self.output)

        if msg:
            GMessage(parent=self, message=msg)
            return

        self.output = l_spl[0]

        # check region
        region = self.params['region'].GetValue().strip()
        reg_spl = region.strip().split("@")

        reg_mapset = '.'
        if len(reg_spl) > 1:
            reg_mapset = reg_spl[1]

        if self.region_types['named'].GetValue():
            if not grass.find_file(reg_spl[0], 'windows',
                                   reg_mapset)['fullname']:
                msg = _('Region <%s> does not exist.' %
                        self.params['region'].GetValue())
                GWarning(parent=self, message=msg)
                return

        # create r.in.wms command
        cmd = ('r.in.wms', deepcopy(self.cmd[1]))

        if 'map' in cmd[1]:
            del cmd[1]['map']

        cmd[1]['output'] = self.output

        if self.overwrite.IsChecked():
            cmd[1]['overwrite'] = True

        env = os.environ.copy()
        if self.region_types['named'].GetValue():
            cmd[1]['region'] = region
        elif self.region_types['display'].GetValue():
            region = self._giface.GetMapWindow().GetMap().SetRegion()
            env['GRASS_REGION'] = region

        cmdList = cmdtuple_to_list(cmd)
        self.currentPid = self.thread.GetId()

        self.thread.RunCmd(cmdList, env=env, stderr=self.cmdStdErr)

        self.statusbar.SetStatusText(_("Downloading data..."))
Exemplo n.º 9
0
    def createPDF(self, save=True):
        self.story = self._parseMDOWS()
        self.doc = Pdf('Metadata file', 'GRASS GIS')

        self.doc.set_theme(MyTheme)

        logo_path = get_lib_path("wx.metadata", 'config')
        logo_path = os.path.join(logo_path, 'logo_variant_bg.png')
        self.doc.add_image(logo_path, 57, 73, LEFT)

        if self.map is None:
            self.doc.add_header(self.filename, T1)
        else:
            self.doc.add_header(self.map, T1)
            self.doc.add_header(self.filename, T2)

        if self.type == 'vector':
            name = 'vector map'
            self.doc.add_header(name, T2)
        else:
            name = 'raster map'
            self.doc.add_header(name, T2)

        self.doc.add_header("%s metadata profile" % self.profile, T3)

        self.doc.add_spacer(2)

        if map is not None:
            mapPic = self.getMapPic()
            self.doc.add_image(mapPic, 200, 200, CENTER)

        self.textFactory(title="Keywords",
                         name='Keywords',
                         tag='identification',
                         multiple=-1)
        self.textFactory(title="Abstract",
                         name='Abstract',
                         tag='identification')
        # #################### metadata #################################
        self.doc.add_spacer(25)
        self.doc.add_header("Metadata on metadata", H1)
        head = ['Organization name', 'E-mail',
                'Role']  # this is the header row
        self.tableFactory("Metadata point of contact", head, 'contact')
        self.textFactory(title="Metadata date",
                         name='Datestamp',
                         tag='datestamp')
        self.textFactory(title="Metadata language",
                         name='Language',
                         tag='languagecode')
        # #################### identification #################################
        self.doc.add(PageBreak())
        self.doc.add_header("Identification", H1)
        self.textFactory(title="Restource title",
                         name='Title',
                         tag='identification')
        self.textFactory(title="Identifier",
                         name='Identifier',
                         tag='identifier')
        # self.textFactory(title="Resource locator", name='Identifier',tag='identifier')#TODO linkage is missing

        self.tableFactory("Resource language", ['Language'], 'identification')
        # head = ['Organization name', 'E-mail','Role']
        #.tableFactory("identifier",head,'contact')

        ##################### Keywords ################################## TODO

        ##################### Geographic ##################################
        self.doc.add_spacer(25)
        self.doc.add_header('Geographic Location', H1)

        maxy = float(self.findItem(self.story['identification'], 'maxy', 0))
        maxx = float(self.findItem(self.story['identification'], 'maxx', 0))
        miny = float(self.findItem(self.story['identification'], 'miny', 0))
        minx = float(self.findItem(self.story['identification'], 'minx', 0))

        head = [[
            'North Bound Latitude', 'East Bound Longitude',
            'South Bound Latitude', 'West Bound Longitude'
        ]]
        head.append([maxx, maxy, minx, miny])
        self.doc.add_table(head, self.TABLE_WIDTH)
        self.doc.add_spacer(25)
        mapPath = MapBBFactory([[maxx, minx], [maxy, miny]], )

        ##################### Add google picture(extend) ##################################
        try:
            gmap = Image(mapPath.link1, 200, 200)
            gmap1 = Image(mapPath.link2, 200, 200)
            self.doc.add(Table([[gmap1, gmap]]))
            self.doc.add(PageBreak())
        except:
            GWarning(
                "Cannot download metadata picture of extend provided by Google API. Please check internet connection."
            )

        ##################### Temporal ##################################
        self.doc.add_spacer(25)
        self.doc.add_header('Temporal reference', H1)
        self.textFactory(title="Temporal extend start",
                         name='Temporal extend start',
                         tag='identification')
        self.textFactory(title="Temporal extend end",
                         name='Temporal extend end',
                         tag='identification')

        ##################### Quality ##################################
        self.doc.add_spacer(25)
        self.doc.add_header('Quality a validity', H1)
        self.textFactory(title="Lineage", name='Lineage', tag='dataquality')

        #self.textFactory(title="Temporal extend start", name='Temporal extend start',tag='identification')
        # TODO md.identification.denominators

        ######################Conformity ########################
        self.doc.add_spacer(25)
        self.doc.add_header('Conformity', H1)
        head = ['Conformance date', "Conformance date type", 'Specification']
        self.tableFactory("Conformity", head, 'dataquality')
        ###################### Constraints ########################
        self.doc.add_spacer(25)
        self.doc.add_header('Constraints', H1)
        self.tableFactory("Condition applying to use", ["Use limitation"],
                          'identification')
        self.tableFactory("Condition applying to access",
                          ["Access constraints"], 'identification')
        self.tableFactory("Limitation on public access",
                          ["Other constraintrs"], 'identification')
        ###################### Responsible party ########################
        self.doc.add_spacer(25)
        self.doc.add_header('Responsible party', H1)
        header = ["Organization name", "E-mail", "Role"]
        self.tableFactory(
            "Organisations responsible for the establishment, management, maintenance and distribution of spatial data sets and services",
            header, 'identification')

        text = self.doc.render()
        # http://www.reportlab.com/docs/reportlab-userguide.pdf
        if save and self.pdf_file is not None:
            path = self.savePDF(text)
            return path

        return text
Exemplo n.º 10
0
    def __init__(self,
                 parent,
                 giface,
                 title=_("GRASS GIS Animation tool"),
                 rasters=None,
                 timeseries=None):
        wx.Frame.__init__(self,
                          parent,
                          title=title,
                          style=wx.DEFAULT_FRAME_STYLE,
                          size=(800, 600))
        self._giface = giface
        self.SetClientSize(self.GetSize())
        self.iconsize = (16, 16)

        self.SetIcon(
            wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_map.ico'),
                    wx.BITMAP_TYPE_ICO))

        # Make sure the temporal database exists
        try:
            tgis.init()
        except FatalError as e:
            GWarning(parent=self, message=str(e))

        # create temporal directory and ensure it's deleted after programs ends
        # (stored in MAPSET/.tmp/)
        global TMP_DIR
        TMP_DIR = gcore.tempdir()

        self.animations = [Animation() for i in range(MAX_COUNT)]
        self.windows = []
        self.animationPanel = AnimationsPanel(self,
                                              self.windows,
                                              initialCount=MAX_COUNT)
        bitmapPool = BitmapPool()
        mapFilesPool = MapFilesPool()

        self._progressDlg = None
        self._progressDlgMax = None

        self.provider = BitmapProvider(bitmapPool=bitmapPool,
                                       mapFilesPool=mapFilesPool,
                                       tempDir=TMP_DIR)
        self.animationSliders = {}
        self.animationSliders['nontemporal'] = SimpleAnimationSlider(self)
        self.animationSliders['temporal'] = TimeAnimationSlider(self)
        self.controller = AnimationController(frame=self,
                                              sliders=self.animationSliders,
                                              animations=self.animations,
                                              mapwindows=self.windows,
                                              provider=self.provider,
                                              bitmapPool=bitmapPool,
                                              mapFilesPool=mapFilesPool)
        for win in self.windows:
            win.Bind(wx.EVT_SIZE, self.FrameSizeChanged)
            self.provider.mapsLoaded.connect(lambda: self.SetStatusText(''))
            self.provider.renderingStarted.connect(self._showRenderingProgress)
            self.provider.renderingContinues.connect(self._updateProgress)
            self.provider.renderingFinished.connect(self._closeProgress)
            self.provider.compositionStarted.connect(
                self._showRenderingProgress)
            self.provider.compositionContinues.connect(self._updateProgress)
            self.provider.compositionFinished.connect(self._closeProgress)

        self.InitStatusbar()
        self._mgr = wx.aui.AuiManager(self)

        # toolbars
        self.toolbars = {}
        self._addToolbars()
        self._addPanes()
        self._mgr.Update()

        self.dialogs = dict()
        self.dialogs['speed'] = None
        self.dialogs['preferences'] = None

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
Exemplo n.º 11
0
    def OnRun(self, event):
        """Import/Link data (each layes as separate vector map)"""
        self.commandId = -1
        data = self.list.GetLayers()

        data = self._getLayersToReprojetion(2, 3)

        if data is None:
            return

        if not data:
            GMessage(_("No layers selected. Operation canceled."), parent=self)
            return

        if not self._validateOutputMapName():
            return

        dsn = self.dsnInput.GetDsn()
        ext = self.dsnInput.GetFormatExt()

        for layer, output, listId in data:
            userData = {}

            if self.dsnInput.GetType() == 'dir':
                idsn = os.path.join(dsn, layer)
            else:
                idsn = dsn

            # check number of bands
            nBandsStr = RunCommand('r.in.gdal',
                                   flags='p',
                                   input=idsn,
                                   read=True)
            nBands = -1
            if nBandsStr:
                try:
                    nBands = int(nBandsStr.rstrip('\n'))
                except:
                    pass
            if nBands < 0:
                GWarning(_("Unable to determine number of raster bands"),
                         parent=self)
                nBands = 1

            userData['nbands'] = nBands
            cmd = self.getSettingsPageCmd()
            cmd.append('input=%s' % idsn)
            cmd.append('output=%s' % output)

            if self.override.IsChecked():
                cmd.append('-o')

            if self.overwrite.IsChecked():
                cmd.append('--overwrite')

            if UserSettings.Get(group='cmd', key='overwrite',
                                subkey='enabled') and '--overwrite' not in cmd:
                cmd.append('--overwrite')

            # run in Layer Manager
            self._giface.RunCmd(cmd,
                                onDone=self.OnCmdDone,
                                userData=userData,
                                addLayer=False)
Exemplo n.º 12
0
    def _initTreeItems(self, locations=None, mapsets=None):
        """Add locations, mapsets and layers to the tree.
        Runs in multiple processes. Saves resulting data and error."""
        # mapsets param currently unused
        if not locations:
            locations = GetListOfLocations(self.gisdbase)

        loc_count = proc_count = 0
        queue_list = []
        proc_list = []
        loc_list = []
        nprocs = 4
        try:
            nprocs = cpu_count()
        except NotImplementedError:
            nprocs = 4

        results = dict()
        errors = []
        location_nodes = []
        nlocations = len(locations)
        grassdata_node = self._model.AppendNode(
            parent=self._model.root,
            label=_('GRASS locations ({})').format(self.gisdbase),
            data=dict(type='grassdata'))
        for location in locations:
            results[location] = dict()
            varloc = self._model.AppendNode(parent=grassdata_node,
                                            label=location,
                                            data=dict(type='location',
                                                      name=location))
            location_nodes.append(varloc)
            loc_count += 1

            Debug.msg(
                3, "Scanning location <{}> ({}/{})".format(
                    location, loc_count, nlocations))

            q = Queue()
            p = Process(target=getLocationTree,
                        args=(self.gisdbase, location, q))
            p.start()

            queue_list.append(q)
            proc_list.append(p)
            loc_list.append(location)

            proc_count += 1
            # Wait for all running processes
            if proc_count == nprocs or loc_count == nlocations:
                Debug.msg(4, "Process subresults")
                for i in range(len(loc_list)):
                    maps, error = queue_list[i].get()
                    proc_list[i].join()
                    if error:
                        errors.append(error)
                    for key in sorted(maps.keys()):
                        mapset_node = self._model.AppendNode(
                            parent=location_nodes[i],
                            label=key,
                            data=dict(type='mapset', name=key))
                        for elem in maps[key]:
                            if maps[key][elem]:
                                element_node = self._model.AppendNode(
                                    parent=mapset_node,
                                    label=elem,
                                    data=dict(type='element', name=elem))
                                for layer in maps[key][elem]:
                                    self._model.AppendNode(parent=element_node,
                                                           label=layer,
                                                           data=dict(
                                                               type=elem,
                                                               name=layer))

                proc_count = 0
                proc_list = []
                queue_list = []
                loc_list = []
                location_nodes = []

        if errors:
            GWarning('\n'.join(errors))
        Debug.msg(1, "Tree filled")
        self.RefreshItems()