def main(): elevation = sys.argv[1] nightlights = sys.argv[2] photopollution = sys.argv[3] max_distance = float(sys.argv[4]) # Overwrite and verbose parameters #os.environ["GRASS_OVERWRITE"] = "1" os.environ['GRASS_VERBOSE'] = "-1" reg = Region() #get current region, use it for cell iteration if Region().nsres != Region().ewres: print "ewres is different from nsres" raise SystemExit # open dem dem = raster.RasterRow(elevation) if dem.is_open(): dem.close() if not dem.is_open(): dem.open() # open night time lights lights = raster.RasterRow(nightlights) if lights.is_open(): lights.close() if not lights.is_open(): lights.open() script.use_temp_region( ) #temporary region in case of parallel processing, maybe useless for current project # expand region according to viewshed max distance (align to dem) script.run_command('g.region', n=reg.north + max_distance, s=reg.south - max_distance, e=reg.east + max_distance, w=reg.west - max_distance, align=elevation) # resample lights raster script.run_command("r.resample", input=nightlights, output=tmp_res_lights, overwrite=True) script.del_temp_region() calcPhotoPolRast(dem, max_distance, reg, elevation, lights, photopollution)
def read_raster_map(self, rast_name): """Read a GRASS raster and return a numpy array """ self.raster_lock.acquire() with raster.RasterRow(rast_name, mode='r') as rast: array = np.array(rast, dtype=self.dtype) self.raster_lock.release() return array
def write_raster_map_blocking(self, arr, rast_name, mkey): mtype = self.grass_dtype(arr.dtype) assert isinstance(mtype, str), u"not a string!" with raster.RasterRow(rast_name, mode='w', mtype=mtype, overwrite=self.overwrite) as newraster: newrow = raster.Buffer((arr.shape[1], ), mtype=mtype) for row in arr: newrow[:] = row[:] newraster.put_row(newrow) # apply color table apply_color_table(rast_name, mkey) return self
def main(): options, flags = gscript.parser() input = options['input'] output = options['output'] if (input is None or input == ""): gscript.error(_("[h.out] ERROR: input is a mandatory parameter.")) exit() exists = False maps_list = utils.findmaps(type='raster') for map in maps_list: if input == map[0]: exists = True break if (not exists): gscript.error(_("[h.out] ERROR: could not find input map.")) exit() if (output is None or output == ""): gscript.error(_("[h.out] ERROR: output is a mandatory parameter.")) exit() rast = raster.RasterRow(input) # Set region (note that it is tricking GRASS to think it is a squared raster) info = gscript.read_command('r.info', map=input, flags='g') info = info.split("\n") print(info[6]) hexASCII = HASC() # This can probably be set from the RasterRow object hexASCII.init( int(info[7].split("=")[1]), #ncols, int(info[6].split("=")[1]), #nrows, int(info[3].split("=")[1]), #xll, int(info[1].split("=")[1]), #yll, "NA") #nodata) r = 0 rast.open() for row in rast: for c in range(0, rast.info.cols): hexASCII.set(c, r, row[c]) gscript.message(_("[h.in] DEBUG: Exporting row: %s" % newRow)) r = r + 1 gscript.message(_("[h.out] SUCCESS: HexASCII raster exported."))
def write_raster_map(self, arr, rast_name, mkey): """Take a numpy array and write it to GRASS DB """ assert isinstance(arr, np.ndarray), u"arr not a np array!" assert isinstance(rast_name, str), u"not a string!" mtype = self.grass_dtype(arr.dtype) with raster.RasterRow(rast_name, mode='w', mtype=mtype, overwrite=self.overwrite) as newraster: newrow = raster.Buffer((arr.shape[1], ), mtype=mtype) for row in arr: newrow[:] = row[:] newraster.put_row(newrow) # apply color table self.apply_color_table(rast_name, mkey) return self
def main(): options, flags = gscript.parser() input = options['input'] output = options['output'] if (output is None or output == ""): gscript.error(_("[h.in] ERROR: output is a mandatory parameter.")) exit() # Load HexASCII raster into memory hexASCII = HASC() try: hexASCII.loadFromFile(input) except (ValueError, IOError) as ex: gscript.error( _("[h.in] ERROR: Failed to load raster %s: %s" % (input, ex))) exit() # Set region (note that it is tricking GRASS to think it is a squared raster) gscript.run_command('g.region', rows=hexASCII.nrows, cols=hexASCII.ncols, res=hexASCII.side) # Create RasterRow object and iterate trough rows newRast = raster.RasterRow(output) newRast.open('w', 'FCELL') for row in range(0, hexASCII.nrows): newRow = Buffer(shape=(1, hexASCII.ncols)) #, dtype=float, order='F') for col in range(0, hexASCII.ncols): newRow[0, col] = hexASCII.get(col, row) gscript.message(_("[h.in] DEBUG: Importing row: %s" % newRow)) newRast.put_row(newRow) gscript.message(_("[h.in] DEBUG: Imported raster: %s" % (newRast))) # Close RasterRow to force its creation newRast.close() gscript.message(_("[h.in] SUCCESS: HexASCII raster imported."))
def raster_writer(q, lock): """Write a raster map in GRASS """ while True: # Get values from the queue next_object = q.get() if next_object is None: break arr, rast_name, mtype, mkey, overwrite = next_object # Write raster lock.acquire() with raster.RasterRow(rast_name, mode='w', mtype=mtype, overwrite=overwrite) as newraster: newrow = raster.Buffer((arr.shape[1], ), mtype=mtype) for row in arr: newrow[:] = row[:] newraster.put_row(newrow) # Apply colour table apply_color_table(rast_name, mkey) lock.release() # Signal end of task q.task_done()
def main(options, flags): # Get the options points = options["points"] strds = options["strds"] output = options["output"] where = options["where"] order = options["order"] column = options["column"] separator = options["separator"] coordinates = options["coordinates"] # Setup separator if separator == "pipe": separator = "|" if separator == "comma": separator = "," if separator == "space": separator = " " if separator == "tab": separator = "\t" if separator == "newline": separator = "\n" use_cats = False write_header = flags["n"] use_raster_region = flags["r"] overwrite = gscript.overwrite() if points and coordinates: gscript.fatal(_("points and coordinates are mutually exclusive")) if not points and not coordinates: gscript.fatal(_("You must specify points or coordinates")) # Make sure the temporal database exists tgis.init() # We need a database interface dbif = tgis.SQLDatabaseInterfaceConnection() dbif.connect() sp = tgis.open_old_stds(strds, "strds", dbif) maps = sp.get_registered_maps_as_objects(where=where, order=order, dbif=dbif) dbif.close() if not maps: gscript.fatal(_("Space time raster dataset <%s> is empty") % sp.get_id()) # The list of sample points p_list = [] if not coordinates: # Check if the chosen header column is in the vector map vname = points vmapset= "" if "@" in points: vname, vmapset = points.split("@") v = pyvect.VectorTopo(vname, vmapset) v.open("r") col_index = 0 if v.exist() is False: gscript.fatal(_("Vector map <%s> does not exist" %(points))) if not v.table: use_cats = True gscript.warning(_("Vector map <%s> does not have an attribute table, using cats as header column." %(points))) if v.table and column not in v.table.columns: gscript.fatal(_("Vector map <%s> has no column named %s" %(points, column))) if use_cats is False: col_index = list(v.table.columns.names()).index(column) # Create the point list for line in v: if line.gtype == libvect.GV_POINT: if use_cats is False: p = SamplePoint(line.x, line.y, line.cat, line.attrs.values()[col_index]) elif use_cats is True: p = SamplePoint(line.x, line.y, line.cat) p_list.append(p) v.close() else: # Convert the coordinates into sample points coord_list = coordinates.split(",") use_cats = True count = 0 cat = 1 while count < len(coord_list): x = coord_list[count] count += 1 y = coord_list[count] count += 1 p = SamplePoint(float(x), float(y), cat) p_list.append(p) cat += 1 if output: out_file = open(output, "w") else: out_file = sys.stdout # Write the header if write_header: out_file.write("start_time") out_file.write(separator) out_file.write("end_time") out_file.write(separator) count = 0 for p in p_list: count += 1 if use_cats is True: out_file.write(str(p.cat)) else: out_file.write(str(p.column)) if count != len(p_list): out_file.write(separator) out_file.write("\n") # Sorting the points by y-coordinate to make use of the single row cache and read direction sorted_p_list = sorted(p_list, key=SamplePointComparisonY) # Sample the raster maps num = 0 for map in maps: num += 1 sys.stderr.write("Sample map <%s> number %i out of %i\n" %(map.get_name(), num, len(maps))) start, end = map.get_temporal_extent_as_tuple() out_file.write(str(start)) out_file.write(separator) if not end: out_file.write(str(start)) else: out_file.write(str(end)) out_file.write(separator) r = pyrast.RasterRow(map.get_name(), map.get_mapset()) if r.exist() is False: gscript.fatal(_("Raster map <%s> does not exist" %(map.get_id()))) region = None if use_raster_region is True: r.set_region_from_rast() region = pyregion.Region() region.from_rast(map.get_name()) # Open the raster layer after the region settings r.open("r") # Sample the raster maps with the sorted points for p in sorted_p_list: p.value = r.get_value(point=p, region=region) # Write the point values from the original list count = 0 for p in p_list: count += 1 out_file.write(str(p.value)) if count != len(p_list): out_file.write(separator) out_file.write("\n") r.close() out_file.close()
#!/usr/bin/env python import numpy as np from grass.pygrass import raster ndvi = raster.RasterRow('ndvi') ndvi.open() min = max = None count = ncount = 0 for row in ndvi: for value in row: if np.isnan(value): ncount += 1 else: if min is None: min = max = value else: if min > value: min = value elif max < value: max = value count += 1 ndvi.close() print("min={0:.6f} max={1:.6f} count={2} (no-data: {3})".format( min, max, count, ncount))
def read_raster_map(self, rast_name): """Read a GRASS raster and return a numpy array """ with raster.RasterRow(rast_name, mode='r') as rast: array = np.array(rast, dtype=self.dtype) return array