Example #1
0
def main():
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from dbmgr.manager import AttributeManager

    mapName = gscript.find_file(options["map"], element="vector")["fullname"]
    if not mapName:
        gscript.set_raise_on_error(False)
        gscript.fatal(_("Vector map <%s> not found") % options["map"])

    app = wx.App()
    gscript.message(
        _("Loading attribute data for vector map <%s>...") % mapName)
    f = AttributeManager(
        parent=None,
        id=wx.ID_ANY,
        base_title=_("Attribute Table Manager - GRASS GIS"),
        size=(900, 600),
        vectorName=mapName,
    )
    f.Show()

    app.MainLoop()
Example #2
0
def main():
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.utils import _
    from dbmgr.manager import AttributeManager

    mapName = gscript.find_file(options['map'], element='vector')['fullname']
    if not mapName:
        gscript.set_raise_on_error(False)
        gscript.fatal(_("Vector map <%s> not found") % options['map'])

    app = wx.App()
    gscript.message(
        _("Loading attribute data for vector map <%s>...") % mapName)
    f = AttributeManager(parent=None,
                         id=wx.ID_ANY,
                         title="%s - <%s>" %
                         (_("GRASS GIS Attribute Table Manager"), mapName),
                         size=(900, 600),
                         vectorName=mapName)
    f.Show()

    app.MainLoop()
Example #3
0
def main():
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()
    
    from core.utils import _
    from dbmgr.manager import AttributeManager

    mapName = gscript.find_file(options['map'], element='vector')['fullname']
    if not mapName:
        gscript.set_raise_on_error(False)
        gscript.fatal(_("Vector map <%s> not found") % options['map'])

    app = wx.App()
    gscript.message(_("Loading attribute data for vector map <%s>...") % mapName)
    f = AttributeManager(parent=None, id=wx.ID_ANY,
                         title="%s - <%s>" % (_("GRASS GIS Attribute Table Manager"),
                                              mapName),
                         size=(900, 600), vectorName=mapName)
    f.Show()

    app.MainLoop()
def main():
    grass.set_raise_on_error(False)

    options, flags = grass.parser()

    app = MyApp(0)  # Create an instance of the application class
    app.MainLoop()  # Tell it to start processing events
Example #5
0
def _set_notebook_defaults():
    """
    This function sets several GRASS environment variables that are
    important for GRASS to run smoothly in Jupyter.

    It also allows GRASS to overwrite existing maps of the same name.
    """
    # We want functions to raise exceptions and see standard output of
    # the modules in the notebook.
    gs.set_raise_on_error(True)
    gs.set_capture_stderr(True)

    # Allow overwrite of existing maps
    os.environ["GRASS_OVERWRITE"] = "1"
Example #6
0
def main():
    mapName = grass.find_file(options['map'], element = 'vector')['fullname']
    if not mapName:
        grass.set_raise_on_error(False)
        grass.fatal(_("Vector map <%s> not found") % options['map'])
    
    app = wx.App()
    grass.message(_("Loading attribute data for vector map <%s>...") % mapName)
    f = AttributeManager(parent = None, id = wx.ID_ANY,
                         title = "%s - <%s>" % (_("GRASS GIS Attribute Table Manager"),
                                                mapName),
                         size = (900, 600), vectorName = mapName)
    f.Show()
    
    app.MainLoop()
Example #7
0
def main():
    mapName = grass.find_file(options['map'], element='vector')['fullname']
    if not mapName:
        grass.set_raise_on_error(False)
        grass.fatal(_("Vector map <%s> not found") % options['map'])

    app = wx.App()
    grass.message(_("Loading attribute data for vector map <%s>...") % mapName)
    f = AttributeManager(parent=None,
                         id=wx.ID_ANY,
                         title="%s - <%s>" %
                         (_("GRASS GIS Attribute Table Manager"), mapName),
                         size=(900, 600),
                         vectorName=mapName)
    f.Show()

    app.MainLoop()
def initialize_GRASS_notebook(binary, grassdata, location, mapset):

    # create GRASS GIS runtime environment
    gisbase = subprocess.check_output([binary, "--config", "path"], universal_newlines=True).strip()
    os.environ['GISBASE'] = gisbase
    sys.path.append(os.path.join(gisbase, "etc", "python"))

    # do GRASS GIS imports
    import grass.script as gs
    import grass.script.setup as gsetup

    # set GRASS GIS session data
    rcfile = gsetup.init(gisbase, grassdata, location, mapset)
    # default font displays
    os.environ['GRASS_FONT'] = 'sans'
    # overwrite existing maps
    os.environ['GRASS_OVERWRITE'] = '1'
    gs.set_raise_on_error(True)
    gs.set_capture_stderr(True)
    # set display modules to render into a file (named map.png by default)
    os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
    os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE'
    os.environ['GRASS_LEGEND_FILE'] = 'legend.txt'
Example #9
0
from core.gcmd import RunCommand

from animation.mapwindow import AnimationWindow
from animation.provider import BitmapProvider, BitmapPool, \
    MapFilesPool, CleanUp
from animation.controller import AnimationController
from animation.anim import Animation
from animation.toolbars import MainToolbar, AnimationToolbar, MiscToolbar
from animation.dialogs import SpeedDialog, PreferencesDialog
from animation.utils import Orientation, ReplayMode, TemporalType


MAX_COUNT = 4
TMP_DIR = None

gcore.set_raise_on_error(True)


class AnimationFrame(wx.Frame):

    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(
Example #10
0
    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()

    # show main frame
    giface = StandaloneGrassInterface()
    frame = IClassMapFrame(parent=None, giface=giface)
    if not flags["m"]:
        frame.CenterOnScreen()
    if group_name:
        frame.SetGroup(group_name, subgroup_name)
    if map_name:
        giface.WriteLog(_("Loading raster map <%s>...") % map_name)
        frame.trainingMapManager.AddLayer(map_name)
    if trainingmap_name:
        giface.WriteLog(_("Loading training map <%s>...") % trainingmap_name)
        frame.ImportAreas(trainingmap_name)

    frame.Show()
    if flags["m"]:
        frame.Maximize()

    app.MainLoop()


if __name__ == "__main__":
    grass.set_raise_on_error(False)
    options, flags = grass.parser()

    GuiModuleMain(main)
Example #11
0
#%option G_OPT_STDS_INPUTS
#%end

#%option G_OPT_STDS_OUTPUT
#%end

#%option G_OPT_STDS_TYPE
#% guidependency: inputs
#% guisection: Required
#%end

import grass.temporal as tgis
import grass.script as grass

############################################################################
grass.set_raise_on_error(True)

def main():

    # Get the options
    inputs = options["inputs"]
    output = options["output"]
    type = options["type"]

    # Make sure the temporal database exists
    tgis.init()

    #Get the current mapset to create the id of the space time dataset
    mapset = grass.gisenv()["MAPSET"]

    inputs_split = inputs.split(",")
Example #12
0
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()
    frame = VDigitMapFrame(options['map'])
    frame.Show()

    app.MainLoop()


if __name__ == "__main__":
    grass.set_raise_on_error(False)

    options, flags = grass.parser()

    if not haveVDigit:
        grass.fatal(_("Vector digitizer not available. %s") % errorMsg)

    if not grass.find_file(name=options['map'],
                           element='vector',
                           mapset=grass.gisenv()['MAPSET'])['fullname']:
        if not flags['c']:
            grass.fatal(
                _("Vector map <%s> not found in current mapset. "
                  "New vector map can be created by providing '-c' flag.") %
                options['map'])
        else:
Example #13
0
def main():
    grass.set_raise_on_error(False)

    options, flags = grass.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.render import Map
    from core.globalvar import ICONDIR
    from mapdisp.frame import MapPanel
    from gui_core.mapdisp import FrameMixin
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings
    from vdigit.main import haveVDigit, errorMsg
    from grass.exceptions import CalledModuleError

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class VDigitMapDisplay(FrameMixin, MapPanel):
        """Map display for wrapping map panel with v.digit mathods and frame methods"""
        def __init__(self, parent, vectorMap):
            MapPanel.__init__(self,
                              parent=parent,
                              Map=Map(),
                              giface=DMonGrassInterface(None))

            # set system icon
            parent.SetIcon(
                wx.Icon(os.path.join(ICONDIR, "grass_map.ico"),
                        wx.BITMAP_TYPE_ICO))

            # bindings
            parent.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

            # extend shortcuts and create frame accelerator table
            self.shortcuts_table.append(
                (self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11))
            self._initShortcuts()

            # this giface issue not solved yet, we must set mapframe aferwards
            self._giface._mapframe = self
            # load vector map
            mapLayer = self.GetMap().AddLayer(
                ltype="vector",
                name=vectorMap,
                command=["d.vect", "map=%s" % vectorMap],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True,
            )

            # switch toolbar
            self.AddToolbar("vdigit", fixed=True)

            # start editing
            self.toolbars["vdigit"].StartEditing(mapLayer)
            # use Close instead of QuitVDigit for standalone tool
            self.toolbars["vdigit"].quitDigitizer.disconnect(self.QuitVDigit)
            self.toolbars["vdigit"].quitDigitizer.connect(lambda: self.Close())

            # add Map Display panel to Map Display frame
            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(self, proportion=1, flag=wx.EXPAND)
            parent.SetSizer(sizer)
            parent.Layout()

    if not haveVDigit:
        grass.fatal(_("Vector digitizer not available. %s") % errorMsg)

    if not grass.find_file(name=options["map"],
                           element="vector",
                           mapset=grass.gisenv()["MAPSET"])["fullname"]:
        if not flags["c"]:
            grass.fatal(
                _("Vector map <%s> not found in current mapset. "
                  "New vector map can be created by providing '-c' flag.") %
                options["map"])
        else:
            grass.verbose(_("New vector map <%s> created") % options["map"])
            try:
                grass.run_command("v.edit",
                                  map=options["map"],
                                  tool="create",
                                  quiet=True)
            except CalledModuleError:
                grass.fatal(
                    _("Unable to create new vector map <%s>") % options["map"])

    # allow immediate rendering
    driver = UserSettings.Get(group="display", key="driver", subkey="type")
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    app = wx.App()
    frame = wx.Frame(
        None,
        id=wx.ID_ANY,
        size=(850, 600),
        style=wx.DEFAULT_FRAME_STYLE,
        title=_("Vector Digitizer - GRASS GIS"),
    )
    frame = VDigitMapDisplay(parent=frame, vectorMap=options["map"])
    frame.Show()

    app.MainLoop()
Example #14
0
def main():
    gs.set_raise_on_error(False)

    options, flags = gs.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.render import Map
    from mapdisp.frame import MapFrame
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings
    from grass.exceptions import CalledModuleError

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class RDigitMapFrame(MapFrame):
        def __init__(
            self,
            new_map=None,
            base_map=None,
            edit_map=None,
            map_type=None,
        ):
            MapFrame.__init__(
                self,
                parent=None,
                Map=Map(),
                giface=DMonGrassInterface(None),
                title=_("GRASS GIS Raster Digitizer"),
                size=(850, 600),
            )
            # this giface issue not solved yet, we must set mapframe aferwards
            self._giface._mapframe = self
            self._giface.mapCreated.connect(self.OnMapCreated)
            self._mapObj = self.GetMap()

            # load raster map
            self._addLayer(name=new_map if new_map else edit_map)

            # switch toolbar
            self.AddToolbar('rdigit', fixed=True)

            rdigit = self.toolbars['rdigit']
            if new_map:
                rdigit._mapSelectionCombo.Unbind(wx.EVT_COMBOBOX)
                self.rdigit.SelectNewMap(
                    standalone=True,
                    mapName=new_map,
                    bgMap=base_map,
                    mapType=map_type,
                )
                rdigit._mapSelectionCombo.Bind(
                    wx.EVT_COMBOBOX,
                    rdigit.OnMapSelection,
                )
            else:
                rdigit._mapSelectionCombo.SetSelection(n=1)
                rdigit.OnMapSelection()

        def _addLayer(self, name, ltype='raster'):
            """Add layer into map

            :param str name: map name
            :param str ltype: layer type
            """
            mapLayer = self._mapObj.AddLayer(
                ltype=ltype,
                name=name,
                command=['d.rast', "map={}".format(name)],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True,
            )

        def OnMapCreated(self, name, ltype):
            """Add new created raster layer into map

            :param str name: map name
            :param str ltype: layer type
            """
            self._mapObj.Clean()
            self._addLayer(name=name, ltype=ltype)
            self.GetMapWindow().UpdateMap()

    kwargs = {
        'new_map': options['create'],
        'base_map': options['base'],
        'edit_map': options['edit'],
        'map_type': options['type'],
    }

    mapset = gs.gisenv()['MAPSET']

    if kwargs['edit_map']:
        edit_map = gs.find_file(
            name=kwargs['edit_map'],
            element='raster',
            mapset=mapset,
        )['fullname']

        if not edit_map:
            gs.fatal(
                _(
                    "Raster map <{}> not found in current mapset.".format(
                        options['edit'], ), ), )
        else:
            kwargs['edit_map'] = edit_map
    else:
        if kwargs['base_map']:
            base_map = gs.find_file(
                name=kwargs['base_map'],
                element='raster',
                mapset=mapset,
            )['fullname']
            if not base_map:
                gs.fatal(
                    _(
                        "Base raster map <{}> not found in "
                        "current mapset.".format(options['base'], ), ), )
            kwargs['base_map'] = base_map

    # allow immediate rendering
    driver = UserSettings.Get(
        group='display',
        key='driver',
        subkey='type',
    )
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

    app = wx.App()
    frame = RDigitMapFrame(**kwargs)
    frame.Show()

    app.MainLoop()
Example #15
0
def main():
    # Get the options
    input = options["input"]
    start = options["start"]
    stop = options["stop"]
    base = options["basename"]
    cycle = options["cycle"]
    offset = options["offset"]
    minimum = options["minimum"]
    maximum = options["maximum"]
    occurrence = options["occurrence"]
    range = options["range"]
    indicator = options["indicator"]
    staend = options["staend"]
    register_null = flags["n"]
    reverse = flags["r"]

    grass.set_raise_on_error(True)

    # Make sure the temporal database exists
    tgis.init()
    # We need a database interface
    dbif = tgis.SQLDatabaseInterfaceConnection()
    dbif.connect()

    mapset = tgis.get_current_mapset()

    if input.find("@") >= 0:
        id = input
    else:
        id = input + "@" + mapset

    input_strds = tgis.SpaceTimeRasterDataset(id)

    if input_strds.is_in_db() == False:
        dbif.close()
        grass.fatal(_("Space time %s dataset <%s> not found") % (
            input_strds.get_output_map_instance(None).get_type(), id))

    input_strds.select(dbif)
    dummy = input_strds.get_new_map_instance(None)

    # The occurrence space time raster dataset
    if occurrence:
        if not minimum or not maximum:
            if not range:
                dbif.close()
                grass.fatal(_("You need to set the range to compute the occurrence"
                              " space time raster dataset"))

        if occurrence.find("@") >= 0:
            occurrence_id = occurrence
        else:
            occurrence_id = occurrence + "@" + mapset

        occurrence_strds = tgis.SpaceTimeRasterDataset(occurrence_id)
        if occurrence_strds.is_in_db(dbif):
            if not grass.overwrite():
                dbif.close()
                grass.fatal(_("Space time raster dataset <%s> is already in the "
                              "database, use overwrite flag to overwrite") % occurrence_id)

    # The indicator space time raster dataset
    if indicator:
        if not occurrence:
            dbif.close()
            grass.fatal(_("You need to set the occurrence to compute the indicator"
                          " space time raster dataset"))
        if not staend:
            dbif.close()
            grass.fatal(_("You need to set the staend options to compute the indicator"
                          " space time raster dataset"))
        if indicator.find("@") >= 0:
            indicator = indicator
        else:
            indicator_id = indicator + "@" + mapset

        indicator_strds = tgis.SpaceTimeRasterDataset(indicator_id)
        if indicator_strds.is_in_db(dbif):
            if not grass.overwrite():
                dbif.close()
                grass.fatal(_("Space time raster dataset <%s> is already in the "
                              "database, use overwrite flag to overwrite") % indicator_id)
        staend = staend.split(",")
        indicator_start = int(staend[0])
        indicator_mid = int(staend[1])
        indicator_end = int(staend[2])

    # The minimum threshold space time raster dataset
    minimum_strds = None
    if minimum:
        if minimum.find("@") >= 0:
            minimum_id = minimum
        else:
            minimum_id = minimum + "@" + mapset

        minimum_strds = tgis.SpaceTimeRasterDataset(minimum_id)
        if minimum_strds.is_in_db() == False:
            dbif.close()
            grass.fatal(_("Space time raster dataset <%s> not found") % (minimum_strds.get_id()))

        if minimum_strds.get_temporal_type() != input_strds.get_temporal_type():
            dbif.close()
            grass.fatal(_("Temporal type of input strds and minimum strds must be equal"))

        minimum_strds.select(dbif)

    # The maximum threshold space time raster dataset
    maximum_strds = None
    if maximum:
        if maximum.find("@") >= 0:
            maximum_id = maximum
        else:
            maximum_id = maximum + "@" + mapset

        maximum_strds = tgis.SpaceTimeRasterDataset(maximum_id)
        if maximum_strds.is_in_db() == False:
            dbif.close()
            grass.fatal(_("Space time raster dataset <%s> not found") % (maximum_strds.get_id()))

        if maximum_strds.get_temporal_type() != input_strds.get_temporal_type():
            dbif.close()
            grass.fatal(_("Temporal type of input strds and maximum strds must be equal"))

        maximum_strds.select(dbif)

    input_strds_start, input_strds_end = input_strds.get_temporal_extent_as_tuple()

    if input_strds.is_time_absolute():
        start = tgis.string_to_datetime(start)
        if stop:
            stop = tgis.string_to_datetime(stop)
        else:
            stop = input_strds_end
    else:
        start = int(start)
        if stop:
            stop = int(stop)
        else:
            stop = input_strds_end

    if input_strds.is_time_absolute():
        end = tgis.increment_datetime_by_string(start, cycle)
    else:
        end = start + cycle

    count = 1
    indi_count = 1
    occurrence_maps = {}
    indicator_maps = {}

    while input_strds_end > start and stop > start:

        # Make sure that the cyclic computation will stop at the correct time
        if stop and end > stop:
            end = stop

        where = "start_time >= \'%s\' AND start_time < \'%s\'"%(str(start),
                                                                str(end))
        input_maps = input_strds.get_registered_maps_as_objects(where=where,
                                                                dbif=dbif)

        print len(input_maps)

        input_topo = tgis.SpatioTemporalTopologyBuilder()
        input_topo.build(input_maps, input_maps)

        if len(input_maps) == 0:
            continue

        grass.message(_("Processing cycle %s - %s"%(str(start), str(end))))

        count = compute_occurrence(occurrence_maps, input_strds, input_maps,
                                   start, base, count, mapset, where, reverse,
                                   range, minimum_strds, maximum_strds, dbif)

        # Indicator computation is based on the occurrence so we need to start it after
        # the occurrence cycle
        if indicator:
            num_maps = len(input_maps)
            for i in xrange(num_maps):
                if reverse:
                    map = input_maps[num_maps - i - 1]
                else:
                    map = input_maps[i]

                indicator_map_name = "%s_indicator_%i" % (base, indi_count)
                indicator_map_id = dummy.build_id(indicator_map_name, mapset)
                indicator_map = input_strds.get_new_map_instance(indicator_map_id)

                # Check if new map is in the temporal database
                if indicator_map.is_in_db(dbif):
                    if grass.overwrite():
                        # Remove the existing temporal database entry
                        indicator_map.delete(dbif)
                        indicator_map = input_strds.get_new_map_instance(indicator_map_id)
                    else:
                        grass.fatal(_("Map <%s> is already registered in the temporal"
                                     " database, use overwrite flag to overwrite.") %
                                    (indicator_map.get_map_id()))

                curr_map = occurrence_maps[map.get_id()].get_name()

                # Reverse time
                if reverse:
                    if i ==  0:
                        prev_map = curr_map
                        subexpr1 = "null()"
                        subexpr3 = "%i"%(indicator_start)
                    elif i > 0 and i < num_maps - 1:
                        prev_map = occurrence_maps[map.next().get_id()].get_name()
                        next_map = occurrence_maps[map.prev().get_id()].get_name()
                        # In case the previous map is null() set null() or the start indicator
                        subexpr1 = "if(isnull(%s), null(), %i)"%(curr_map, indicator_start)
                        # In case the previous map was not null() if the current map is null() set null()
                        # if the current map is not null() and the next map is not null() set
                        # intermediate indicator, if the next map is null set the end indicator
                        subexpr2 = "if(isnull(%s), %i, %i)"%(next_map, indicator_end, indicator_mid)
                        subexpr3 = "if(isnull(%s), null(), %s)"%(curr_map, subexpr2)
                        expression = "%s = if(isnull(%s), %s, %s)"%(indicator_map_name,
                                                                    prev_map, subexpr1,
                                                                    subexpr3)
                    else:
                        prev_map = occurrence_maps[map.next().get_id()].get_name()
                        subexpr1 = "if(isnull(%s), null(), %i)"%(curr_map, indicator_start)
                        subexpr3 = "if(isnull(%s), null(), %i)"%(curr_map, indicator_mid)
                else:
                    if i == 0:
                        prev_map = curr_map
                        subexpr1 = "null()"
                        subexpr3 = "%i"%(indicator_start)
                    elif i > 0 and i < num_maps - 1:
                        prev_map = occurrence_maps[map.prev().get_id()].get_name()
                        next_map = occurrence_maps[map.next().get_id()].get_name()
                        # In case the previous map is null() set null() or the start indicator
                        subexpr1 = "if(isnull(%s), null(), %i)"%(curr_map, indicator_start)
                        # In case the previous map was not null() if the current map is null() set null()
                        # if the current map is not null() and the next map is not null() set
                        # intermediate indicator, if the next map is null set the end indicator
                        subexpr2 = "if(isnull(%s), %i, %i)"%(next_map, indicator_end, indicator_mid)
                        subexpr3 = "if(isnull(%s), null(), %s)"%(curr_map, subexpr2)
                        expression = "%s = if(isnull(%s), %s, %s)"%(indicator_map_name,
                                                                    prev_map, subexpr1,
                                                                    subexpr3)
                    else:
                        prev_map = occurrence_maps[map.prev().get_id()].get_name()
                        subexpr1 = "if(isnull(%s), null(), %i)"%(curr_map, indicator_start)
                        subexpr3 = "if(isnull(%s), null(), %i)"%(curr_map, indicator_mid)

                expression = "%s = if(isnull(%s), %s, %s)"%(indicator_map_name,
                                                            prev_map, subexpr1,
                                                            subexpr3)
                print expression
                grass.mapcalc(expression, overwrite=True)

                map_start, map_end = map.get_temporal_extent_as_tuple()

                if map.is_time_absolute():
                    indicator_map.set_absolute_time(map_start, map_end)
                else:
                    indicator_map.set_relative_time(map_start, map_end,
                                                 map.get_relative_time_unit())

                indicator_maps[map.get_id()] = indicator_map
                indi_count += 1

        # Increment the cycle
        start = end
        if input_strds.is_time_absolute():
            start = end
            if offset:
                start = tgis.increment_datetime_by_string(end, offset)
            end = tgis.increment_datetime_by_string(start, cycle)
        else:
            if offset:
                start = end + offset
            end = start + cycle

    empty_maps = []

    create_strds_register_maps(input_strds, occurrence_strds, occurrence_maps,
                               register_null, empty_maps, dbif)

    if indicator:
        create_strds_register_maps(input_strds, indicator_strds, indicator_maps,
                                   register_null, empty_maps, dbif)

    dbif.close()

    # Remove empty maps
    if len(empty_maps) > 0:
        for map in empty_maps:
            grass.run_command("g.remove", flags='f', type="rast",  pattern=map.get_name(), quiet=True)
Example #16
0
#%option G_OPT_STDS_INPUTS
#%end

#%option G_OPT_STDS_OUTPUT
#%end

#%option G_OPT_STDS_TYPE
#% guidependency: inputs
#% guisection: Required
#%end

import grass.script as grass


############################################################################
grass.set_raise_on_error(True)

def main():
    # lazy imports
    import grass.temporal as tgis

    # Get the options
    inputs = options["inputs"]
    output = options["output"]
    type = options["type"]

    # Make sure the temporal database exists
    tgis.init()

    #Get the current mapset to create the id of the space time dataset
    mapset = grass.gisenv()["MAPSET"]
Example #17
0
os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE'
os.environ['GRASS_LEGEND_FILE'] = 'legend.txt'

# import GRASS GIS
import grass.script as gs
import grass.script.setup as gsetup
from grass.script import core as grass

# for pygrass
from grass.pygrass.modules.shortcuts import raster as r, vector as v, general as g, display as d

from subprocess import PIPE

# further setup for GRASS GIS
gs.set_raise_on_error(True)
#gs.set_capture_stderr(True)  #might be Python 2 vs 3 issue

## set default encoding
#import sys
#reload(sys)
#sys.setdefaultencoding('utf-8')


class Basemap():
    """prepares a set of basemaps for project layout"""
    def __init__(self, project):
        self.project = project

        #define project dir
        project_dir = project_basedir + project + '/'
Example #18
0
def import_stds(input,
                output,
                directory,
                title=None,
                descr=None,
                location=None,
                link=False,
                exp=False,
                overr=False,
                create=False,
                stds_type="strds",
                base=None,
                set_current_region=False,
                memory=300):
    """Import space time datasets of type raster and vector

        :param input: Name of the input archive file
        :param output: The name of the output space time dataset
        :param directory: The extraction directory
        :param title: The title of the new created space time dataset
        :param descr: The description of the new created
                     space time dataset
        :param location: The name of the location that should be created,
                        maps are imported into this location
        :param link: Switch to link raster maps instead importing them
        :param exp: Extend location extents based on new dataset
        :param overr: Override projection (use location's projection)
        :param create: Create the location specified by the "location"
                      parameter and exit.
                      Do not import the space time datasets.
        :param stds_type: The type of the space time dataset that
                         should be imported
        :param base: The base name of the new imported maps, it will be
                     extended using a numerical index.
        :param memory: Cache size for raster rows, used in r.in.gdal
    """

    global raise_on_error
    old_state = gscript.raise_on_error
    gscript.set_raise_on_error(True)

    # Check if input file and extraction directory exits
    if not os.path.exists(input):
        gscript.fatal(
            _("Space time raster dataset archive <%s> not found") % input)
    if not create and not os.path.exists(directory):
        gscript.fatal(_("Extraction directory <%s> not found") % directory)

    tar = tarfile.open(name=input, mode='r')

    # Check for important files
    msgr = get_tgis_message_interface()
    msgr.message(
        _("Checking validity of input file (size: %0.1f MB). Make take a while..."
          % (os.path.getsize(input) / (1024 * 1024.0))))
    members = tar.getnames()
    # Make sure that the basenames of the files are used for comparison
    member_basenames = [os.path.basename(name) for name in members]

    if init_file_name not in member_basenames:
        gscript.fatal(_("Unable to find init file <%s>") % init_file_name)
    if list_file_name not in member_basenames:
        gscript.fatal(_("Unable to find list file <%s>") % list_file_name)
    if proj_file_name not in member_basenames:
        gscript.fatal(
            _("Unable to find projection file <%s>") % proj_file_name)

    msgr.message(_("Extracting data..."))
    tar.extractall(path=directory)
    tar.close()

    # We use a new list file name for map registration
    new_list_file_name = list_file_name + "_new"
    # Save current working directory path
    old_cwd = os.getcwd()

    # Switch into the data directory
    os.chdir(directory)

    # Check projection information
    if not location:
        temp_name = gscript.tempfile()
        temp_file = open(temp_name, "w")
        proj_name = os.path.abspath(proj_file_name)

        # We need to convert projection strings generated
        # from other programs than g.proj into
        # new line format so that the grass file comparison function
        # can be used to compare the projections
        proj_name_tmp = temp_name + "_in_projection"
        proj_file = open(proj_name, "r")
        proj_content = proj_file.read()
        proj_content = proj_content.replace(" +", "\n+")
        proj_content = proj_content.replace("\t+", "\n+")
        proj_file.close()

        proj_file = open(proj_name_tmp, "w")
        proj_file.write(proj_content)
        proj_file.close()

        p = gscript.start_command("g.proj", flags="j", stdout=temp_file)
        p.communicate()
        temp_file.close()

        if not gscript.compare_key_value_text_files(
                temp_name, proj_name_tmp, sep="="):
            if overr:
                gscript.warning(
                    _("Projection information does not match. "
                      "Proceeding..."))
            else:
                diff = ''.join(gscript.diff_files(temp_name, proj_name))
                gscript.warning(
                    _("Difference between PROJ_INFO file of "
                      "imported map and of current location:"
                      "\n{diff}").format(diff=diff))
                gscript.fatal(
                    _("Projection information does not match. "
                      "Aborting."))

    # Create a new location based on the projection information and switch
    # into it
    old_env = gscript.gisenv()
    if location:
        try:
            proj4_string = open(proj_file_name, 'r').read()
            gscript.create_location(dbase=old_env["GISDBASE"],
                                    location=location,
                                    proj4=proj4_string)
            # Just create a new location and return
            if create:
                os.chdir(old_cwd)
                return
        except Exception as e:
            gscript.fatal(
                _("Unable to create location %(l)s. Reason: %(e)s") % {
                    'l': location,
                    'e': str(e)
                })
        # Switch to the new created location
        try:
            gscript.run_command("g.mapset",
                                mapset="PERMANENT",
                                location=location,
                                dbase=old_env["GISDBASE"])
        except CalledModuleError:
            gscript.fatal(_("Unable to switch to location %s") % location)
        # create default database connection
        try:
            gscript.run_command("t.connect", flags="d")
        except CalledModuleError:
            gscript.fatal(
                _("Unable to create default temporal database "
                  "in new location %s") % location)

    try:
        # Make sure the temporal database exists
        factory.init()

        fs = "|"
        maplist = []
        mapset = get_current_mapset()
        list_file = open(list_file_name, "r")
        new_list_file = open(new_list_file_name, "w")

        # get number of lines to correctly form the suffix
        max_count = -1
        for max_count, l in enumerate(list_file):
            pass
        max_count += 1
        list_file.seek(0)

        # Read the map list from file
        line_count = 0
        while True:
            line = list_file.readline()
            if not line:
                break

            line_list = line.split(fs)

            # The filename is actually the base name of the map
            # that must be extended by the file suffix
            filename = line_list[0].strip().split(":")[0]
            if base:
                mapname = "%s_%s" % (
                    base, gscript.get_num_suffix(line_count + 1, max_count))
                mapid = "%s@%s" % (mapname, mapset)
            else:
                mapname = filename
                mapid = mapname + "@" + mapset

            row = {}
            row["filename"] = filename
            row["name"] = mapname
            row["id"] = mapid
            row["start"] = line_list[1].strip()
            row["end"] = line_list[2].strip()

            new_list_file.write("%s%s%s%s%s\n" %
                                (mapname, fs, row["start"], fs, row["end"]))

            maplist.append(row)
            line_count += 1

        list_file.close()
        new_list_file.close()

        # Read the init file
        fs = "="
        init = {}
        init_file = open(init_file_name, "r")
        while True:
            line = init_file.readline()
            if not line:
                break

            kv = line.split(fs)
            init[kv[0]] = kv[1].strip()

        init_file.close()

        if "temporal_type" not in init or \
           "semantic_type" not in init or \
           "number_of_maps" not in init:
            gscript.fatal(
                _("Key words %(t)s, %(s)s or %(n)s not found in init"
                  " file.") % {
                      't': "temporal_type",
                      's': "semantic_type",
                      'n': "number_of_maps"
                  })

        if line_count != int(init["number_of_maps"]):
            gscript.fatal(_("Number of maps mismatch in init and list file."))

        format_ = "GTiff"
        type_ = "strds"

        if "stds_type" in init:
            type_ = init["stds_type"]
        if "format" in init:
            format_ = init["format"]

        if stds_type != type_:
            gscript.fatal(
                _("The archive file is of wrong space time dataset"
                  " type"))

        # Check the existence of the files
        if format_ == "GTiff":
            for row in maplist:
                filename = row["filename"] + ".tif"
                if not os.path.exists(filename):
                    gscript.fatal(
                        _("Unable to find GeoTIFF raster file "
                          "<%s> in archive.") % filename)
        elif format_ == "AAIGrid":
            for row in maplist:
                filename = row["filename"] + ".asc"
                if not os.path.exists(filename):
                    gscript.fatal(
                        _("Unable to find AAIGrid raster file "
                          "<%s> in archive.") % filename)
        elif format_ == "GML":
            for row in maplist:
                filename = row["filename"] + ".xml"
                if not os.path.exists(filename):
                    gscript.fatal(
                        _("Unable to find GML vector file "
                          "<%s> in archive.") % filename)
        elif format_ == "pack":
            for row in maplist:
                if type_ == "stvds":
                    filename = str(row["filename"].split(":")[0]) + ".pack"
                else:
                    filename = row["filename"] + ".pack"
                if not os.path.exists(filename):
                    gscript.fatal(
                        _("Unable to find GRASS package file "
                          "<%s> in archive.") % filename)
        else:
            gscript.fatal(_("Unsupported input format"))

        # Check the space time dataset
        id = output + "@" + mapset
        sp = dataset_factory(type_, id)
        if sp.is_in_db() and gscript.overwrite() is False:
            gscript.fatal(
                _("Space time %(t)s dataset <%(sp)s> is already in"
                  " the database. Use the overwrite flag.") % {
                      't': type_,
                      'sp': sp.get_id()
                  })

        # Import the maps
        if type_ == "strds":
            if format_ == "GTiff" or format_ == "AAIGrid":
                _import_raster_maps_from_gdal(maplist, overr, exp, location,
                                              link, format_,
                                              set_current_region, memory)
            if format_ == "pack":
                _import_raster_maps(maplist, set_current_region)
        elif type_ == "stvds":
            if format_ == "GML":
                _import_vector_maps_from_gml(maplist, overr, exp, location,
                                             link)
            if format_ == "pack":
                _import_vector_maps(maplist)

        # Create the space time dataset
        if sp.is_in_db() and gscript.overwrite() is True:
            gscript.info(
                _("Overwrite space time %(sp)s dataset "
                  "<%(id)s> and unregister all maps.") % {
                      'sp': sp.get_new_map_instance(None).get_type(),
                      'id': sp.get_id()
                  })
            sp.delete()
            sp = sp.get_new_instance(id)

        temporal_type = init["temporal_type"]
        semantic_type = init["semantic_type"]
        relative_time_unit = None
        if temporal_type == "relative":
            if "relative_time_unit" not in init:
                gscript.fatal(
                    _("Key word %s not found in init file.") %
                    ("relative_time_unit"))
            relative_time_unit = init["relative_time_unit"]
            sp.set_relative_time_unit(relative_time_unit)

        gscript.verbose(
            _("Create space time %s dataset.") %
            sp.get_new_map_instance(None).get_type())

        sp.set_initial_values(temporal_type=temporal_type,
                              semantic_type=semantic_type,
                              title=title,
                              description=descr)
        sp.insert()

        # register the maps
        fs = "|"
        register_maps_in_space_time_dataset(
            type=sp.get_new_map_instance(None).get_type(),
            name=output,
            file=new_list_file_name,
            start="file",
            end="file",
            unit=relative_time_unit,
            dbif=None,
            fs=fs,
            update_cmd_list=False)

        os.chdir(old_cwd)
    except:
        raise

    # Make sure the location is switched back correctly
    finally:
        if location:
            # Switch to the old location
            try:
                gscript.run_command("g.mapset",
                                    mapset=old_env["MAPSET"],
                                    location=old_env["LOCATION_NAME"],
                                    gisdbase=old_env["GISDBASE"])
            except CalledModuleError:
                grass.warning(_("Switching to original location failed"))

        gscript.set_raise_on_error(old_state)
Example #19
0
def main():
    grass.set_raise_on_error(False)

    options, flags = grass.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()
    
    from core.globalvar import CheckWxVersion
    from core.utils import _
    from core.render import Map
    from mapdisp.frame import MapFrame
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings
    from vdigit.main import haveVDigit, errorMsg
    from grass.exceptions import CalledModuleError

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class VDigitMapFrame(MapFrame):
        def __init__(self, vectorMap):
            MapFrame.__init__(
                self, parent=None, Map=Map(), giface=DMonGrassInterface(None),
                title=_("GRASS GIS Vector Digitizer"), size=(850, 600))
            # this giface issue not solved yet, we must set mapframe aferwards
            self._giface._mapframe = self
            # load vector map
            mapLayer = self.GetMap().AddLayer(
                ltype='vector', name=vectorMap,
                command=['d.vect', 'map=%s' % vectorMap],
                active=True, hidden=False, opacity=1.0, render=True)

            # switch toolbar
            self.AddToolbar('vdigit', fixed=True)

            # start editing
            self.toolbars['vdigit'].StartEditing(mapLayer)

    if not haveVDigit:
        grass.fatal(_("Vector digitizer not available. %s") % errorMsg)

    if not grass.find_file(name=options['map'], element='vector',
                           mapset=grass.gisenv()['MAPSET'])['fullname']:
        if not flags['c']:
            grass.fatal(_("Vector map <%s> not found in current mapset. "
                          "New vector map can be created by providing '-c' flag.") % options['map'])
        else:
            grass.verbose(_("New vector map <%s> created") % options['map'])
            try:
                grass.run_command('v.edit', map=options['map'], tool='create', quiet=True)
            except CalledModuleError:
                grass.fatal(_("Unable to create new vector map <%s>") % options['map'])

    # allow immediate rendering
    driver = UserSettings.Get(group='display', key='driver', subkey='type')
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()
    frame = VDigitMapFrame(options['map'])
    frame.Show()

    app.MainLoop()
Example #20
0
File: frame.py Project: caomw/grass
from core.utils import _

from animation.mapwindow import AnimationWindow
from animation.provider import BitmapProvider, BitmapPool, \
    MapFilesPool, CleanUp
from animation.controller import AnimationController
from animation.anim import Animation
from animation.toolbars import MainToolbar, AnimationToolbar, MiscToolbar
from animation.dialogs import SpeedDialog, PreferencesDialog
from animation.utils import Orientation, ReplayMode, TemporalType


MAX_COUNT = 4
TMP_DIR = None

gcore.set_raise_on_error(True)


class AnimationFrame(wx.Frame):
    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
        tgis.init()
Example #21
0
def main():
    grass.set_raise_on_error(False)

    options, flags = grass.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.render import Map
    from mapdisp.frame import MapFrame
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings
    from vdigit.main import haveVDigit, errorMsg
    from grass.exceptions import CalledModuleError

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class VDigitMapFrame(MapFrame):
        def __init__(self, vectorMap):
            MapFrame.__init__(
                self,
                parent=None,
                Map=Map(),
                giface=DMonGrassInterface(None),
                title=_("Vector Digitizer - GRASS GIS"),
                size=(850, 600),
            )
            # this giface issue not solved yet, we must set mapframe aferwards
            self._giface._mapframe = self
            # load vector map
            mapLayer = self.GetMap().AddLayer(
                ltype="vector",
                name=vectorMap,
                command=["d.vect", "map=%s" % vectorMap],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True,
            )

            # switch toolbar
            self.AddToolbar("vdigit", fixed=True)

            # start editing
            self.toolbars["vdigit"].StartEditing(mapLayer)
            # use Close instead of QuitVDigit for standalone tool
            self.toolbars["vdigit"].quitDigitizer.disconnect(self.QuitVDigit)
            self.toolbars["vdigit"].quitDigitizer.connect(lambda: self.Close())

    if not haveVDigit:
        grass.fatal(_("Vector digitizer not available. %s") % errorMsg)

    if not grass.find_file(name=options["map"],
                           element="vector",
                           mapset=grass.gisenv()["MAPSET"])["fullname"]:
        if not flags["c"]:
            grass.fatal(
                _("Vector map <%s> not found in current mapset. "
                  "New vector map can be created by providing '-c' flag.") %
                options["map"])
        else:
            grass.verbose(_("New vector map <%s> created") % options["map"])
            try:
                grass.run_command("v.edit",
                                  map=options["map"],
                                  tool="create",
                                  quiet=True)
            except CalledModuleError:
                grass.fatal(
                    _("Unable to create new vector map <%s>") % options["map"])

    # allow immediate rendering
    driver = UserSettings.Get(group="display", key="driver", subkey="type")
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    app = wx.App()
    frame = VDigitMapFrame(options["map"])
    frame.Show()

    app.MainLoop()
Example #22
0
def main():
    gscript.set_raise_on_error(False)
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.settings import UserSettings
    from iclass.frame import IClassMapFrame

    group_name = subgroup_name = map_name = trainingmap_name = None

    if options["group"]:
        if not options["subgroup"]:
            gscript.fatal(_("Name of subgroup required"))
        group_name = gscript.find_file(name=options["group"],
                                       element="group")["name"]
        if not group_name:
            gscript.fatal(_("Group <%s> not found") % options["group"])
        subgroups = gscript.read_command("i.group",
                                         group=group_name,
                                         flags="sg").splitlines()
        if options["subgroup"] not in subgroups:
            gscript.fatal(_("Subgroup <%s> not found") % options["subgroup"])
        subgroup_name = options["subgroup"]

    if options["map"]:
        map_name = gscript.find_file(name=options["map"],
                                     element="cell")["fullname"]
        if not map_name:
            gscript.fatal(_("Raster map <%s> not found") % options["map"])

    if options["trainingmap"]:
        trainingmap_name = gscript.find_file(name=options["trainingmap"],
                                             element="vector")["fullname"]
        if not trainingmap_name:
            gscript.fatal(
                _("Vector map <%s> not found") % options["trainingmap"])

    # define display driver
    driver = UserSettings.Get(group="display", key="driver", subkey="type")
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    # launch application
    app = wx.App()

    # show main frame
    frame = IClassMapFrame(
        parent=None,
        giface=None,
        title=_("Supervised Classification Tool - GRASS GIS"),
    )
    if not flags["m"]:
        frame.CenterOnScreen()
    if group_name:
        frame.SetGroup(group_name, subgroup_name)
    if map_name:
        frame.giface.WriteLog(_("Loading raster map <%s>...") % map_name)
        frame.trainingMapManager.AddLayer(map_name)
    if trainingmap_name:
        frame.giface.WriteLog(
            _("Loading training map <%s>...") % trainingmap_name)
        frame.ImportAreas(trainingmap_name)

    frame.Show()
    if flags["m"]:
        frame.Maximize()
    app.MainLoop()
Example #23
0
def main():
    gscript.set_raise_on_error(False)
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.settings import UserSettings
    from core.globalvar import CheckWxVersion
    from core.giface import StandaloneGrassInterface
    from core.utils import _
    from iclass.frame import IClassMapFrame

    group_name = subgroup_name = map_name = trainingmap_name = None

    if options['group']:
        if not options['subgroup']:
            gscript.fatal(_("Name of subgroup required"))
        group_name = gscript.find_file(name=options['group'],
                                       element='group')['name']
        if not group_name:
            gscript.fatal(_("Group <%s> not found") % options['group'])
        subgroups = gscript.read_command('i.group',
                                         group=group_name,
                                         flags='sg').splitlines()
        if options['subgroup'] not in subgroups:
            gscript.fatal(_("Subgroup <%s> not found") % options['subgroup'])
        subgroup_name = options['subgroup']

    if options['map']:
        map_name = gscript.find_file(name=options['map'],
                                     element='cell')['fullname']
        if not map_name:
            gscript.fatal(_("Raster map <%s> not found") % options['map'])

    if options['trainingmap']:
        trainingmap_name = gscript.find_file(name=options['trainingmap'],
                                             element='vector')['fullname']
        if not trainingmap_name:
            gscript.fatal(
                _("Vector map <%s> not found") %
                options['trainingmap'])

    # define display driver
    driver = UserSettings.Get(group='display', key='driver', subkey='type')
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

    # launch application
    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()

    # show main frame
    giface = StandaloneGrassInterface()
    frame = IClassMapFrame(parent=None, giface=giface)
    if not flags['m']:
        frame.CenterOnScreen()
    if group_name:
        frame.SetGroup(group_name, subgroup_name)
    if map_name:
        giface.WriteLog(_("Loading raster map <%s>...") % map_name)
        frame.trainingMapManager.AddLayer(map_name)
    if trainingmap_name:
        giface.WriteLog(_("Loading training map <%s>...") % trainingmap_name)
        frame.ImportAreas(trainingmap_name)

    frame.Show()
    if flags['m']:
        frame.Maximize()
    app.MainLoop()
Example #24
0
def main():
    # Get the options
    input = options["input"]
    start = options["start"]
    stop = options["stop"]
    base = options["basename"]
    cycle = options["cycle"]
    offset = options["offset"]
    minimum = options["minimum"]
    maximum = options["maximum"]
    occurrence = options["occurrence"]
    range = options["range"]
    indicator = options["indicator"]
    staend = options["staend"]
    register_null = flags["n"]
    reverse = flags["r"]
    time_suffix = options["suffix"]

    grass.set_raise_on_error(True)

    # Make sure the temporal database exists
    tgis.init()
    # We need a database interface
    dbif = tgis.SQLDatabaseInterfaceConnection()
    dbif.connect()

    mapset = tgis.get_current_mapset()

    if input.find("@") >= 0:
        id = input
    else:
        id = input + "@" + mapset

    input_strds = tgis.SpaceTimeRasterDataset(id)

    if input_strds.is_in_db() == False:
        dbif.close()
        grass.fatal(
            _("Space time %s dataset <%s> not found") %
            (input_strds.get_output_map_instance(None).get_type(), id))

    input_strds.select(dbif)
    dummy = input_strds.get_new_map_instance(None)

    # The occurrence space time raster dataset
    if occurrence:
        if not minimum or not maximum:
            if not range:
                dbif.close()
                grass.fatal(
                    _("You need to set the range to compute the occurrence"
                      " space time raster dataset"))

        if occurrence.find("@") >= 0:
            occurrence_id = occurrence
        else:
            occurrence_id = occurrence + "@" + mapset

        occurrence_strds = tgis.SpaceTimeRasterDataset(occurrence_id)
        if occurrence_strds.is_in_db(dbif):
            if not grass.overwrite():
                dbif.close()
                grass.fatal(
                    _("Space time raster dataset <%s> is already in the "
                      "database, use overwrite flag to overwrite") %
                    occurrence_id)

    # The indicator space time raster dataset
    if indicator:
        if not occurrence:
            dbif.close()
            grass.fatal(
                _("You need to set the occurrence to compute the indicator"
                  " space time raster dataset"))
        if not staend:
            dbif.close()
            grass.fatal(
                _("You need to set the staend options to compute the indicator"
                  " space time raster dataset"))
        if indicator.find("@") >= 0:
            indicator = indicator
        else:
            indicator_id = indicator + "@" + mapset

        indicator_strds = tgis.SpaceTimeRasterDataset(indicator_id)
        if indicator_strds.is_in_db(dbif):
            if not grass.overwrite():
                dbif.close()
                grass.fatal(
                    _("Space time raster dataset <%s> is already in the "
                      "database, use overwrite flag to overwrite") %
                    indicator_id)
        staend = staend.split(",")
        indicator_start = int(staend[0])
        indicator_mid = int(staend[1])
        indicator_end = int(staend[2])

    # The minimum threshold space time raster dataset
    minimum_strds = None
    if minimum:
        if minimum.find("@") >= 0:
            minimum_id = minimum
        else:
            minimum_id = minimum + "@" + mapset

        minimum_strds = tgis.SpaceTimeRasterDataset(minimum_id)
        if minimum_strds.is_in_db() == False:
            dbif.close()
            grass.fatal(
                _("Space time raster dataset <%s> not found") %
                (minimum_strds.get_id()))

        if minimum_strds.get_temporal_type() != input_strds.get_temporal_type(
        ):
            dbif.close()
            grass.fatal(
                _("Temporal type of input strds and minimum strds must be equal"
                  ))

        minimum_strds.select(dbif)

    # The maximum threshold space time raster dataset
    maximum_strds = None
    if maximum:
        if maximum.find("@") >= 0:
            maximum_id = maximum
        else:
            maximum_id = maximum + "@" + mapset

        maximum_strds = tgis.SpaceTimeRasterDataset(maximum_id)
        if maximum_strds.is_in_db() == False:
            dbif.close()
            grass.fatal(
                _("Space time raster dataset <%s> not found") %
                (maximum_strds.get_id()))

        if maximum_strds.get_temporal_type() != input_strds.get_temporal_type(
        ):
            dbif.close()
            grass.fatal(
                _("Temporal type of input strds and maximum strds must be equal"
                  ))

        maximum_strds.select(dbif)

    input_strds_start, input_strds_end = input_strds.get_temporal_extent_as_tuple(
    )

    if input_strds.is_time_absolute():
        start = tgis.string_to_datetime(start)
        if stop:
            stop = tgis.string_to_datetime(stop)
        else:
            stop = input_strds_end
    else:
        start = int(start)
        if stop:
            stop = int(stop)
        else:
            stop = input_strds_end

    if input_strds.is_time_absolute():
        end = tgis.increment_datetime_by_string(start, cycle)
    else:
        end = start + cycle

    count = 1
    indi_count = 1
    occurrence_maps = {}
    indicator_maps = {}

    while input_strds_end > start and stop > start:

        # Make sure that the cyclic computation will stop at the correct time
        if stop and end > stop:
            end = stop

        where = "start_time >= \'%s\' AND start_time < \'%s\'" % (str(start),
                                                                  str(end))
        input_maps = input_strds.get_registered_maps_as_objects(where=where,
                                                                dbif=dbif)

        print len(input_maps)

        input_topo = tgis.SpatioTemporalTopologyBuilder()
        input_topo.build(input_maps, input_maps)

        if len(input_maps) == 0:
            continue

        grass.message(_("Processing cycle %s - %s" % (str(start), str(end))))

        count = compute_occurrence(occurrence_maps, input_strds, input_maps,
                                   start, base, count, time_suffix, mapset,
                                   where, reverse, range, minimum_strds,
                                   maximum_strds, dbif)

        # Indicator computation is based on the occurrence so we need to start it after
        # the occurrence cycle
        if indicator:
            num_maps = len(input_maps)
            for i in xrange(num_maps):
                if reverse:
                    map = input_maps[num_maps - i - 1]
                else:
                    map = input_maps[i]

                if input_strds.get_temporal_type(
                ) == 'absolute' and time_suffix == 'gran':
                    suffix = tgis.create_suffix_from_datetime(
                        map.temporal_extent.get_start_time(),
                        input_strds.get_granularity())
                    indicator_map_name = "{ba}_indicator_{su}".format(
                        ba=base, su=suffix)
                elif input_strds.get_temporal_type(
                ) == 'absolute' and time_suffix == 'time':
                    suffix = tgis.create_time_suffix(map)
                    indicator_map_name = "{ba}_indicator_{su}".format(
                        ba=base, su=suffix)
                else:
                    indicator_map_name = tgis.create_numeric_suffic(
                        base + "_indicator", indi_count, time_suffix)
                indicator_map_id = dummy.build_id(indicator_map_name, mapset)
                indicator_map = input_strds.get_new_map_instance(
                    indicator_map_id)

                # Check if new map is in the temporal database
                if indicator_map.is_in_db(dbif):
                    if grass.overwrite():
                        # Remove the existing temporal database entry
                        indicator_map.delete(dbif)
                        indicator_map = input_strds.get_new_map_instance(
                            indicator_map_id)
                    else:
                        grass.fatal(
                            _("Map <%s> is already registered in the temporal"
                              " database, use overwrite flag to overwrite.") %
                            (indicator_map.get_map_id()))

                curr_map = occurrence_maps[map.get_id()].get_name()

                # Reverse time
                if reverse:
                    if i == 0:
                        prev_map = curr_map
                        subexpr1 = "null()"
                        subexpr3 = "%i" % (indicator_start)
                    elif i > 0 and i < num_maps - 1:
                        prev_map = occurrence_maps[
                            map.next().get_id()].get_name()
                        next_map = occurrence_maps[
                            map.prev().get_id()].get_name()
                        # In case the previous map is null() set null() or the start indicator
                        subexpr1 = "if(isnull(%s), null(), %i)" % (
                            curr_map, indicator_start)
                        # In case the previous map was not null() if the current map is null() set null()
                        # if the current map is not null() and the next map is not null() set
                        # intermediate indicator, if the next map is null set the end indicator
                        subexpr2 = "if(isnull(%s), %i, %i)" % (
                            next_map, indicator_end, indicator_mid)
                        subexpr3 = "if(isnull(%s), null(), %s)" % (curr_map,
                                                                   subexpr2)
                        expression = "%s = if(isnull(%s), %s, %s)" % (
                            indicator_map_name, prev_map, subexpr1, subexpr3)
                    else:
                        prev_map = occurrence_maps[
                            map.next().get_id()].get_name()
                        subexpr1 = "if(isnull(%s), null(), %i)" % (
                            curr_map, indicator_start)
                        subexpr3 = "if(isnull(%s), null(), %i)" % (
                            curr_map, indicator_mid)
                else:
                    if i == 0:
                        prev_map = curr_map
                        subexpr1 = "null()"
                        subexpr3 = "%i" % (indicator_start)
                    elif i > 0 and i < num_maps - 1:
                        prev_map = occurrence_maps[
                            map.prev().get_id()].get_name()
                        next_map = occurrence_maps[
                            map.next().get_id()].get_name()
                        # In case the previous map is null() set null() or the start indicator
                        subexpr1 = "if(isnull(%s), null(), %i)" % (
                            curr_map, indicator_start)
                        # In case the previous map was not null() if the current map is null() set null()
                        # if the current map is not null() and the next map is not null() set
                        # intermediate indicator, if the next map is null set the end indicator
                        subexpr2 = "if(isnull(%s), %i, %i)" % (
                            next_map, indicator_end, indicator_mid)
                        subexpr3 = "if(isnull(%s), null(), %s)" % (curr_map,
                                                                   subexpr2)
                        expression = "%s = if(isnull(%s), %s, %s)" % (
                            indicator_map_name, prev_map, subexpr1, subexpr3)
                    else:
                        prev_map = occurrence_maps[
                            map.prev().get_id()].get_name()
                        subexpr1 = "if(isnull(%s), null(), %i)" % (
                            curr_map, indicator_start)
                        subexpr3 = "if(isnull(%s), null(), %i)" % (
                            curr_map, indicator_mid)

                expression = "%s = if(isnull(%s), %s, %s)" % (
                    indicator_map_name, prev_map, subexpr1, subexpr3)
                print expression
                grass.mapcalc(expression, overwrite=True)

                map_start, map_end = map.get_temporal_extent_as_tuple()

                if map.is_time_absolute():
                    indicator_map.set_absolute_time(map_start, map_end)
                else:
                    indicator_map.set_relative_time(
                        map_start, map_end, map.get_relative_time_unit())

                indicator_maps[map.get_id()] = indicator_map
                indi_count += 1

        # Increment the cycle
        start = end
        if input_strds.is_time_absolute():
            start = end
            if offset:
                start = tgis.increment_datetime_by_string(end, offset)
            end = tgis.increment_datetime_by_string(start, cycle)
        else:
            if offset:
                start = end + offset
            end = start + cycle

    empty_maps = []

    create_strds_register_maps(input_strds, occurrence_strds, occurrence_maps,
                               register_null, empty_maps, dbif)

    if indicator:
        create_strds_register_maps(input_strds, indicator_strds,
                                   indicator_maps, register_null, empty_maps,
                                   dbif)

    dbif.close()

    # Remove empty maps
    if len(empty_maps) > 0:
        for map in empty_maps:
            grass.run_command("g.remove",
                              flags='f',
                              type="raster",
                              name=map.get_name(),
                              quiet=True)
Example #25
0
def main():
    gs.set_raise_on_error(False)

    options, flags = gs.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.render import Map
    from mapdisp.frame import MapFrame
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class RDigitMapFrame(MapFrame):
        def __init__(
            self,
            new_map=None,
            base_map=None,
            edit_map=None,
            map_type=None,
        ):
            MapFrame.__init__(
                self,
                parent=None,
                Map=Map(),
                giface=DMonGrassInterface(None),
                title=_("Raster Digitizer - GRASS GIS"),
                size=(850, 600),
            )
            # this giface issue not solved yet, we must set mapframe afterwards
            self._giface._mapframe = self
            self._giface.mapCreated.connect(self.OnMapCreated)
            self._mapObj = self.GetMap()

            # load raster map
            self._addLayer(name=new_map if new_map else edit_map)

            # switch toolbar
            self.AddToolbar("rdigit", fixed=True)

            rdigit = self.toolbars["rdigit"]
            if new_map:
                rdigit._mapSelectionCombo.Unbind(wx.EVT_COMBOBOX)
                self.rdigit.SelectNewMap(
                    standalone=True,
                    mapName=new_map,
                    bgMap=base_map,
                    mapType=map_type,
                )
                rdigit._mapSelectionCombo.Bind(
                    wx.EVT_COMBOBOX,
                    rdigit.OnMapSelection,
                )
            else:
                rdigit._mapSelectionCombo.SetSelection(n=1)
                rdigit.OnMapSelection()
            # use Close instead of QuitRDigit for standalone tool
            self.rdigit.quitDigitizer.disconnect(self.QuitRDigit)
            self.rdigit.quitDigitizer.connect(lambda: self.Close())

        def _addLayer(self, name, ltype="raster"):
            """Add layer into map

            :param str name: map name
            :param str ltype: layer type
            """
            mapLayer = self._mapObj.AddLayer(
                ltype=ltype,
                name=name,
                command=["d.rast", "map={}".format(name)],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True,
            )

        def OnMapCreated(self, name, ltype):
            """Add new created raster layer into map

            :param str name: map name
            :param str ltype: layer type
            """
            self._mapObj.Clean()
            self._addLayer(name=name, ltype=ltype)
            self.GetMapWindow().UpdateMap()

    kwargs = {
        "new_map": options["create"],
        "base_map": options["base"],
        "edit_map": options["edit"],
        "map_type": options["type"],
    }

    mapset = gs.gisenv()["MAPSET"]

    if kwargs["edit_map"]:
        edit_map = gs.find_file(
            name=kwargs["edit_map"],
            element="raster",
            mapset=mapset,
        )["fullname"]

        if not edit_map:
            gs.fatal(
                _(
                    "Raster map <{}> not found in current mapset.".format(
                        options["edit"], ), ), )
        else:
            kwargs["edit_map"] = edit_map
    else:
        if kwargs["base_map"]:
            base_map = gs.find_file(
                name=kwargs["base_map"],
                element="raster",
                mapset=mapset,
            )["fullname"]
            if not base_map:
                gs.fatal(
                    _(
                        "Base raster map <{}> not found in "
                        "current mapset.".format(options["base"], ), ), )
            kwargs["base_map"] = base_map

    # allow immediate rendering
    driver = UserSettings.Get(
        group="display",
        key="driver",
        subkey="type",
    )
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    app = wx.App()
    frame = RDigitMapFrame(**kwargs)
    frame.Show()

    app.MainLoop()
Example #26
0
def main():
    gscript.set_raise_on_error(False)
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.settings import UserSettings
    from core.giface import StandaloneGrassInterface
    from iclass.frame import IClassMapFrame

    group_name = subgroup_name = map_name = trainingmap_name = None

    if options['group']:
        if not options['subgroup']:
            gscript.fatal(_("Name of subgroup required"))
        group_name = gscript.find_file(name=options['group'],
                                       element='group')['name']
        if not group_name:
            gscript.fatal(_("Group <%s> not found") % options['group'])
        subgroups = gscript.read_command('i.group',
                                         group=group_name,
                                         flags='sg').splitlines()
        if options['subgroup'] not in subgroups:
            gscript.fatal(_("Subgroup <%s> not found") % options['subgroup'])
        subgroup_name = options['subgroup']

    if options['map']:
        map_name = gscript.find_file(name=options['map'],
                                     element='cell')['fullname']
        if not map_name:
            gscript.fatal(_("Raster map <%s> not found") % options['map'])

    if options['trainingmap']:
        trainingmap_name = gscript.find_file(name=options['trainingmap'],
                                             element='vector')['fullname']
        if not trainingmap_name:
            gscript.fatal(
                _("Vector map <%s> not found") % options['trainingmap'])

    # define display driver
    driver = UserSettings.Get(group='display', key='driver', subkey='type')
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

    # launch application
    app = wx.App()

    # show main frame
    giface = StandaloneGrassInterface()
    frame = IClassMapFrame(parent=None, giface=giface)
    if not flags['m']:
        frame.CenterOnScreen()
    if group_name:
        frame.SetGroup(group_name, subgroup_name)
    if map_name:
        giface.WriteLog(_("Loading raster map <%s>...") % map_name)
        frame.trainingMapManager.AddLayer(map_name)
    if trainingmap_name:
        giface.WriteLog(_("Loading training map <%s>...") % trainingmap_name)
        frame.ImportAreas(trainingmap_name)

    frame.Show()
    if flags['m']:
        frame.Maximize()
    app.MainLoop()
Example #27
0
def import_stds(input, output, directory, title=None, descr=None, location=None,
                link=False, exp=False, overr=False, create=False,
                stds_type="strds", base=None, set_current_region=False):
    """Import space time datasets of type raster and vector

        :param input: Name of the input archive file
        :param output: The name of the output space time dataset
        :param directory: The extraction directory
        :param title: The title of the new created space time dataset
        :param descr: The description of the new created
                     space time dataset
        :param location: The name of the location that should be created,
                        maps are imported into this location
        :param link: Switch to link raster maps instead importing them
        :param exp: Extend location extents based on new dataset
        :param overr: Override projection (use location's projection)
        :param create: Create the location specified by the "location"
                      parameter and exit.
                      Do not import the space time datasets.
        :param stds_type: The type of the space time dataset that
                         should be imported
        :param base: The base name of the new imported maps, it will be
                     extended using a numerical index.
    """

    global raise_on_error
    old_state = gscript.raise_on_error
    gscript.set_raise_on_error(True)

    # Check if input file and extraction directory exits
    if not os.path.exists(input):
        gscript.fatal(_("Space time raster dataset archive <%s> not found")
                      % input)
    if not create and not os.path.exists(directory):
        gscript.fatal(_("Extraction directory <%s> not found") % directory)

    tar = tarfile.open(name=input, mode='r')

    # Check for important files
    msgr = get_tgis_message_interface()
    msgr.message(_("Checking validity of input file (size: %0.1f MB). Make take a while..."
        % (os.path.getsize(input)/(1024*1024.0))))
    members = tar.getnames()
    # Make sure that the basenames of the files are used for comparison
    member_basenames = [os.path.basename(name) for name in members]

    if init_file_name not in member_basenames:
        gscript.fatal(_("Unable to find init file <%s>") % init_file_name)
    if list_file_name not in member_basenames:
        gscript.fatal(_("Unable to find list file <%s>") % list_file_name)
    if proj_file_name not in member_basenames:
        gscript.fatal(_("Unable to find projection file <%s>") % proj_file_name)

    msgr.message(_("Extracting data..."))
    tar.extractall(path=directory)
    tar.close()

    # We use a new list file name for map registration
    new_list_file_name = list_file_name + "_new"
    # Save current working directory path
    old_cwd = os.getcwd()

    # Switch into the data directory
    os.chdir(directory)

    # Check projection information
    if not location:
        temp_name = gscript.tempfile()
        temp_file = open(temp_name, "w")
        proj_name = os.path.abspath(proj_file_name)

        # We need to convert projection strings generated 
        # from other programms than g.proj into
        # new line format so that the grass file comparison function
        # can be used to compare the projections
        proj_name_tmp = temp_name + "_in_projection"
        proj_file = open(proj_name, "r")
        proj_content = proj_file.read()
        proj_content = proj_content.replace(" +", "\n+")
        proj_content = proj_content.replace("\t+", "\n+")
        proj_file.close()

        proj_file = open(proj_name_tmp, "w")
        proj_file.write(proj_content)
        proj_file.close()

        p = gscript.start_command("g.proj", flags="j", stdout=temp_file)
        p.communicate()
        temp_file.close()

        if not gscript.compare_key_value_text_files(temp_name, proj_name_tmp,
                                                    sep="="):
            if overr:
                gscript.warning(_("Projection information does not match. "
                                  "Proceeding..."))
            else:
                diff = ''.join(gscript.diff_files(temp_name, proj_name))
                gscript.warning(_("Difference between PROJ_INFO file of "
                                  "imported map and of current location:"
                                  "\n{diff}").format(diff=diff))
                gscript.fatal(_("Projection information does not match. "
                                "Aborting."))

    # Create a new location based on the projection information and switch
    # into it
    old_env = gscript.gisenv()
    if location:
        try:
            proj4_string = open(proj_file_name, 'r').read()
            gscript.create_location(dbase=old_env["GISDBASE"],
                                    location=location,
                                    proj4=proj4_string)
            # Just create a new location and return
            if create:
                os.chdir(old_cwd)
                return
        except Exception as e:
            gscript.fatal(_("Unable to create location %(l)s. Reason: %(e)s")
                          % {'l': location, 'e': str(e)})
        # Switch to the new created location
        try:
            gscript.run_command("g.mapset", mapset="PERMANENT",
                                location=location,
                                dbase=old_env["GISDBASE"])
        except CalledModuleError:
            gscript.fatal(_("Unable to switch to location %s") % location)
        # create default database connection
        try:
            gscript.run_command("t.connect", flags="d")
        except CalledModuleError:
            gscript.fatal(_("Unable to create default temporal database "
                            "in new location %s") % location)

    try:
        # Make sure the temporal database exists
        factory.init()

        fs = "|"
        maplist = []
        mapset = get_current_mapset()
        list_file = open(list_file_name, "r")
        new_list_file = open(new_list_file_name, "w")

        # get number of lines to correctly form the suffix
        max_count = -1
        for max_count, l in enumerate(list_file):
            pass
        max_count += 1
        list_file.seek(0)

        # Read the map list from file
        line_count = 0
        while True:
            line = list_file.readline()
            if not line:
                break

            line_list = line.split(fs)

            # The filename is actually the base name of the map
            # that must be extended by the file suffix
            filename = line_list[0].strip().split(":")[0]
            if base:
                mapname = "%s_%s" % (base, gscript.get_num_suffix(line_count + 1,
                                                                  max_count))
                mapid = "%s@%s" % (mapname, mapset)
            else:
                mapname = filename
                mapid = mapname + "@" + mapset

            row = {}
            row["filename"] = filename
            row["name"] = mapname
            row["id"] = mapid
            row["start"] = line_list[1].strip()
            row["end"] = line_list[2].strip()

            new_list_file.write("%s%s%s%s%s\n" % (mapname, fs, row["start"],
                                                  fs, row["end"]))

            maplist.append(row)
            line_count += 1

        list_file.close()
        new_list_file.close()

        # Read the init file
        fs = "="
        init = {}
        init_file = open(init_file_name, "r")
        while True:
            line = init_file.readline()
            if not line:
                break

            kv = line.split(fs)
            init[kv[0]] = kv[1].strip()

        init_file.close()

        if "temporal_type" not in init or \
           "semantic_type" not in init or \
           "number_of_maps" not in init:
            gscript.fatal(_("Key words %(t)s, %(s)s or %(n)s not found in init"
                            " file.") % {'t': "temporal_type",
                                         's': "semantic_type",
                                         'n': "number_of_maps"})

        if line_count != int(init["number_of_maps"]):
            gscript.fatal(_("Number of maps mismatch in init and list file."))

        format_ = "GTiff"
        type_ = "strds"

        if "stds_type" in init:
            type_ = init["stds_type"]
        if "format" in init:
            format_ = init["format"]

        if stds_type != type_:
            gscript.fatal(_("The archive file is of wrong space time dataset"
                            " type"))

        # Check the existence of the files
        if format_ == "GTiff":
            for row in maplist:
                filename = row["filename"] + ".tif"
                if not os.path.exists(filename):
                    gscript.fatal(_("Unable to find GeoTIFF raster file "
                                    "<%s> in archive.") % filename)
        elif format_ == "AAIGrid":
            for row in maplist:
                filename = row["filename"] + ".asc"
                if not os.path.exists(filename):
                    gscript.fatal(_("Unable to find AAIGrid raster file "
                                    "<%s> in archive.") % filename)
        elif format_ == "GML":
            for row in maplist:
                filename = row["filename"] + ".xml"
                if not os.path.exists(filename):
                    gscript.fatal(_("Unable to find GML vector file "
                                    "<%s> in archive.") % filename)
        elif format_ == "pack":
            for row in maplist:
                if type_ == "stvds":
                    filename = str(row["filename"].split(":")[0]) + ".pack"
                else:
                    filename = row["filename"] + ".pack"
                if not os.path.exists(filename):
                    gscript.fatal(_("Unable to find GRASS package file "
                                    "<%s> in archive.") % filename)
        else:
            gscript.fatal(_("Unsupported input format"))

        # Check the space time dataset
        id = output + "@" + mapset
        sp = dataset_factory(type_, id)
        if sp.is_in_db() and gscript.overwrite() is False:
            gscript.fatal(_("Space time %(t)s dataset <%(sp)s> is already in"
                            " the database. Use the overwrite flag.") %
                          {'t': type_, 'sp': sp.get_id()})

        # Import the maps
        if type_ == "strds":
            if format_ == "GTiff" or format_ == "AAIGrid":
                _import_raster_maps_from_gdal(maplist, overr, exp, location,
                                              link, format_, set_current_region)
            if format_ == "pack":
                _import_raster_maps(maplist, set_current_region)
        elif type_ == "stvds":
            if format_ == "GML":
                _import_vector_maps_from_gml(
                    maplist, overr, exp, location, link)
            if format_ == "pack":
                _import_vector_maps(maplist)

        # Create the space time dataset
        if sp.is_in_db() and gscript.overwrite() is True:
            gscript.info(_("Overwrite space time %(sp)s dataset "
                           "<%(id)s> and unregister all maps.") %
                         {'sp': sp.get_new_map_instance(None).get_type(),
                          'id': sp.get_id()})
            sp.delete()
            sp = sp.get_new_instance(id)

        temporal_type = init["temporal_type"]
        semantic_type = init["semantic_type"]
        relative_time_unit = None
        if temporal_type == "relative":
            if "relative_time_unit" not in init:
                gscript.fatal(_("Key word %s not found in init file.") %
                              ("relative_time_unit"))
            relative_time_unit = init["relative_time_unit"]
            sp.set_relative_time_unit(relative_time_unit)

        gscript.verbose(_("Create space time %s dataset.") %
                        sp.get_new_map_instance(None).get_type())

        sp.set_initial_values(temporal_type=temporal_type,
                              semantic_type=semantic_type, title=title,
                              description=descr)
        sp.insert()

        # register the maps
        fs = "|"
        register_maps_in_space_time_dataset(
            type=sp.get_new_map_instance(None).get_type(),
            name=output, file=new_list_file_name, start="file",
            end="file", unit=relative_time_unit, dbif=None, fs=fs,
            update_cmd_list=False)

        os.chdir(old_cwd)
    except:
        raise

    # Make sure the location is switched back correctly
    finally:
        if location:
            # Switch to the old location
            try:
                gscript.run_command("g.mapset", mapset=old_env["MAPSET"],
                                    location=old_env["LOCATION_NAME"],
                                    gisdbase=old_env["GISDBASE"])
            except CalledModuleError:
                grass.warning(_("Switching to original location failed"))

        gscript.set_raise_on_error(old_state)
Example #28
0
def main():
    grass.set_raise_on_error(False)

    options, flags = grass.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.render import Map
    from mapdisp.frame import MapFrame
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings
    from vdigit.main import haveVDigit, errorMsg
    from grass.exceptions import CalledModuleError

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class VDigitMapFrame(MapFrame):
        def __init__(self, vectorMap):
            MapFrame.__init__(self,
                              parent=None,
                              Map=Map(),
                              giface=DMonGrassInterface(None),
                              title=_("Vector Digitizer - GRASS GIS"),
                              size=(850, 600))
            # this giface issue not solved yet, we must set mapframe aferwards
            self._giface._mapframe = self
            # load vector map
            mapLayer = self.GetMap().AddLayer(
                ltype='vector',
                name=vectorMap,
                command=['d.vect', 'map=%s' % vectorMap],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True)

            # switch toolbar
            self.AddToolbar('vdigit', fixed=True)

            # start editing
            self.toolbars['vdigit'].StartEditing(mapLayer)

    if not haveVDigit:
        grass.fatal(_("Vector digitizer not available. %s") % errorMsg)

    if not grass.find_file(name=options['map'],
                           element='vector',
                           mapset=grass.gisenv()['MAPSET'])['fullname']:
        if not flags['c']:
            grass.fatal(
                _("Vector map <%s> not found in current mapset. "
                  "New vector map can be created by providing '-c' flag.") %
                options['map'])
        else:
            grass.verbose(_("New vector map <%s> created") % options['map'])
            try:
                grass.run_command('v.edit',
                                  map=options['map'],
                                  tool='create',
                                  quiet=True)
            except CalledModuleError:
                grass.fatal(
                    _("Unable to create new vector map <%s>") % options['map'])

    # allow immediate rendering
    driver = UserSettings.Get(group='display', key='driver', subkey='type')
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

    app = wx.App()
    frame = VDigitMapFrame(options['map'])
    frame.Show()

    app.MainLoop()
Example #29
0
def main():
    gs.set_raise_on_error(False)

    options, flags = gs.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.render import Map
    from core.globalvar import ICONDIR
    from mapdisp.frame import MapPanel
    from gui_core.mapdisp import FrameMixin
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class RDigitMapDisplay(FrameMixin, MapPanel):
        """Map display for wrapping map panel with r.digit mathods and frame methods"""
        def __init__(
            self,
            parent,
            new_map=None,
            base_map=None,
            edit_map=None,
            map_type=None,
        ):
            MapPanel.__init__(self,
                              parent=parent,
                              Map=Map(),
                              giface=DMonGrassInterface(None))

            # set system icon
            parent.SetIcon(
                wx.Icon(os.path.join(ICONDIR, "grass_map.ico"),
                        wx.BITMAP_TYPE_ICO))

            # bindings
            parent.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

            # extend shortcuts and create frame accelerator table
            self.shortcuts_table.append(
                (self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11))
            self._initShortcuts()

            # this giface issue not solved yet, we must set mapframe afterwards
            self._giface._mapframe = self
            self._giface.mapCreated.connect(self.OnMapCreated)
            self._mapObj = self.GetMap()

            # load raster map
            self._addLayer(name=new_map if new_map else edit_map)

            # switch toolbar
            self.AddToolbar("rdigit", fixed=True)

            rdigit = self.toolbars["rdigit"]
            if new_map:
                rdigit._mapSelectionCombo.Unbind(wx.EVT_COMBOBOX)
                self.rdigit.SelectNewMap(
                    standalone=True,
                    mapName=new_map,
                    bgMap=base_map,
                    mapType=map_type,
                )
                rdigit._mapSelectionCombo.Bind(
                    wx.EVT_COMBOBOX,
                    rdigit.OnMapSelection,
                )
            else:
                rdigit._mapSelectionCombo.SetSelection(n=1)
                rdigit.OnMapSelection()
            # use Close instead of QuitRDigit for standalone tool
            self.rdigit.quitDigitizer.disconnect(self.QuitRDigit)
            self.rdigit.quitDigitizer.connect(lambda: self.Close())

            # add Map Display panel to Map Display frame
            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(self, proportion=1, flag=wx.EXPAND)
            parent.SetSizer(sizer)
            parent.Layout()

        def _addLayer(self, name, ltype="raster"):
            """Add layer into map

            :param str name: map name
            :param str ltype: layer type
            """
            mapLayer = self._mapObj.AddLayer(
                ltype=ltype,
                name=name,
                command=["d.rast", "map={}".format(name)],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True,
            )

        def OnMapCreated(self, name, ltype):
            """Add new created raster layer into map

            :param str name: map name
            :param str ltype: layer type
            """
            self._mapObj.Clean()
            self._addLayer(name=name, ltype=ltype)
            self.GetMapWindow().UpdateMap()

    kwargs = {
        "new_map": options["create"],
        "base_map": options["base"],
        "edit_map": options["edit"],
        "map_type": options["type"],
    }

    mapset = gs.gisenv()["MAPSET"]

    if kwargs["edit_map"]:
        edit_map = gs.find_file(
            name=kwargs["edit_map"],
            element="raster",
            mapset=mapset,
        )["fullname"]

        if not edit_map:
            gs.fatal(
                _(
                    "Raster map <{}> not found in current mapset.".format(
                        options["edit"], ), ), )
        else:
            kwargs["edit_map"] = edit_map
    else:
        if kwargs["base_map"]:
            base_map = gs.find_file(
                name=kwargs["base_map"],
                element="raster",
                mapset=mapset,
            )["fullname"]
            if not base_map:
                gs.fatal(
                    _(
                        "Base raster map <{}> not found in "
                        "current mapset.".format(options["base"], ), ), )
            kwargs["base_map"] = base_map

    # allow immediate rendering
    driver = UserSettings.Get(
        group="display",
        key="driver",
        subkey="type",
    )
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    app = wx.App()
    frame = wx.Frame(
        None,
        id=wx.ID_ANY,
        size=(850, 600),
        style=wx.DEFAULT_FRAME_STYLE,
        title=_("Raster Digitizer - GRASS GIS"),
    )
    frame = RDigitMapDisplay(parent=frame, **kwargs)
    frame.Show()

    app.MainLoop()