Exemple #1
0
    def from_rast(self, raster_name):
        """Set the region from the computational region
        of a raster map layer.

        :param raster_name: the name of raster
        :type raster_name: str

        :param mapset: the mapset of raster
        :type mapset: str

        call C function `Rast_get_cellhd`

        Example ::

        >>> reg = Region()
        >>> reg.from_rast(test_raster_name)
        >>> reg.get_bbox()
        Bbox(50.0, 0.0, 60.0, 0.0)
        >>> reg.read()
        >>> reg.get_bbox()
        Bbox(40.0, 0.0, 40.0, 0.0)

        ..
        """
        if not raster_name:
            raise ValueError("Raster name or mapset are invalid")

        mapset = get_mapset_raster(raster_name)

        if mapset:
            libraster.Rast_get_cellhd(raster_name, mapset, self.byref())
Exemple #2
0
    def set_region_from_rast(self, rastname='', mapset=''):
        """Set the computational region from a map,
           if rastername and mapset is not specify, use itself.
           This region will be used by all
           raster map layers that are opened in the same process.

           The GRASS region settings will not be modified.

           call C function `Rast_get_cellhd`, `Rast_set_window`

           return: The region that was used to set the computational region

           """
        if self.is_open():
            fatal("You cannot change the region if map is open")
            raise
        region = Region()
        if rastname == '':
            rastname = self.name
        if mapset == '':
            mapset = self.mapset

        libraster.Rast_get_cellhd(rastname, mapset,
                                  region.byref())
        self._set_raster_window(region)
        return region
Exemple #3
0
    def set_from_rast(self, rastname='', mapset=''):
        """Set the region that will use from a map, if rastername and mapset
        is not specify, use itself.

        call C function `Rast_get_cellhd`"""
        if self.is_open():
            fatal("You cannot change the region if map is open")
            raise
        region = Region()
        if rastname == '':
            rastname = self.name
        if mapset == '':
            mapset = self.mapset

        libraster.Rast_get_cellhd(rastname, mapset,
                                  ctypes.byref(region._region))
        # update rows and cols attributes
        self._rows = libraster.Rast_window_rows()
        self._cols = libraster.Rast_window_cols()
Exemple #4
0
 def _get_raster_region(self):
     libraster.Rast_get_cellhd(self.name, self.mapset, self.c_region)
Exemple #5
0
    def __init__(self,
                 parent=None,
                 id=wx.ID_ANY,
                 title=_("Imagery - wx.class"),
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.DEFAULT_FRAME_STYLE,
                 toolbars=["map"],
                 tree=None,
                 notebook=None,
                 gismgr=None,
                 page=None,
                 Map=None,
                 auimgr=None):

        self._layerManager = gismgr
        self.Map = Map
        self.gismanager = gismgr  # GIS Manager object
        self.Map = Map  # instance of render.Map
        self.tree = tree  # GIS Manager layer tree object
        self.page = page  # Notebook page holding the layer tree
        self.layerbook = notebook  # GIS Manager layer tree notebook
        self.parent = parent
        #
        # available cursors
        #

        self.counter = 0
        # available cursors
        #
        self.cursors = {
            # default: cross
            # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
            "default": wx.StockCursor(wx.CURSOR_ARROW),
            "cross": wx.StockCursor(wx.CURSOR_CROSS),
            "hand": wx.StockCursor(wx.CURSOR_HAND),
            "pencil": wx.StockCursor(wx.CURSOR_PENCIL),
            "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
        }

        wx.Frame.__init__(self, parent, id, title, pos, size, style)
        self.SetName("MapWindow")

        #
        # set the size & system icon
        #
        self.SetClientSize(size)
        self.iconsize = (16, 16)

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

        #
        # Fancy gui
        #
        # self._mgr = auimgr
        self._mgr = wx.aui.AuiManager(self)

        #
        # Add toolbars
        #
        self.toolbars = {
            'map': None,
            'vdigit': None,
            'georect': None,
            'nviz': None
        }
        #  for toolb in toolbars:
        #            self.AddToolbar(toolb)

        #
        # Add statusbar
        #

        self.statusbar = self.CreateStatusBar(number=4, style=0)
        self.statusbar.SetStatusWidths([-5, -2, -1, -1])
        self.statusbarWin = dict()
        self.statusbarWin['toggle'] = wx.Choice(
            self.statusbar,
            wx.ID_ANY,
            choices=globalvar.MAP_DISPLAY_STATUSBAR_MODE)
        self.statusbarWin['toggle'].SetSelection(
            UserSettings.Get(group='display',
                             key='statusbarMode',
                             subkey='selection'))
        self.statusbar.Bind(wx.EVT_CHOICE, self.OnToggleStatus,
                            self.statusbarWin['toggle'])
        # auto-rendering checkbox
        self.statusbarWin['render'] = wx.CheckBox(parent=self.statusbar,
                                                  id=wx.ID_ANY,
                                                  label=_("Render"))
        self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleRender,
                            self.statusbarWin['render'])
        self.statusbarWin['render'].SetValue(
            UserSettings.Get(group='display',
                             key='autoRendering',
                             subkey='enabled'))
        self.statusbarWin['render'].SetToolTip(
            wx.ToolTip(_("Enable/disable auto-rendering")))
        # show region
        self.statusbarWin['region'] = wx.CheckBox(
            parent=self.statusbar,
            id=wx.ID_ANY,
            label=_("Show computational extent"))
        self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion,
                            self.statusbarWin['region'])

        self.statusbarWin['region'].SetValue(False)
        self.statusbarWin['region'].Hide()
        self.statusbarWin['region'].SetToolTip(
            wx.ToolTip(
                _("Show/hide computational "
                  "region extent (set with g.region). "
                  "Display region drawn as a blue box inside the "
                  "computational region, "
                  "computational region inside a display region "
                  "as a red box).")))
        # set resolution
        self.statusbarWin['resolution'] = wx.CheckBox(
            parent=self.statusbar,
            id=wx.ID_ANY,
            label=_("Constrain display resolution to computational settings"))
        self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleResolution,
                            self.statusbarWin['resolution'])
        self.statusbarWin['resolution'].SetValue(
            UserSettings.Get(group='display',
                             key='compResolution',
                             subkey='enabled'))
        self.statusbarWin['resolution'].Hide()
        self.statusbarWin['resolution'].SetToolTip(
            wx.ToolTip(
                _("Constrain display resolution "
                  "to computational region settings. "
                  "Default value for new map displays can "
                  "be set up in 'User GUI settings' dialog.")))
        # map scale
        self.statusbarWin['mapscale'] = wx.ComboBox(parent=self.statusbar,
                                                    id=wx.ID_ANY,
                                                    style=wx.TE_PROCESS_ENTER,
                                                    size=(150, -1))
        self.statusbarWin['mapscale'].SetItems([
            '1:1000', '1:5000', '1:10000', '1:25000', '1:50000', '1:100000',
            '1:1000000'
        ])
        self.statusbarWin['mapscale'].Hide()
        self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale,
                            self.statusbarWin['mapscale'])
        self.statusbar.Bind(wx.EVT_COMBOBOX, self.OnChangeMapScale,
                            self.statusbarWin['mapscale'])

        # go to
        self.statusbarWin['goto'] = wx.TextCtrl(parent=self.statusbar,
                                                id=wx.ID_ANY,
                                                value="",
                                                style=wx.TE_PROCESS_ENTER,
                                                size=(300, -1))
        self.statusbarWin['goto'].Hide()
        #self.statusbar.Bind(wx.EVT_TEXT_ENTER, MapFrame.OnGoTo, self.statusbarWin['goto'])

        # projection
        self.statusbarWin['projection'] = wx.CheckBox(
            parent=self.statusbar,
            id=wx.ID_ANY,
            label=_("Use defined projection"))
        self.statusbarWin['projection'].SetValue(False)
        size = self.statusbarWin['projection'].GetSize()
        self.statusbarWin['projection'].SetMinSize((size[0] + 150, size[1]))
        self.statusbarWin['projection'].SetToolTip(
            wx.ToolTip(
                _("Reproject coordinates displayed "
                  "in the statusbar. Projection can be "
                  "defined in GUI preferences dialog "
                  "(tab 'Display')")))
        self.statusbarWin['projection'].Hide()

        # mask
        self.statusbarWin['mask'] = wx.StaticText(parent=self.statusbar,
                                                  id=wx.ID_ANY,
                                                  label='')
        self.statusbarWin['mask'].SetForegroundColour(wx.Colour(255, 0, 0))

        # on-render gauge
        self.statusbarWin['progress'] = wx.Gauge(parent=self.statusbar,
                                                 id=wx.ID_ANY,
                                                 range=0,
                                                 style=wx.GA_HORIZONTAL)
        self.statusbarWin['progress'].Hide()
        self.StatusbarReposition()  # reposition statusbar

        #
        # Init map display (buffered DC & set default cursor)
        #
        self.MapWindow2D = BufferedWindow2(self,
                                           id=wx.ID_ANY,
                                           Map=self.Map,
                                           tree=self.tree,
                                           lmgr=self.gismanager)
        # default is 2D display mode
        self.MapWindow = self.MapWindow2D
        #self.MapWindow.Bind(wx.EVT_MOTION, BufferedWindow2.OnMotion)
        self.MapWindow.SetCursor(self.cursors["default"])
        # used by Nviz (3D display mode)
        self.MapWindow3D = None

        self.MapWindow.Bind(wx.EVT_LEFT_DCLICK, self.OnButtonDClick)
        self.MapWindow.Bind(wx.EVT_RIGHT_DCLICK, self.RDClick)

        #
        # initialize region values
        #
        self.width, self.height = self.GetClientSize()
        self.Map.ChangeMapSize(self.GetClientSize())
        self.Map.region = self.Map.GetRegion()

        #
        # Bind various events
        #
        #self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        #self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)

        #
        # Update fancy gui style
        #
        self._mgr.AddPane(
            self.MapWindow,
            wx.aui.AuiPaneInfo().CentrePane().Dockable(False).BestSize(
                (-1, -1)).CloseButton(False).DestroyOnClose(True).Layer(0))
        self._mgr.Update()

        #
        # Init print module and classes
        #
        #self.printopt = disp_print.PrintOptions(self, self.MapWindow)

        #
        # Initialization of digitization tool
        #
        self.digit = None

        #
        # Init zoom history
        #

        #
        # Re-use dialogs
        #
        self.dialogs = {}
        self.dialogs['attributes'] = None
        self.dialogs['category'] = None
        self.dialogs['barscale'] = None
        self.dialogs['legend'] = None

        self.decorationDialog = None  # decoration/overlays

        #
        # Re-use dialogs
        #
        self.coords = []
        self.coor = []
        self.mapname = 'lsat7_2000_10@' + grass1.gisenv()['MAPSET']
        self.cmd = ['d.rast', str("map=" + self.mapname)]
        self.Map.AddLayer(type='raster', name=self.mapname, command=self.cmd)
        self.MapWindow.UpdateMap(render=True)

        self.dialogs = {}
        self.dialogs['attributes'] = None
        self.dialogs['category'] = None
        self.dialogs['barscale'] = None
        self.dialogs['legend'] = None

        self.decorationDialog = None  # decoration/overlays

        #self.Maximize()

        self.X = []
        self.Y = []
        self.tempX = []
        self.tempY = []

        self.npoints = 0

        self.VX = []
        self.VY = []
        self.perimeter_npoints = 0
        self.perimeterX = []
        self.perimeterY = []
        self.Region_perimeter = []

        # initialize

        self.data_type = []
        self.inrast = []
        self.infd = []
        self.Band_sum = []
        self.Bandbuf = []
        self.Band_histo = []
        self.Band_Product = []
        self.Band_min = []
        self.Band_max = []
        self.np = 0

        # find map in search path

        self.name = [
            'lsat7_2000_10', 'lsat7_2000_20', 'lsat7_2000_30', 'lsat7_2000_40',
            'lsat7_2000_50', 'lsat7_2000_70'
        ]
        # determine the inputmap type (CELL/FCELL/DCELL) */
        #   for n in range(0,6):
        #      self.data_type = grass.G_raster_map_type(name[n], mapset)
        #     self.infd.append( grass.G_open_cell_old(name[n], mapset))

        # determine the inputmap type (CELL/FCELL/DCELL) */
        self.mapset = 'landsat'
        self.mapset = c_char_p(self.mapset).value

        self.open_band_files()

        self.vnrows = 0
        self.vncols = 0
        self.hnrows = 0
        self.hncols = 0
        self.htop = self.hbottom = self.hleft = self.hright = 0
        self.view()
        self.viewhistogram()

        self.cellhd = grasslib.Cell_head()

        if (raster.Rast_get_cellhd('lsat7_2000_10', self.mapset,
                                   byref(self.cellhd))) == 0:
            print "error1"
#9400694566

        self.Band_cellhd = self.cellhd
        self.dst = self.adjust_window_to_box(self.cellhd, self.vnrows,
                                             self.vncols)
        self.vcleft = self.vleft + (self.vncols - self.dst.cols) / 2
        self.vcright = self.vcleft + self.dst.cols - 1
        self.vctop = self.vtop + (self.vnrows - self.dst.rows) / 2
        self.vcbottom = self.vctop + self.dst.rows - 1
        self.vc_ns_res = self.cellhd.ns_res
        self.vc_ew_res = self.cellhd.ew_res

        for b in xrange(6):
            self.Band_sum.append(0.0)
            self.Band_histo.append([])
            for b2 in xrange(256):
                self.Band_Product.append([])
                self.Band_histo[b].append(0.0)
            for b2 in xrange(255):
                self.Band_Product[b].append(0)
Exemple #6
0
def _read_raster_info(name, mapset):
    """Read the raster map info from the file system and store the content
       into a dictionary

       This method uses the ctypes interface to the gis and raster libraries
       to read the map metadata information

       :param name: The name of the map
       :param mapset: The mapset of the map
       :returns: The key value pairs of the map specific metadata, or None in
                 case of an error
    """

    kvp = {}

    if not libgis.G_find_raster(name, mapset):
        return None

    # Read the region information
    region = libgis.Cell_head()
    libraster.Rast_get_cellhd(name, mapset, byref(region))

    kvp["north"] = region.north
    kvp["south"] = region.south
    kvp["east"] = region.east
    kvp["west"] = region.west
    kvp["nsres"] = region.ns_res
    kvp["ewres"] = region.ew_res
    kvp["rows"] = region.cols
    kvp["cols"] = region.rows

    maptype = libraster.Rast_map_type(name, mapset)

    if maptype == libraster.DCELL_TYPE:
        kvp["datatype"] = "DCELL"
    elif maptype == libraster.FCELL_TYPE:
        kvp["datatype"] = "FCELL"
    elif maptype == libraster.CELL_TYPE:
        kvp["datatype"] = "CELL"

    # Read range
    if libraster.Rast_map_is_fp(name, mapset):
        range = libraster.FPRange()
        libraster.Rast_init_fp_range(byref(range))
        ret = libraster.Rast_read_fp_range(name, mapset, byref(range))
        if ret < 0:
            logging.error(_("Unable to read range file"))
            return None
        if ret == 2:
            kvp["min"] = None
            kvp["max"] = None
        else:
            min = libgis.DCELL()
            max = libgis.DCELL()
            libraster.Rast_get_fp_range_min_max(byref(range), byref(min),
                                                byref(max))
            kvp["min"] = min.value
            kvp["max"] = max.value
    else:
        range = libraster.Range()
        libraster.Rast_init_range(byref(range))
        ret = libraster.Rast_read_range(name, mapset, byref(range))
        if ret < 0:
            logging.error(_("Unable to read range file"))
            return None
        if ret == 2:
            kvp["min"] = None
            kvp["max"] = None
        else:
            min = libgis.CELL()
            max = libgis.CELL()
            libraster.Rast_get_range_min_max(byref(range), byref(min),
                                             byref(max))
            kvp["min"] = min.value
            kvp["max"] = max.value

    return kvp