예제 #1
0
 def __init__(self, options):
     self._tmpxyz = grass.tempfile()
     self._xyzout = grass.tempfile()
     self._tmp = grass.tempfile()
     self._tmpcat = grass.tempfile()
     self.options = options
     self.region()
     pass
예제 #2
0
    def _saveToFile(self, fileName, fileType):
        """Creates composite image by rendering both images and
        pasting them into the new one.

        .. todo::
            specify size of the new image (problem is inaccurate scaling)
        .. todo::
            make dividing line width and color optional
        """
        w1 = self.splitter.GetWindow1()
        w2 = self.splitter.GetWindow2()
        lineWidth = 1
        # render to temporary files
        filename1 = grass.tempfile(False) + '1'
        filename2 = grass.tempfile(False) + '2'
        width, height = self.splitter.GetClientSize()
        if self._mode == 'swipe':
            x, y = w2.GetImageCoords()
            w1.SaveToFile(filename1, fileType, width, height)
            w2.SaveToFile(filename2, fileType, width, height)
        else:
            fw, fh = w1.GetClientSize()
            w1.SaveToFile(filename1, fileType, fw, fh)
            sw, sh = w2.GetClientSize()
            w2.SaveToFile(filename2, fileType, sw, sh)

        # create empty white image  - needed for line
        im = wx.EmptyImage(width, height)
        im.Replace(0, 0, 0, 255, 255, 255)

        # paste images
        if self._mode == 'swipe':
            if self.splitter.GetSplitMode() == wx.SPLIT_HORIZONTAL:
                im1 = wx.Image(filename1).GetSubImage((0, 0, width, -y))
                im.Paste(im1, 0, 0)
                im.Paste(wx.Image(filename2), -x, -y + lineWidth)
            else:
                im1 = wx.Image(filename1).GetSubImage((0, 0, -x, height))
                im.Paste(im1, 0, 0)
                im.Paste(wx.Image(filename2), -x + lineWidth, -y)
        else:
            if self.splitter.GetSplitMode() == wx.SPLIT_HORIZONTAL:
                im1 = wx.Image(filename1)
                im.Paste(im1, 0, 0)
                im.Paste(wx.Image(filename2), 0, fh + lineWidth)
            else:
                im1 = wx.Image(filename1)
                im.Paste(im1, 0, 0)
                im.Paste(wx.Image(filename2), fw + lineWidth, 0)
        im.SaveFile(fileName, fileType)

        # remove temporary files
        grass.try_remove(filename1)
        grass.try_remove(filename2)
예제 #3
0
def create_banks(cutline_pts, bank_dist, out_vect):
    """
    Use the two lists of cutline point locations, and distances along those cutlines
    To create points for the left and right bank locations
    """
    cl_cnt = len(cutline_pts)
    bk_cnt = len(bank_dist)
    if (cl_cnt <> bk_cnt):
        grass.fatal("Number of cutlines: %s, not equal to number of bank points: %s" % (cl_cnt, bk_cnt))
        sys.exit(0)

    tmp_coords = grass.tempfile()
    tmp_banks = grass.tempfile()
    proc=os.getpid()
    # tmp_line holds a temporary line vector for each single cutline
    # The locations in bank_dist will be used to create new points as bank points
    # and added to the bank points vector, tmp_pts
    tmp_line = "cutline_tmp_"+str(proc)
    tmp_pts = "bankpt_tmp_"+str(proc)

    grass.run_command('v.edit', map=out_vect, tool='create', type_='point',overwrite=True)

    for i in range(len(cutline_pts)):
        with open(tmp_coords,'w') as tmp:
            tmp.write("VERTI:\n")
            tmp.write("L 3 1\n")
            tmp.write(" "+cutline_pts[i][0][0]+" "+cutline_pts[i][0][1]+"\n" )
            tmp.write(" "+cutline_pts[i][1][0]+" "+cutline_pts[i][1][1]+"\n" )
            tmp.write(" "+cutline_pts[i][2][0]+" "+cutline_pts[i][2][1]+"\n" )
            tmp.write(" 1 1\n")
        tmp.close()
        # Create one cutline (from 3 points)
        grass.run_command('v.in.ascii',input_=tmp_coords, output=tmp_line, overwrite=True, format_='standard', quiet=True)

        # Now find the point locations at the bank dist distances along that line
        # Use the same list index, i, to get the points for the current cutline
        # and multiply fraction by 100 to create % distance along cutline
        with open(tmp_banks, 'w') as tmp:
            rule_line1 = "P 1 1\n"
            tmp.write("P 1 1 %s" % str(float(bank_dist[i][0])*100) + "%\n")
            tmp.write("P 2 1 %s" % str(float(bank_dist[i][1])*100) + "%\n")
        tmp.close()
        # Create a new point vector, and append to existing bank points
        grass.run_command('v.segment', input_=tmp_line, output=tmp_pts, rules=tmp_banks, overwrite=True, quiet=True)
        grass.run_command('v.patch', input_=tmp_pts, output=out_vect, overwrite=True, flags='a', quiet=True )

    # Cleanup
    os.unlink(tmp_coords)
    os.unlink(tmp_banks)
    grass.run_command('g.remove', type_='vect', name=tmp_line, flags='f')
    grass.run_command('g.remove', type_='vect', name=tmp_pts, flags='f')
예제 #4
0
def main():
    try:
        from owslib.ogcapi.coverages import Coverages
    except:
        grass.fatal(
            _("OSWLib was not found. Install OSWLib (http://geopython.github.com/OWSLib/)."
              ))

    feats = Coverages(options["url"])
    collections = feats.coverages()
    if flags["l"]:
        for coll in collections:
            print("{}".format(coll))
        return
    if not options["layer"]:
        grass.fatal(
            _("Required parameter <layer> not set: (Name for input vector map layer)"
              ))
    elif options["layer"] not in collections:
        grass.fatal(_("Layer {} is not a Coverage layer"))

    if not options["output"]:
        grass.fatal(
            _("Required parameter <output> not set: (Name for output vector map)"
              ))
    try:
        layer = feats.coverage(options["layer"])
    except Exception as e:
        grass.fatal(
            _("Problem retrieving data from the server. The error was: {}".
              format(e)))
    tmpfile = grass.tempfile()
    with open(tmpfile, "wb") as f:
        f.write(layer.getbuffer())
    grass.run_command("r.import", input=tmpfile, output=options["output"])
예제 #5
0
def main():
    global tmp
    tmp = grass.tempfile()

    vector = options['map']
    layer = options['layer']
    column = options['column']
    where = options['where']
    perc = options['percentile']
    extend = flags['e']
    shellstyle = flags['g']

    fi = grass.vector_db(vector, stderr=nuldev)[int(layer)]
    table = fi['table']
    database = fi['database']
    driver = fi['driver']

    passflags = None
    if flags['e']:
        passflags = 'e'
    if flags['g']:
        if not passflags:
            passflags = 'g'
        else:
            passflags = passflags + 'g'

    grass.run_command('db.univar',
                      table=table,
                      column=column,
                      database=database,
                      driver=driver,
                      perc=perc,
                      where=where,
                      flags=passflags)
예제 #6
0
def main():

    # Get the options
    input = options["input"]
    output = options["output"]
    method = options["method"]
    order = options["order"]
    where = options["where"]
    add_time = flags["t"]
    nulls = flags["n"]

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

    sp = tgis.open_old_stds(input, "strds")

    rows = sp.get_registered_maps("id", where, order, None)

    if rows:
        # Create the r.series input file
        filename = grass.tempfile(True)
        file = open(filename, 'w')

        for row in rows:
            string = "%s\n" % (row["id"])
            file.write(string)

        file.close()

        flag = ""
        if len(rows) > 1000:
            grass.warning(_("Processing over 1000 maps: activating -z flag of r.series which slows down processing"))
            flag += "z"
        if nulls:
            flag += "n"

        try:
            grass.run_command("r.series", flags=flag, file=filename,
                              output=output, overwrite=grass.overwrite(),
                              method=method)
        except CalledModuleError:
            grass.fatal(_("%s failed. Check above error messages.") % 'r.series')

        if not add_time:
            # Create the time range for the output map
            if output.find("@") >= 0:
                id = output
            else:
                mapset = grass.gisenv()["MAPSET"]
                id = output + "@" + mapset

            map = sp.get_new_map_instance(id)
            map.load()
            map.set_temporal_extent(sp.get_temporal_extent())

            # Register the map in the temporal database
            if map.is_in_db():
                map.update_all()
            else:
                map.insert()
예제 #7
0
    def OnRun(self, event):
        """Run Python script"""
        if self.running:
            # ignore when already running
            return

        if not self.filename:
            self.filename = gscript.tempfile()
            self.tempfile = True
            try:
                fd = open(self.filename, "w")
                fd.write(self.body.GetText())
            except IOError as e:
                GError(_("Unable to launch Python script. %s") % e,
                       parent=self.guiparent)
                return
            finally:
                fd.close()
                mode = stat.S_IMODE(os.lstat(self.filename)[stat.ST_MODE])
                os.chmod(self.filename, mode | stat.S_IXUSR)
        else:
            fd = open(self.filename, "w")
            try:
                fd.write(self.body.GetText())
            finally:
                fd.close()
            # set executable file
            # (not sure if needed every time but useful for opened files)
            os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)

        # TODO: add overwrite to toolbar, needs env in GConsole
        # run in console as other modules, avoid Python shell which
        # carries variables over to the next execution
        self.giface.RunCmd([fd.name], skipInterface=True, onDone=self.OnDone)
        self.running = True
예제 #8
0
def string_to_rules(string):
    """Converts a string to a file for input as a GRASS Rules File"""
    tmp = gs.tempfile()
    f = open("%s" % (tmp), "wt")
    f.write(string)
    f.close()
    return tmp
예제 #9
0
    def AddScattPlot(self, cat_id, scatt_id):

        if cat_id not in self.cats:
            return -1

        if scatt_id in self.cats[cat_id]:
            return 0

        b_i = self.GetBandsInfo(scatt_id)

        shape = (
            b_i['b2']['max'] -
            b_i['b2']['min'] +
            1,
            b_i['b1']['max'] -
            b_i['b1']['min'] +
            1)

        np_vals = np.memmap(
            grass.tempfile(),
            dtype=self.dtype,
            mode='w+',
            shape=shape)

        self.cats[cat_id][scatt_id] = {'np_vals': np_vals}

        return 1
예제 #10
0
파일: v.db.univar.py 프로젝트: caomw/grass
def main():
    global tmp
    tmp = grass.tempfile()

    vector = options['map']
    layer = options['layer']
    column = options['column']
    where = options['where']
    perc = options['percentile']
    extend = flags['e']
    shellstyle = flags['g']

    
    fi = grass.vector_db(vector, stderr = nuldev)[int(layer)]
    table = fi['table']
    database = fi['database']
    driver = fi['driver']
    
    passflags = None
    if flags['e']:
	passflags = 'e'
    if flags['g']:
	if not passflags:
	    passflags = 'g'
	else:
	    passflags = passflags + 'g'
    
    grass.run_command('db.univar', table = table, column = column, 
                      database = database, driver = driver,
		      perc = perc, where = where, flags = passflags)
예제 #11
0
def createTMPlocation(epsg=4326):
    SRCGISRC = grass.tempfile()
    TMPLOC = "temp_import_location_" + str(os.getpid())
    f = open(SRCGISRC, "w")
    f.write("MAPSET: PERMANENT\n")
    f.write("GISDBASE: %s\n" % GISDBASE)
    f.write("LOCATION_NAME: %s\n" % TMPLOC)
    f.write("GUI: text\n")
    f.close()

    # create temp location from input without import
    grass.verbose(_("Creating temporary location with EPSG:%d...") % epsg)
    grass.run_command("g.proj", flags="c", epsg=epsg, location=TMPLOC, quiet=True)

    # switch to temp location
    os.environ["GISRC"] = str(SRCGISRC)
    proj = grass.parse_command("g.proj", flags="g")
    if "epsg" in proj:
        currepsg = proj["epsg"]
    else:
        currepsg = proj["srid"].split("EPSG:")[1]

    if currepsg != str(epsg):
        grass.fatal("Creation of temporary location failed!")

    return SRCGISRC, TMPLOC
예제 #12
0
    def OnRun(self, event):
        """Run Python script"""
        if not self.filename:
            self.filename = gscript.tempfile() + ".py"
            self.tempfile = True
            file_is_written = self._writeFile(
                file_path=self.filename,
                content=self.body.GetText(),
                additional_err_message=" Unable to launch Python script.",
            )
            if file_is_written:
                mode = stat.S_IMODE(os.lstat(self.filename)[stat.ST_MODE])
                os.chmod(self.filename, mode | stat.S_IXUSR)
        else:
            # always save automatically before running
            file_is_written = self._writeFile(
                file_path=self.filename,
                content=self.body.GetText(),
                additional_err_message=" Unable to launch Python script.",
            )
            if file_is_written:
                # set executable file
                # (not sure if needed every time but useful for opened files)
                os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)

        if file_is_written:
            # run in console as other modules, avoid Python shell which
            # carries variables over to the next execution
            env = os.environ.copy()
            if self.overwrite:
                env["GRASS_OVERWRITE"] = "1"
            cmd = [self.filename]
            if self.parameters:
                cmd.extend(self.parameters)
            self.giface.RunCmd(cmd, env=env)
예제 #13
0
def createTMPlocation(epsg=4326):
    SRCGISRC = grass.tempfile()
    TMPLOC = 'temp_import_location_' + str(os.getpid())
    f = open(SRCGISRC, 'w')
    f.write('MAPSET: PERMANENT\n')
    f.write('GISDBASE: %s\n' % GISDBASE)
    f.write('LOCATION_NAME: %s\n' % TMPLOC)
    f.write('GUI: text\n')
    f.close()

    # create temp location from input without import
    grass.verbose(_("Creating temporary location with EPSG:%d...") % epsg)
    grass.run_command('g.proj',
                      flags='c',
                      epsg=epsg,
                      location=TMPLOC,
                      quiet=True)

    # switch to temp location
    os.environ['GISRC'] = str(SRCGISRC)
    proj = grass.parse_command('g.proj', flags='g')
    if 'epsg' in proj:
        currepsg = proj['epsg']
    else:
        currepsg = proj['srid'].split('EPSG:')[1]

    currepsg = ":".join(srid.split(":")[-1:])
    if currepsg != str(epsg):
        grass.fatal("Creation of temporary location failed!")

    return SRCGISRC, TMPLOC
예제 #14
0
def create_pointmap(units, groups, groupsets, pointmapname, overwrite=True):
    """Transform info from json files into a GRASS GIS point map."""
    tempfile = grass.tempfile()
    groupsnotfound = []
    groupsetsnotfound = []
    with open(tempfile, 'w') as fout:
        for unit in units.keys():
            output = []
            output.append(str(unit))
            for v in units[unit]:
                output.append(str(v))
            if unit in groups:
                groupid = groups[unit]['groupid']
                groupname = groups[unit]['groupname']
            else:
                # if groupid not in groupsnotfound:
                #     groupsnotfound.append(groupid)
                groupid = ''
                groupname = ''
            output.append(str(groupid))
            output.append(str(groupname))

            if groupid in groupsets:
                groupsetid = groupsets[groupid]['groupsetid']
                groupsetname = groupsets[groupid]['groupsetname']
            else:
                # if groupsetid not in groupsetsnotfound:
                #     groupsetsnotfound.append(groupsetid)
                groupsetid = ''
                groupsetname = ''
            output.append(str(groupsetid))
            output.append(str(groupsetname))

            output_string = ','.join(output)
            fout.write(output_string)
            fout.write('\n')

    if groupsnotfound:
        warning_message = "Could not find the following groups:\n"
        for group in groupsnotfound:
            warning_message += "%s\n" % group
        grass.warning(warning_message)
    if groupsetsnotfound:
        warning_message = "Could not find the following groupsets:\n"
        for groupset in groupsetsnotfound:
            warning_message += "%s\n" % groupset
        grass.warning(warning_message)

    columns = 'id varchar, x double precision, y double precision, name varchar, shortName varchar, groupid varchar, groupname varchar, groupsetid varchar, groupsetname varchar'
    grass.run_command('v.in.ascii',
                      output=pointmapname,
                      input_=tempfile,
                      x=2,
                      y=3,
                      columns=columns,
                      separator='comma',
                      overwrite=overwrite,
                      quiet=True)
예제 #15
0
def main():
    # lazy imports
    import grass.temporal as tgis

    # Get the options
    _input = options["input"]
    output = options["output"]
    source = options["source"]
    target = options["target"]

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

    # specs of input strds
    sp = tgis.open_old_stds(input, "strds", dbif)
    ttype, stype, title, descr = sp.get_initial_values()
    dbif.close()

    # t.rast.list with columns name, start date, band reference
    rlist = grass.read_command("t.rast.list",
                               input=_input,
                               columns="name,start_time,band_reference",
                               flags="u")

    rlistfile = grass.tempfile(create=False)
    fd = open(rlistfile, "w")

    if source:
        source = source.split(',')
    target = target.split(',')

    # modify band names
    for rmap in rlist.splitlines():
        name, start_time, band_reference = rmap.split('|')
        if source:
            if band_reference in source:
                idx = source.index(band_reference)
                band_reference = target[idx]
        else:
            band_reference = target[0]
        fd.write("%s|%s|%s\n" % (name, start_time, band_reference))

    fd.close()

    # t.create, use specs of input strds
    grass.run_command('t.create',
                      type='strds',
                      output=output,
                      temporaltype=ttype,
                      semantictype=stype,
                      title=title,
                      description=descr)

    # t.register to create new strds
    grass.run_command('t.register', input=output, file=rlistfile)
예제 #16
0
def tmp_map_name(name):
    """
    Return a temporary map name, for example:

    tmp_avg_lse = tmp + '.avg_lse'
    """
    temporary_file = grass.tempfile()
    tmp = "tmp." + grass.basename(temporary_file)  # use its basename
    return tmp + '.' + str(name)
예제 #17
0
def string_to_rules(string):
    # Converts a string to a file for input as a GRASS Rules File

    tmp = gs.tempfile()
    f = open('%s' % (tmp), 'wt')
    f.write(string)
    f.close()

    return tmp
def tmp_map_name(name):
    """
    Return a temporary map name, for example:

    tmp_avg_lse = tmp + '.avg_lse'
    """
    temporary_file = grass.tempfile()
    tmp = "tmp." + grass.basename(temporary_file)  # use its basename
    return tmp + '.' + str(name)
예제 #19
0
    def _reprojectMap(self):
        """!Reproject data  using gdalwarp if needed
        """
        # reprojection of raster
        if self.proj_srs != self.proj_location:  # TODO: do it better
            grass.message(_("Reprojecting raster..."))
            self.temp_warpmap = grass.tempfile()

            if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
                nuldev = file(os.devnull, 'w+')
            else:
                nuldev = None

            if self.params['method'] == "nearest":
                gdal_method = "near"
            elif self.params['method'] == "linear":
                gdal_method = "bilinear"
            else:
                gdal_method = self.params['method']

            #"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
            # RGB rasters - alpha layer is added for cropping edges of projected raster
            try:
                if self.temp_map_bands_num == 3:
                    ps = grass.Popen([
                        'gdalwarp', '-s_srs',
                        '%s' % self.proj_srs, '-t_srs',
                        '%s' % self.proj_location, '-r', gdal_method,
                        '-dstalpha', self.temp_map, self.temp_warpmap
                    ],
                                     stdout=nuldev)
                # RGBA rasters
                else:
                    ps = grass.Popen([
                        'gdalwarp', '-s_srs',
                        '%s' % self.proj_srs, '-t_srs',
                        '%s' % self.proj_location, '-r', gdal_method,
                        self.temp_map, self.temp_warpmap
                    ],
                                     stdout=nuldev)
                ps.wait()
            except OSError as e:
                grass.fatal('%s \nThis can be caused by missing %s utility. ' %
                            (e, 'gdalwarp'))

            if nuldev:
                nuldev.close()

            if ps.returncode != 0:
                grass.fatal(_('%s failed') % 'gdalwarp')
            grass.try_remove(self.temp_map)
        # raster projection is same as projection of location
        else:
            self.temp_warpmap = self.temp_map
            self.temp_files_to_cleanup.remove(self.temp_map)

        return self.temp_warpmap
예제 #20
0
def main():

    # Get the options
    input = options["input"]
    output = options["output"]
    method = options["method"]
    order = options["order"]
    where = options["where"]
    add_time = flags["t"]
    nulls = flags["n"]

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

    sp = tgis.open_old_stds(input, "strds")

    rows = sp.get_registered_maps("id", where, order, None)

    if rows:
        # Create the r.series input file
        filename = grass.tempfile(True)
        file = open(filename, 'w')

        for row in rows:
            string = "%s\n" % (row["id"])
            file.write(string)

        file.close()

        flag = "z"
        if nulls:
            flag += "n"

        ret = grass.run_command("r.series",
                                flags=flag,
                                file=filename,
                                output=output,
                                overwrite=grass.overwrite(),
                                method=method)

        if ret == 0 and not add_time:
            # Create the time range for the output map
            if output.find("@") >= 0:
                id = output
            else:
                mapset = grass.gisenv()["MAPSET"]
                id = output + "@" + mapset

            map = sp.get_new_map_instance(id)
            map.load()
            map.set_temporal_extent(sp.get_temporal_extent())

            # Register the map in the temporal database
            if map.is_in_db():
                map.update_all()
            else:
                map.insert()
예제 #21
0
 def map_timestamps(directory, bands):
     tmpfile = grass.tempfile()
     mtl = process_mtl(directory)
     with open(tmpfile, 'w') as f:
         for band in bands:
             basename = band[band.find('LT'):].split('_')[0]
             starttime = datetime.datetime.strptime(mtl[basename]['date'], '%Y-%m-%d %H:%M:%S')
             endtime = starttime + datetime.timedelta(seconds=1)
             f.write('{}|{}|{}{}'.format(band, starttime, endtime, os.linesep))
     return tmpfile
예제 #22
0
def write_segarcdefs(lineinfo, maxcat):

    filename = gscript.tempfile()
    with open(filename, 'w') as fout:
        for arccat in lineinfo:
            for cat in range(1, maxcat):
                pointcat = arccat * 10000 + cat
                fout.write("%d %d %d\n" % (arccat, pointcat, pointcat + 1))

    return filename
예제 #23
0
    def __init__(
        self,
        parent,
        giface,
        layer,
        ws_cap_files,
        cmd,
        id=wx.ID_ANY,
        style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
        **kwargs,
    ):
        """
        :param giface: grass interface
        :param layer: layer tree item
        :param ws_cap_files: dict web service('WMS_1.1.1', 'WMS_1.3.0',
        'WMTS', 'OnEarth') : cap file path cap files, which will be parsed
        :param cmd: cmd to which dialog widgets will be initialized if
        it is possible (cmp parameters exists in parsed web service cap_file)
        """

        WSDialogBase.__init__(
            self,
            parent,
            id=wx.ID_ANY,
            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
            **kwargs,
        )

        self.SetTitle(_("Web service layer properties"))

        self.layer = layer
        self.giface = giface

        # after web service panels are connected, set dialog widgets
        # according to cmd in this variable (if it is not None)
        self.cmd_to_set = None

        # store data needed for reverting
        self.revert_ws_cap_files = {}
        self.revert_cmd = cmd

        ws_cap = self._getWSfromCmd(cmd)
        for ws in six.iterkeys(self.ws_panels):
            # cap file used in cmd will be deleted, thnaks to the dialogs
            # destructor
            if ws == ws_cap and "capfile" in cmd[1]:
                self.revert_ws_cap_files[ws] = cmd[1]["capfile"]
                del ws_cap_files[ws]
            else:
                self.revert_ws_cap_files[ws] = grass.tempfile()

        self._setRevertCapFiles(ws_cap_files)

        self.LoadCapFiles(ws_cap_files=self.revert_ws_cap_files, cmd=cmd)
        self.btn_ok.SetDefault()
예제 #24
0
    def mkstreams(self):
        '''Create minimal stream network reaching all subbasins and with nice main streams'''
        # get max accumulation and cell count for each subbasin
        rsmaxaccum = gread('r.stats', input='maxaccum__', flags='lcn')
        rsmaxaccum = np.array(rsmaxaccum.split(), dtype=float).reshape((-1, 3)).astype(int)
        subbasinIDs = rsmaxaccum[:, 0]
        maxaccum = rsmaxaccum[:, 1]
        # cellcounts must not be larger than maxaccum (may happen in subbasins with more than 1 outlet)
        cellcounts = np.min([rsmaxaccum[:, 2], maxaccum], axis=0)
        # calculate optima accumulation for nice headwater mainstreams
        accr = grass.parse_command('r.info', map=self.accumulation, flags='g')
        minaccum = np.int32(round(float(self.minmainstreams)*1e6 /
                            (float(accr['nsres'])*float(accr['ewres']))))
        minaccum = np.ones_like(maxaccum) * minaccum
        optiaccum   = np.min([maxaccum-np.int32(cellcounts*0.1), minaccum], axis=0)
        # check incoming subbasins maxaccum and take the smallest accumulation to update optiaccum
        subnext     = readSubNxtID(self.outlets)
        optiaccum   = dict(zip(subbasinIDs,optiaccum))
        maxaccum    = dict(zip(subbasinIDs,maxaccum))
        for sn in np.unique(subnext['nextID']):
            if sn < 0: continue
            for sb in subnext[subnext['nextID']==sn]['subbasinID']:
                optiaccum[sn] = min(optiaccum[sn],maxaccum[sb]-1)
        # make raster
        tempf = grass.tempfile()
        np.savetxt(tempf,optiaccum.items(),fmt='%i=%i')
        grass.run_command('r.reclass',input='maxaccum__',output='optiaccum__',
                          rules=tempf,quiet=True)
        # get accumulation and make lines
        grass.mapcalc("{0}__unthin=if({1} > {2},{1},null())".format(self.mainstreams,
                      self.accumulation,'optiaccum__'),overwrite=True)

        # make sure all pixels between outlets and inlets are included
        #grun('v.to.rast',input=self.outletinletlines,output='routingnet__rast',
        #     use='val',type='line',quiet=True)
        #grass.mapcalc("{0}=if(isnull({0})&~isnull({1}),{2},{0})".format(self.mainstreams,
        #              'routingnet__rast',self.accumulation),overwrite=True)
        grun('r.thin', input=self.mainstreams+'__unthin', output=self.mainstreams, overwrite=True, quiet=True) # may exclude outlet/inlet points

        # use predefined streams for subbasins that have them
        if 'streams' in self.options:
            grun('v.to.rast',input=self.streams,output='stream__rast',
             use='val',type='line',val=1,quiet=True)
            grun('r.thin', input='stream__rast', output='stream__rast__thin',
                 overwrite=True, quiet=True)
            grun('r.stats.zonal',base=self.subbasinrast,cover='stream__rast__thin',
                 method='sum',output='n__streams__subbasins',quiet=True,overwrite=True)
            # get subbasins that have at least x cells of streams
            grass.mapcalc('{0}=if(n__streams__subbasins>10,{1},{0})'.format(self.mainstreams,'stream__rast__thin'),
                            overwrite=True)
        # make final vector
        grun('r.to.vect', input=self.mainstreams, output=self.mainstreams,
             type='line',quiet=True)
        return
예제 #25
0
def main():

    # Get the options
    input = options["input"]
    output = options["output"]
    method = options["method"]
    order = options["order"]
    where = options["where"]
    add_time = flags["t"]
    nulls = flags["n"]

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

    sp = tgis.open_old_stds(input, "strds")

    rows = sp.get_registered_maps("id", where, order, None)

    if rows:
        # Create the r.series input file
        filename = grass.tempfile(True)
        file = open(filename, 'w')

        for row in rows:
            string = "%s\n" % (row["id"])
            file.write(string)

        file.close()

        flag = "z"
        if nulls:
            flag += "n"

        ret = grass.run_command("r.series", flags=flag, file=filename,
                                output=output, overwrite=grass.overwrite(),
                                method=method)

        if ret == 0 and not add_time:
            # Create the time range for the output map
            if output.find("@") >= 0:
                id = output
            else:
                mapset = grass.gisenv()["MAPSET"]
                id = output + "@" + mapset

            map = sp.get_new_map_instance(id)
            map.load()
            map.set_temporal_extent(sp.get_temporal_extent())

            # Register the map in the temporal database
            if map.is_in_db():
                map.update_all()
            else:
                map.insert()
예제 #26
0
def main(rinput, background, output, method):
    if '@' in rinput:
        rinput = rinput.split('@')[0]
    suffix = '_' + os.path.basename(gscript.tempfile(False))
    tmpname = rinput + suffix
    gscript.run_command('g.copy', raster=[rinput, tmpname])
    TMPRAST.append(tmpname)
    gscript.run_command('r.colors', map=tmpname, color='grey')

    reg = gscript.region()
    width = reg['cols']
    height = reg['rows']

    fg_out = os.path.join(TMPDIR, 'foreground.png')
    bg_out = os.path.join(TMPDIR, 'background.png')
    intensity_tmp = os.path.join(TMPDIR, 'intensity.png')
    gscript.run_command('d.mon', start='cairo', output=fg_out,
                        width=width, height=height, bgcolor='black')
    gscript.run_command('d.rast', map=rinput)
    gscript.run_command('d.mon', stop='cairo')

    # background
    gscript.run_command('d.mon', start='cairo', output=bg_out,
                        width=width, height=height)
    gscript.run_command('d.rast', map=background)
    gscript.run_command('d.mon', stop='cairo')

    # greyscale
    gscript.run_command('d.mon', start='cairo', output=intensity_tmp,
                        width=width, height=height)
    gscript.run_command('d.rast', map=tmpname)
    gscript.run_command('d.mon', stop='cairo')

    # put together with transparency
    foreground = Image.open(fg_out)
    background = Image.open(bg_out)
    intensity = Image.open(intensity_tmp)

    foreground = foreground.convert("RGBA")
    data_f = foreground.getdata()
    data_i = intensity.getdata()
    newData = []
    for i in range(len(data_f)):
        intens = data_i[i][0]
        if intens == 0:
            newData.append((data_f[i][0], data_f[i][1], data_f[i][2], 0))
        else:
            newData.append((data_f[i][0], data_f[i][1], data_f[i][2],
                            scale(0, 255, intens, method)))
    foreground.putdata(newData)
    background.paste(foreground, (0, 0), foreground)
    background.save(output)
예제 #27
0
    def _reprojectMap(self): 
        """!Reproject data  using gdalwarp if needed
        """
        # reprojection of raster
        if self.proj_srs != self.proj_location: # TODO: do it better
            grass.message(_("Reprojecting raster..."))
            self.temp_warpmap = grass.tempfile()
            
            if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
                nuldev = file(os.devnull, 'w+')
            else:
                nuldev = None

            if self.params['method'] == "nearest":
                gdal_method = "near"
            elif self.params['method'] == "linear":
                gdal_method = "bilinear"
            else:
                gdal_method = self.params['method']
            
            #"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
            # RGB rasters - alpha layer is added for cropping edges of projected raster
            try:
                if self.temp_map_bands_num == 3:
                    ps = grass.Popen(['gdalwarp',
                                      '-s_srs', '%s' % self.proj_srs,
                                      '-t_srs', '%s' % self.proj_location,
                                      '-r', gdal_method, '-dstalpha',
                                      self.temp_map, self.temp_warpmap], stdout = nuldev)
                # RGBA rasters
                else:
                    ps = grass.Popen(['gdalwarp',
                                      '-s_srs', '%s' % self.proj_srs,
                                      '-t_srs', '%s' % self.proj_location,
                                      '-r', gdal_method,
                                      self.temp_map, self.temp_warpmap], stdout = nuldev)
                ps.wait()
            except OSError as e:
                grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
            
            if nuldev:
                nuldev.close()
            
            if ps.returncode != 0:
                grass.fatal(_('%s failed') % 'gdalwarp')
            grass.try_remove(self.temp_map)
        # raster projection is same as projection of location
        else:
            self.temp_warpmap = self.temp_map
            self.temp_files_to_cleanup.remove(self.temp_map)

        return self.temp_warpmap
예제 #28
0
    def save_footprints(self, map_name):
        if self._products_df_sorted is None:
            return

        try:
            from osgeo import ogr, osr
        except ImportError as e:
            gs.fatal(
                _("Option <footprints> requires GDAL library: {}").format(e))

        gs.message(_("Writing footprints into <{}>...").format(map_name))
        driver = ogr.GetDriverByName("GPKG")
        tmp_name = gs.tempfile() + '.gpkg'
        data_source = driver.CreateDataSource(tmp_name)

        srs = osr.SpatialReference()
        srs.ImportFromEPSG(4326)

        layer = data_source.CreateLayer(str(map_name), srs, ogr.wkbPolygon)

        # attributes
        attrs = OrderedDict([("uuid", ogr.OFTString),
                             ("ingestiondate", ogr.OFTString),
                             ("cloudcoverpercentage", ogr.OFTInteger),
                             ("producttype", ogr.OFTString),
                             ("identifier", ogr.OFTString)])
        for key in attrs.keys():
            field = ogr.FieldDefn(key, attrs[key])
            layer.CreateField(field)

        # features
        for idx in range(len(self._products_df_sorted['uuid'])):
            wkt = self._products_df_sorted['footprint'][idx]
            feature = ogr.Feature(layer.GetLayerDefn())
            feature.SetGeometry(ogr.CreateGeometryFromWkt(wkt))
            for key in attrs.keys():
                if key == 'ingestiondate':
                    value = self._products_df_sorted[key][idx].strftime(
                        "%Y-%m-%dT%H:%M:%SZ")
                else:
                    value = self._products_df_sorted[key][idx]
                feature.SetField(key, value)
            layer.CreateFeature(feature)
            feature = None

        data_source = None

        gs.run_command('v.import',
                       input=tmp_name,
                       output=map_name,
                       layer=map_name,
                       quiet=True)
예제 #29
0
    def OnAddLayer(self, event):
        """Add web service layer."""
        # add layer
        if self.active_ws_panel is None:
            return

        lcmd = self.active_ws_panel.CreateCmd()
        if not lcmd:
            return None

        # TODO: It is not clear how to do GetOptData in giface
        # knowing what GetOptData is doing might help
        # (maybe Get... is not the right name)
        # please fix giface if you know
        # tree -> giface
        # GetLayerTree -> GetLayerList
        # AddLayer -> AddLayer (but tree ones returns some layer,
        # giface ones nothing)
        # GetLayerInfo -> Layer object can by used instead
        # GetOptData -> unknown
        ltree = self.giface.GetLayerTree()

        active_ws = self.active_ws_panel.GetWebService()
        if "WMS" not in active_ws:
            cap_file = self.active_ws_panel.GetCapFile()
            cmd_cap_file = grass.tempfile()
            shutil.copyfile(cap_file, cmd_cap_file)
            lcmd.append("capfile=" + cmd_cap_file)

        layer = ltree.AddLayer(
            ltype="wms",
            lname=self.active_ws_panel.GetOutputLayerName(),
            lchecked=True,
            lcmd=lcmd,
        )

        ws_cap_files = self._getCapFiles()
        # create properties dialog
        cmd_list = ltree.GetLayerInfo(layer, "cmd")
        cmd = cmdlist_to_tuple(cmd_list)

        prop_win = WSPropertiesDialog(
            parent=self.parent,
            giface=self.giface,
            id=wx.ID_ANY,
            layer=layer,
            ws_cap_files=ws_cap_files,
            cmd=cmd,
        )

        prop_win.Hide()
        ltree.GetOptData(dcmd=None, layer=layer, params=None, propwin=prop_win)
예제 #30
0
def getEnvironment(gisdbase, location, mapset):
    """Creates environment to be passed in run_command for example.
    Returns tuple with temporary file path and the environment. The user
    of this function is responsile for deleting the file."""
    tmp_gisrc_file = gscript.tempfile()
    with open(tmp_gisrc_file, 'w') as f:
        f.write('MAPSET: {mapset}\n'.format(mapset=mapset))
        f.write('GISDBASE: {g}\n'.format(g=gisdbase))
        f.write('LOCATION_NAME: {l}\n'.format(l=location))
        f.write('GUI: text\n')
    env = os.environ.copy()
    env['GISRC'] = tmp_gisrc_file
    return tmp_gisrc_file, env
예제 #31
0
def getEnvironment(gisdbase, location, mapset):
    """Creates environment to be passed in run_command for example.
    Returns tuple with temporary file path and the environment. The user
    of this function is responsile for deleting the file."""
    tmp_gisrc_file = gscript.tempfile()
    with open(tmp_gisrc_file, 'w') as f:
        f.write('MAPSET: {mapset}\n'.format(mapset=mapset))
        f.write('GISDBASE: {g}\n'.format(g=gisdbase))
        f.write('LOCATION_NAME: {l}\n'.format(l=location))
        f.write('GUI: text\n')
    env = os.environ.copy()
    env['GISRC'] = tmp_gisrc_file
    return tmp_gisrc_file, env
예제 #32
0
파일: p.mon.py 프로젝트: imincik/pkg-grass
def main():
    start = options["start"]
#    select = options["select"]
#    stop = options["stop"]
#    unlock = options["unlock"]

    # create the command file
    command_file = grass.tempfile()
    os.system("g.gisenv set=GRASS_PYCMDFILE=%s" % command_file)

    if start != "":
        os.spawnlp(os.P_NOWAIT, os.environ["GRASS_PYTHON"], os.environ["GRASS_PYTHON"], "%s/etc/wxpython/gui_core/mapdisp.py" % os.environ["GISBASE"], start, command_file)
        return
예제 #33
0
def create_water_surface(left_pairs, right_pairs, out_vect):
    """
	Use the two lists of coordinate pairs to create a text file for import into v.in.ascii
	The left coords first, then the right coords starting from the end, 
	in order to make a closed polygon. Starting upstream along the left side of the water surface, 
	to the end of the reach, then back to the start along the right side
	Add the first point of the left pairs a second time to complete the boundary
	"""
    tmp_coords = grass.tempfile()
    proc = os.getpid()
    tmp_vect = out_vect + "_tmp_" + str(proc)

    # How many total points in the boundary: all the right side+ left side +1
    # to allow for the first point a 2nd time to close boundary
    ttl_pts = len(left_pairs) + len(right_pairs) + 1
    grass.message(
        "Total number of vertices to be added to water surface polygon: %s" %
        ttl_pts)

    with open(tmp_coords, 'w') as tmp:
        # Write coords in the standard ASCII file format for a grass boundary
        # Loop thru the left coord pairs, then in reverse thru the right pairs
        tmp.write("VERTI:\n")
        tmp.write("B %s\n" % ttl_pts)
        for i in range(len(left_pairs)):
            tmp.write(" " + left_pairs[i][0] + " " + left_pairs[i][1] + "\n")

        for j in range(len(right_pairs) - 1, -1, -1):
            tmp.write(" " + right_pairs[j][0] + " " + right_pairs[j][1] + "\n")

# Finally add the first point of the left pairs again to close the boundary
        tmp.write(" " + left_pairs[0][0] + " " + left_pairs[0][1] + "\n")

    tmp.close()

    # Now feed into v.in.ascii and also run v.centroids to make a centroid for the polygon
    grass.run_command('v.in.ascii',
                      input=tmp_coords,
                      output=tmp_vect,
                      format="standard",
                      quiet=True,
                      overwrite=True)
    grass.run_command('v.centroids',
                      input=tmp_vect,
                      output=out_vect,
                      quiet=True,
                      overwrite=True)
    grass.message("Polygon vector: %s has been created" % (out_vect))
    grass.message("Cleaning up tmp files %s,%s" % (str(tmp), str(tmp_vect)))
    grass.run_command('g.remove', type='vect', name=tmp_vect, flags="f")
    os.unlink(tmp_coords)
예제 #34
0
def create_stations_schematic(invect, outvect, spacing, cats):
	""" 
	Loop thru all river reaches, and for each reach
	begin at the downstream end of the reach, 
	and create a series of points at each "spacing" interval. 
	Put these points into an ASCII file, formatted for v.segment
	and run v.segment to create a line vector of stations along the original river
	"""
	# Create temp file for Points
	tmp_stations = grass.tempfile()
	tmp = open(tmp_stations,'w')
	# Keep track of how many total river stations were marked
	station_cnt=0
	# cats is a dict with cat as key and reach length as value
	for c in cats:
		reach_len=float(cats[c])
		# Begins at the downstream of each river reach, and work upstream
		# Each iteration creates a line segment "spacing" meters upstream of the previous
		# Use the same line id for each segment in the reach
		# The first station is postioned spacing/2 from the downstream end of the read
		station=reach_len-(spacing/2)
		pt=0
		# Loop until the remaining length < spacing/2
		while station>=spacing/2:
			# concatenate (as strings) a point iterator with the line cat value to create a point cat 
			pt+=1
			pt_id=c + "%03d" % pt
			st1=str(math.floor(station))
			tmp.write("P "+pt_id+" "+c+" "+st1+"\n")
			grass.message("Adding point: %s at position:%s" % (pt_id, st1))
			station -= spacing
			station_cnt+=1

	tmp.close()
	
	grass.run_command('v.segment',input=invect, output=outvect, rules=tmp_stations, overwrite=True, quiet=True)
	os.unlink(tmp_stations)

	# Add coordinates to each station
	grass.run_command('v.db.addtable', map=outvect, quiet=True)
	grass.run_command('v.db.addcolumn', map=outvect, columns="x DOUBLE PRECISION, y DOUBLE PRECISION", quiet=True)
	grass.run_command('v.to.db', map=outvect, option="coor", columns="x,y", quiet=True)
	
	# Also get the reach id for each station
	# The point ids are created from line (reach) cats + three more digits.
	# Dividing point id by 1000 returns original line id
	grass.run_command('v.db.addcolumn', map=outvect, columns="reach_id INTEGER", quiet=True)
	grass.run_command('v.to.db', map=outvect, option="query", columns="reach_id", qcolumn="cat/1000", quiet=True)
	
	return station_cnt
예제 #35
0
def main():
    geojson = options['input']
    outvect = options['output']

    tmpfile = grass.tempfile() + ".geojson"
    fd = open(tmpfile, "w")
    fd.write("%s\n" % (geojson))
    fd.close()

    grass.run_command('v.import', input=tmpfile, output=outvect)

    grass.try_remove(tmpfile)

    return 0
예제 #36
0
    def OnAddLayer(self, event):
        """Add web service layer.
        """
        # add layer
        if self.active_ws_panel is None:
            return 

        lcmd = self.active_ws_panel.CreateCmd()
        if not lcmd:
            return None

        # TODO: It is not clear how to do GetOptData in giface
        # knowing what GetOptData is doing might help
        # (maybe Get... is not the right name)
        # please fix giface if you know
        # tree -> giface
        # GetLayerTree -> GetLayerList
        # AddLayer -> AddLayer (but tree ones returns some layer,
        # giface ones nothing)
        # GetLayerInfo -> Layer object can by used instead
        # GetOptData -> unknown
        ltree = self.giface.GetLayerTree()

        active_ws = self.active_ws_panel.GetWebService()
        if 'WMS' not in active_ws:
            cap_file =  self.active_ws_panel.GetCapFile()
            cmd_cap_file = grass.tempfile()
            shutil.copyfile(cap_file, cmd_cap_file)
            lcmd.append('capfile=' + cmd_cap_file)

        layer = ltree.AddLayer(ltype = 'wms',
                               lname = self.active_ws_panel.GetOutputLayerName(), 
                               lchecked = True, lcmd = lcmd)


        ws_cap_files = self._getCapFiles()
        # create properties dialog
        cmd_list = ltree.GetLayerInfo(layer,'cmd')
        cmd = CmdToTuple(cmd_list)

        prop_win = WSPropertiesDialog(parent = self.parent,
                                      giface = self.giface,
                                      id = wx.ID_ANY,
                                      layer = layer,
                                      ws_cap_files = ws_cap_files,
                                      cmd = cmd)

        prop_win.Hide()
        ltree.GetOptData(dcmd = None, layer = layer, 
                         params = None, propwin = prop_win)
예제 #37
0
    def _tempfile(self):
        """!Create temp_file and append list self.temp_files_to_cleanup 
            with path of file 
     
        @return string path to temp_file
        """
        temp_file = grass.tempfile()
        if temp_file is None:
            grass.fatal(_("Unable to create temporary files"))

        # list of created tempfiles for destructor
        self.temp_files_to_cleanup.append(temp_file)

        return temp_file
예제 #38
0
def clean_temp(pid):
    """Remove temporary files of the current processes
    :param pid: Process ID whos tempfiles to remove
    :type pid: int
    """
    from pathlib import Path
    from shutil import rmtree

    tempfile = Path(grass.tempfile(create=False))
    for path in tempfile.parent.glob(str(pid) + ".*"):
        if path.is_file():
            grassutils.try_rmdir(path)
        else:
            rmtree(path)
예제 #39
0
def process_infile(flow_file, separator, header, sameok, outputfile):

    vnetinfile = gscript.tempfile()
    sqlfile = gscript.tempfile()
    cat = 0

    with open(vnetinfile, 'w') as fout:
        with open(sqlfile, 'w') as sqlout:
            sqlout.write("BEGIN TRANSACTION;\n")
            with open(flow_file, 'r') as fin:
                for line in fin:
                    cat += 1
                    if header:
                        header = False
                        continue
                    data = line.rstrip().split(separator)
                    print(data)
                    if sameok or not (data[0] == data[1]):
                        fout.write("%s %s %s\n" % (cat, data[0], data[1]))
                        sqlout.write("UPDATE %s SET from_node = %s, to_node = %s, volume = %s WHERE cat = %d;\n" % (outputfile, data[0], data[1], data[2], cat))
            sqlout.write("END TRANSACTION;\n")

    return vnetinfile, sqlfile
예제 #40
0
파일: wms_base.py 프로젝트: caomw/grass
    def _tempfile(self):
        """!Create temp_file and append list self.temp_files_to_cleanup 
            with path of file 
     
        @return string path to temp_file
        """
        temp_file = grass.tempfile()
        if temp_file is None:
            grass.fatal(_("Unable to create temporary files"))

        # list of created tempfiles for destructor
        self.temp_files_to_cleanup.append(temp_file)

        return temp_file
예제 #41
0
    def SetBaseStatistics(self, cat, name, color):
        """Sets basic (non-statistical) values.

        .. todo::
            Later self.name is changed but self.rasterName is not.
            self.rasterName should not be set by user. It can remains
            the same. But it should be done more explicitly. Currently
            it looks like unintentional feature or bug.
        """
        self.category = cat
        self.name = name
        self.color = color

        rasterPath = grass.tempfile(create=False)
        name = name.replace(' ', '_')
        self.rasterName = name + '_' + os.path.basename(rasterPath)
예제 #42
0
    def _tempfile(self):
        """!Create temp_file and append list self.temp_files_to_cleanup
            with path of file

        @return string path to temp_file
        """
        self._debug("_tempfile", "started")
        temp_file = g.tempfile()
        if temp_file is None:
            g.fatal(_("Unable to create temporary files"))

        # list of created tempfiles for destructor
        self.temp_files_to_cleanup.append(temp_file)
        self._debug("_tempfile", "finished")

        return temp_file
예제 #43
0
    def _tempfile(self):
        """!Create temp_file and append list self.temp_files_to_cleanup
            with path of file

        @return string path to temp_file
        """
        self._debug("_tempfile", "started")
        temp_file = gscript.tempfile()
        if temp_file is None:
            gscript.fatal(_("Unable to create temporary files"))

        # list of created tempfiles for destructor
        self.temp_files_to_cleanup.append(temp_file)
        self._debug("_tempfile", "finished")

        return temp_file
예제 #44
0
파일: v.costnn.py 프로젝트: eomwandho/GRASS
def attributes(layer, column):
    # Method that returns attribute data as a list
    temp = grass.tempfile()
    # ... and create and open a new file for writing with that temporary name.
    layer_temp = file(temp, 'w')
    # Get vector layer attribute data and write it to layer_temp
    grass.run_command("v.db.select", flags="c", map=layer, columns=column, stdout = layer_temp)
    layer_temp.close()
    
    # Create a list for holding the attribute values
    attlist = []
    # Open the file where attribute data ise stored and write each feature attribute data into the list
    layer_temp = file(temp)
    for feat in layer_temp:
        attlist.append(float(feat))
    layer_temp.close()
    return attlist
예제 #45
0
    def buildRoutingNet(self):
        '''Connect with subbasin centroids when subbasincentroids set to subbasins
        vector (x,y will be uploaded to table)'''
        # get inlets and outlets information
        oinfo = vreport(self.outlets,index='subbasinID')
        iinfo  = vreport(self.inlets,index='inletID')

        line = lambda fromxy,toxy: '%s,%s\n%s,%s\nNaN,NaN\n' %(fromxy['x'],fromxy['y'],
                                                               toxy['x'],toxy['y'])
        # loop over outlets
        lines=[]
        manual=[]
        for oID in oinfo:
            # inlet ID of outlet or downstream subbasin
            sbinletID=int(oinfo[oID]['inletID'])
            # for manually changed subbasins or outlets
            if sbinletID==0:
                if int(oinfo[oID]['nextID'])>0: manual+=[oinfo[oID]]
                continue
            # from outlets to inlets
            lines+=[line(oinfo[oID],iinfo[sbinletID])]
        gm('Connected %s outlets' %len(oinfo))

        # connect centroids with outlets and inlets with centroids if -c flag set
        # get subbasin centroids
        sbinfo = vreport(self.subbasins,index='subbasinID')
        # from centroids to outlets
        for o in oinfo:
            lines+=[line(sbinfo[o],oinfo[o])]
        # from inlets to centroids
        for i in iinfo:
            # get subbasinId of inlet
            insb = int(iinfo[i]['subbasinID'])
            lines+=[line(iinfo[i],sbinfo[insb])]

        # connect outlets with centroids of nextID for all manually changed subbasins
        for sb in manual:
            lines+=line(oinfo[int(sb['subbasinID'])],sbinfo[int(sb['nextID'])])
        # write to tmpfile and read as lines
        tf=grass.tempfile()
        f=file(tf,'w')
        f.writelines(lines)
        f.close()
        # make line vector
        grun('v.in.lines',input=tf,output=self.routingnet,separator=',',quiet=True)
        return
예제 #46
0
def getEnvironment(gisdbase, location, mapset):
    """Creates environment to be passed in run_command for example.
    Returns tuple with temporary file path and the environment. The user
    of this function is responsile for deleting the file."""
    tmp_gisrc_file = gscript.tempfile()
    with open(tmp_gisrc_file, 'w') as f:
        f.write('MAPSET: {mapset}\n'.format(mapset=mapset))
        f.write('GISDBASE: {g}\n'.format(g=gisdbase))
        f.write('LOCATION_NAME: {l}\n'.format(l=location))
        f.write('GUI: text\n')
    env = os.environ.copy()
    env['GISRC'] = tmp_gisrc_file
    env['GRASS_REGION'] = gscript.region_env(raster='elevation_2004@PERMANENT')
    env['GRASS_OVERWRITE'] = '1'
    env['GRASS_VERBOSE'] = '0'
    env['GRASS_MESSAGE_FORMAT'] = 'standard'
    return tmp_gisrc_file, env
def getEnvironment(gisdbase, location, mapset):
    """Creates an environment to be passed in run_command.
    Returns a tuple with a temporary file path and an environment.
    The user should delete this temporary file."""
    tmp_gisrc_file = gscript.tempfile()
    with open(tmp_gisrc_file, 'w') as f:
        f.write('MAPSET: {mapset}\n'.format(mapset=mapset))
        f.write('GISDBASE: {g}\n'.format(g=gisdbase))
        f.write('LOCATION_NAME: {l}\n'.format(l=location))
        f.write('GUI: text\n')
    env = os.environ.copy()
    env['GISRC'] = tmp_gisrc_file
    env['GRASS_REGION'] = gscript.region_env(raster=region, res=res)
    env['GRASS_OVERWRITE'] = '1'
    env['GRASS_VERBOSE'] = '0'
    env['GRASS_MESSAGE_FORMAT'] = 'standard'
    return tmp_gisrc_file, env
예제 #48
0
파일: dialogs.py 프로젝트: rkrug/grass-ci
    def __init__(self, parent, giface, layer, ws_cap_files, cmd, id=wx.ID_ANY,
                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
        """
        :param giface: grass interface
        :param layer: layer tree item
        :param ws_cap_files: dict web service('WMS_1.1.1', 'WMS_1.3.0',
        'WMTS', 'OnEarth') : cap file path cap files, which will be parsed
        :param cmd: cmd to which dialog widgets will be initialized if
        it is possible (cmp parameters exists in parsed web service cap_file)
        """

        WSDialogBase.__init__(
            self,
            parent,
            id=wx.ID_ANY,
            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
            **kwargs)

        self.SetTitle(_("Web service layer properties"))

        self.layer = layer
        self.giface = giface

        # after web service panels are connected, set dialog widgets
        # according to cmd in this variable (if it is not None)
        self.cmd_to_set = None

        # store data needed for reverting
        self.revert_ws_cap_files = {}
        self.revert_cmd = cmd

        ws_cap = self._getWSfromCmd(cmd)
        for ws in self.ws_panels.iterkeys():
            # cap file used in cmd will be deleted, thnaks to the dialogs
            # destructor
            if ws == ws_cap and 'capfile' in cmd[1]:
                self.revert_ws_cap_files[ws] = cmd[1]['capfile']
                del ws_cap_files[ws]
            else:
                self.revert_ws_cap_files[ws] = grass.tempfile()

        self._setRevertCapFiles(ws_cap_files)

        self.LoadCapFiles(ws_cap_files=self.revert_ws_cap_files, cmd=cmd)
        self.btn_ok.SetDefault()
예제 #49
0
파일: iscatt_core.py 프로젝트: caomw/grass
    def AddCategory(self, cat_id):
        cat_id = ScattPlotsCondsData.AddCategory(self, cat_id)
        if cat_id < 0:
            return cat_id

        for scatt_id in self.scatts_ids:
            ScattPlotsCondsData.AddScattPlot(self, cat_id, scatt_id)

        if cat_id == 0:
            self.cats_rasts_conds[cat_id] = None
            self.cats_rasts[cat_id] = None
        else:
            self.cats_rasts_conds[cat_id] = grass.tempfile()
            self.cats_rasts[cat_id] = "temp_cat_rast_%d_%d" % (cat_id, os.getpid())
            region = self.an_data.GetRegion()
            CreateCatRast(region, self.cats_rasts_conds[cat_id])

        return cat_id
예제 #50
0
def main():
    global tmp_img, tmp_grad_abs, tmp_grad_rel

    os.environ['GRASS_OVERWRITE'] = '1'

    color_dir = os.path.join(os.environ['GISBASE'], "etc", "colors")
    output_dir = os.path.join(os.environ['GISBASE'], "docs", "html")

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    pid = os.getpid()
    tmp_grad_abs = "tmp_grad_abs_%d" % pid
    tmp_grad_rel = "tmp_grad_rel_%d" % pid
    tmp_img = grass.tempfile() + ".ppm"

    os.environ['GRASS_RENDER_WIDTH'] = '%d' % width
    os.environ['GRASS_RENDER_HEIGHT'] = '%d' % height
    os.environ['GRASS_RENDER_FRAME'] = '%f,%f,%f,%f' % (0,height,0,width)
    os.environ['GRASS_RENDER_FILE'] = tmp_img
    os.environ['GRASS_RENDER_TRUECOLOR'] = 'TRUE'
    os.environ['GRASS_RENDER_FILE_READ'] = 'FALSE'
    os.environ['GRASS_RENDER_FILE_MAPPED'] = 'FALSE'
    os.environ['GRASS_RENDER_TRANSPARENT'] = 'FALSE'
    os.environ['GRASS_RENDER_BACKGROUNDCOLOR'] = 'ffffff'
    os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

    for var in ['GRASS_RENDER_LINE_WIDTH', 'GRASS_RENDER_ANTIALIAS']:
        if var in os.environ:
            del os.environ[var]

    grass.use_temp_region()
    grass.run_command('g.region', rows = 100, cols = 100)

    grass.mapcalc("$grad = row()/1.0", grad = tmp_grad_rel, quiet = True)
    
    for table in os.listdir(color_dir):
        path = os.path.join(color_dir, table)
        grad = make_gradient(path)
        make_image(output_dir, table, grad)
    
    grass.mapcalc("$grad = row()", grad = tmp_grad_abs, quiet = True)
    for table in ['grey.eq', 'grey.log', 'random']:
        make_image(output_dir, table, tmp_grad_abs, True)
예제 #51
0
 def OnConnect(self, event):
     """!Connect to the server"""
     server = self.server.GetValue()
     if not server:
         self.btn_import.Enable(False)
         return # not reachable
     
     layers = {}
     ret = RunCommand('r.in.wms2',
                      quiet = True,
                      parent = self,
                      wms_version = "1.3.0",
                      read = True,
                      flags = 'c',
                      mapserver = server)
     
     temp_file = grass.tempfile()
     if temp_file is None:
         grass.fatal(_("Unable to create temporary files"))##TOFO
     
     temp = open(temp_file, "w")
     temp.write(ret.encode('utf-8'))#TODO
     temp.close()
     
     if not ret:
         self.list.LoadData()
         self.btn_import.Enable(False)
         return # no layers found
     
     try:
        self.cap = WMSCapabilities(temp_file)
     except GException as error:
         GError(error, parent = self)
     
     # update list of layers
     self.list.LoadData(self.cap)
     
     if len(layers.keys()) > 0:
         self.btn_import.Enable(True)
     else:
         self.btn_import.Enable(False)
예제 #52
0
def create_water_surface(left_pairs, right_pairs, out_vect):
	"""
	Use the two lists of coordinate pairs to create a text file for import into v.in.ascii
	The left coords first, then the right coords starting from the end, 
	in order to make a closed polygon. Starting upstream along the left side of the water surface, 
	to the end of the reach, then back to the start along the right side
	Add the first point of the left pairs a second time to complete the boundary
	"""
	tmp_coords = grass.tempfile()
	proc=os.getpid()
	tmp_vect = out_vect+"_tmp_"+str(proc)
	
	# How many total points in the boundary: all the right side+ left side +1 
	# to allow for the first point a 2nd time to close boundary
	ttl_pts = len(left_pairs)+len(right_pairs)+1
	grass.message("Total number of vertices to be added to water surface polygon: %s" % ttl_pts)
	
	with open(tmp_coords,'w') as tmp:
	# Write coords in the standard ASCII file format for a grass boundary
	# Loop thru the left coord pairs, then in reverse thru the right pairs
	    tmp.write("VERTI:\n")
	    tmp.write("B %s\n" % ttl_pts)
	    for i in range(len(left_pairs)):
	        tmp.write(" "+left_pairs[i][0]+" "+left_pairs[i][1]+"\n")
			
	    for j in range(len(right_pairs)-1, -1, -1):
		tmp.write(" "+right_pairs[j][0]+" "+right_pairs[j][1]+"\n")
	
        # Finally add the first point of the left pairs again to close the boundary
            tmp.write(" "+left_pairs[0][0]+" "+left_pairs[0][1]+"\n")
	
	tmp.close()
	
	# Now feed into v.in.ascii and also run v.centroids to make a centroid for the polygon
	grass.run_command('v.in.ascii',input=tmp_coords, output=tmp_vect, format="standard", 
				quiet=True, overwrite=True)
	grass.run_command('v.centroids', input=tmp_vect, output=out_vect, quiet=True, overwrite=True)
	grass.message("Polygon vector: %s has been created" % (out_vect))
	grass.message("Cleaning up tmp files %s,%s" %(str(tmp), str(tmp_vect)))
	grass.run_command('g.remove',type='vect', name=tmp_vect, flags="f")
	os.unlink(tmp_coords)	
예제 #53
0
def main():
    global tmp
    tmp = grass.tempfile()

    vector = options['map']
    layer = options['layer']
    column = options['column']
    where = options['where']
    perc = options['percentile']
    extend = flags['e']
    shellstyle = flags['g']

    if not grass.find_file(vector, element='vector')['file']:
        grass.fatal(_("Vector map <%s> not found") % vector)

    try:
        fi = grass.vector_db(vector, stderr = nuldev)[int(layer)]
    except KeyError:
        grass.fatal(_("No attribute table linked to layer <%s>") % layer)
                
    table = fi['table']
    database = fi['database']
    driver = fi['driver']
    
    passflags = None
    if flags['e']:
	passflags = 'e'
    if flags['g']:
	if not passflags:
	    passflags = 'g'
	else:
	    passflags = passflags + 'g'

    try:
        grass.run_command('db.univar', table = table, column = column, 
                          database = database, driver = driver,
                          perc = perc, where = where, flags = passflags)
    except CalledModuleError:
        sys.exit(1)
예제 #54
0
def rreclass(in_raster, in_list, out_list, proper=True):
    """Reclass a GRASS raster map from via an in list and outlist \n
    Patches together the rules, writes it to file, performs r.reclass,
    deletes in_raster and rules file and renames the outraster"""

    # temporary rules file
    temp_rules = grass.tempfile()
    # put lists in easy writable numpy array
    rules = np.array((in_list, out_list)).transpose()
    # write rules to file
    np.savetxt(temp_rules, rules, delimiter='=', fmt='%i')
    # reclass raster in grass
    grun('r.reclass', input=in_raster,
         overwrite=True, quiet=True,
         output=in_raster + '__',
         rules=temp_rules)
    # make reclassed raster a proper raster, remove in_rast and rename output
    if proper:
        grass.mapcalc('__temp=' + in_raster + '__', quiet=True)
        grun('g.remove', type='rast', name=in_raster + '__,' + in_raster,
             flags='f', quiet=True)
        grun('g.rename', rast='__temp,' + in_raster, quiet=True)
    return
예제 #55
0
    def initialize(self):
	grass.use_temp_region()

	run('g.region', raster = self.inmap)

	reg = grass.region()
	for k, f in wind_keys.values():
	    self.total[k] = (f)(reg[k])

	if self.cols > self.total['cols']:
	    self.cols = self.total['cols']
	if self.rows > self.total['rows']:
	    self.rows = self.total['rows']

	tempbase = grass.tempfile()
	grass.try_remove(tempbase)

	self.tempfile = tempbase + '.ppm'
	self.tempmap = 'tmp.d.rast.edit'

	atexit.register(self.cleanup)

	run('g.copy', raster = (self.inmap, self.outmap), overwrite = True)
	run('r.colors', map = self.outmap, rast = self.inmap)
예제 #56
0
    def OnRun(self, event):
        """Run Python script"""
        if not self.filename:
            self.filename = gscript.tempfile() + '.py'
            self.tempfile = True
            try:
                fd = open(self.filename, "w")
                fd.write(self.body.GetText())
            except IOError as e:
                GError(_("Unable to launch Python script. %s") % e,
                       parent=self.guiparent)
                return
            finally:
                fd.close()
                mode = stat.S_IMODE(os.lstat(self.filename)[stat.ST_MODE])
                os.chmod(self.filename, mode | stat.S_IXUSR)
        else:
            # always save automatically before running
            fd = open(self.filename, "w")
            try:
                fd.write(self.body.GetText())
            finally:
                fd.close()
            # set executable file
            # (not sure if needed every time but useful for opened files)
            os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)

        # run in console as other modules, avoid Python shell which
        # carries variables over to the next execution
        env = os.environ.copy()
        if self.overwrite:
            env['GRASS_OVERWRITE'] = '1'
        cmd = [fd.name]
        if self.parameters:
            cmd.extend(self.parameters)
        self.giface.RunCmd(cmd, env=env)