def compute_solar_irradiation(inputFile, outputFile, day_of_year, crs='32630'): # Define grass working set GRASS_GISDB = 'grassdata' GRASS_LOCATION = 'GEOPROCESSING' GRASS_MAPSET = 'PERMANENT' GRASS_ELEVATIONS_FILENAME = 'ELEVATIONS' os.environ.update(dict(GRASS_COMPRESS_NULLS='1')) # Clean previously processed data if os.path.isdir(GRASS_GISDB): shutil.rmtree(GRASS_GISDB) with Session(gisdb=GRASS_GISDB, location=GRASS_LOCATION, mapset=GRASS_MAPSET, create_opts='EPSG:32630') as ses: # Set project projection to match elevation raster projection g.proj(epsg=crs, flags='c') # Load raster file into working directory r.import_(input=inputFile, output=GRASS_ELEVATIONS_FILENAME, flags='o') # Set project region to match raster region g.region(raster=GRASS_ELEVATIONS_FILENAME, flags='s') # Calculate solar irradiation gscript.run_command('r.slope.aspect', elevation=GRASS_ELEVATIONS_FILENAME, slope='slope', aspect='aspect') gscript.run_command('r.sun', elevation=GRASS_ELEVATIONS_FILENAME, slope='slope', aspect='aspect', beam_rad='beam', step=1, day=day_of_year) # Get extraterrestrial irradiation from history metadata regex = re.compile(r'\d+\.\d+') output = gscript.read_command("r.info", flags="h", map=["beam"]) splits = str(output).split('\n') line = next(filter(lambda line: 'Extraterrestrial' in line, splits)) extraterrestrial_irradiance = float(regex.search(line)[0]) # Export generated results into a GeoTiff file if os.path.isfile(outputFile): os.remove(outputFile) r.out_gdal(input='beam', output=outputFile) return extraterrestrial_irradiance
for i, reach_no in enumerate(reaches): # make the directory for this reach this_dir = DataDirectory + 'Upper_Miss_reach' + str(reach_no) + '/' try: os.mkdir(this_dir) except: pass # set the region g.region(n=str(n[i]), s=str(s[i]), e=str(e[i]), w=str(w[i]), flags='p') # now output the ENVI bil file r.out_gdal(input="Upper_Miss_filled", format="ENVI", type="Float32", nodata=-9999, output=this_dir + 'Upper_Miss_reach' + str(reach_no) + '.bil') # clip the baseline to this region v.in_region(output='region_tmp', overwrite=True) v.overlay(ainput='Mississippi_River', atype='line', binput='region_tmp', output='Mississippi_River_clip_tmp', operator='and', overwrite=True) v.out_ogr(input='Mississippi_River_clip_tmp', output=this_dir + 'Upper_Miss_baseline_reach' + str(reach_no) + ".shp", overwrite=True)
# Hansen bin r.mapcalc(comm_code[i]+'_treecover_GFW_2000_deforestation_threshold'+str(tr)+'_binary = if('+comm_code[i]+'_treecover_GFW_2000_deforestation > '+str(tr)+', 1, 0)', overwrite = True) # remove mask and vector_cat to avoid problems r.mask(flags = 'r') g.remove(type = 'vector', name = 'vector_cat', flags = 'f') #--------------------------------------- # exporting all output # output folder pa = r'D:\bernardo\00_academico\01_artigos\ms_Lucas_world_landscape_metrics\maps' os.chdir(pa) # list maps list_maps = grass.list_grouped(type = 'raster', pattern = 'com_*')[mapset_name] # export for i in list_maps: # region g.region(raster = i) # export r.out_gdal(input = i, output = i + '_cgs_wgs84.tif', createopt = 'COMPRESS=DEFLATE,TFW=YES', overwrite = True, flags = 'f')
scanNameNULL = scanName+'__NULL__'+scanNumber scanNameShaded = scanName+'__shaded__'+scanNumber try: r.out_gdal(input=scanNameDEM, output=scanNameDEM+'.tif', format='GTiff', overwrite=False) """ # Problem with duplicates DEMs = gscript.parse_command('g.list', type='raster', pattern='*__DEM__*').keys() DEMs = sorted(DEMs) for DEM in DEMs: outname = DEM+'.tif' if os.path.isfile(outname): print "Not overwriting", outname else: print DEM r.out_gdal(input=DEM, output=outname, format='GTiff', overwrite=False) maps = gscript.parse_command('g.list', type='raster', pattern='*__shaded__*').keys() maps = sorted(maps) for mapi in maps: outname = mapi+'.tif' if os.path.isfile(outname): print "Not overwriting", outname else: print DEM r.out_gdal(input=mapi, output=outname, format='GTiff', overwrite=False) # Placeholder to make these into future functions def outputByType(self):
print "Directory " + buffer_dir + " already exists" os.chdir(buffer_dir) # List of raster to be exported list_rast_export = grass.list_grouped(type='rast', pattern='*' + ind + '*')['PERMANENT'] g.region(raster=list_rast_export, flags="ap") # Loop to export all raster for j in list_rast_export: print j r.out_gdal(input=j, output=j + '.tif', createopt="TFW=YES,COMPRESS=DEFLATE", overwrite=True) #-------------------------------------------- # Loop for all the other zones # list maps in cgs-location all_maps = grass.read_command('r.proj', location='newLocation_wgs84', mapset='variables_cut', flags='l').replace('\r', '').split('\n') all_regions = grass.read_command('v.proj', location='newLocation_wgs84', mapset='variables_cut', flags='l').replace('\r', '').split('\n')
# NPP ext in the end r.mapcalc(i+'_MOD17A3_Science_NPP_mean_00_15_exp = '+i+'_MOD17A3_Science_NPP_mean_00_15', overwrite = True) # export maps maps_exp = grass.list_grouped(type = 'raster', pattern = i+'*exp')['akde'] names = ['HFP2009', 'livestock_cattle_density', 'net_primary_productivity', 'forest_year', 'population_density', 'road_dist', 'road_density_km_per100km2', 'protected_areas', 'bio12_annual_precipitation', 'bio15_precipitation_seasonality'] names_exp = [i+'_'+nm for nm in names] pa = r'E:\_neojaguardatabase\other_limits_cut_variables\akde\maps' os.chdir(pa) for mm in range(len(maps_exp)): if 'NPP' in maps_exp[mm]: r.out_gdal(input = maps_exp[mm], output = names_exp[mm], createopt = 'COMPRESS=DEFLATE', overwrite = True, flags = 'f') else: r.out_gdal(input = maps_exp[mm], output = names_exp[mm], createopt = 'COMPRESS=DEFLATE', overwrite = True) # save statistics f = open('table_akde.csv', 'a+') f.write(ind_codmatch+';'+kern) for mm in range(len(maps_exp)): var = grass.parse_command('r.univar', map = maps_exp[mm], flags = 'g') if len(var) == 0: val = 'NA' else: val = var['mean'].encode("utf-8") f.write(';'+val)
#That's mostly because I don't know how to programmatically #rescale a float to an int print "Recoding raster layer" rules = "0.0:" + str(vals[-1]) + ":0:255" #r.recode(input=raster_layer, rules=rules, output=recoded_raster_layer) g.write_command('r.recode', input=raster_layer, rule='-', output=recoded_raster_layer, stdin=rules) # Now, we apply our color table # Again, we'll pipe this from stdin, but you should probably use a file. # These rules get way more complicated, since we need multiple lines, # but I'm still too lazy to write to a file. Also, \n's are fun. print "Applying new color table" color_rules = "0% blue\n33.33% green\n66.67% yellow\n100% red" g.write_command('r.colors', map=recoded_raster_layer, rules='-', stdin=color_rules) # Set NULL values to remove noise # I'm doing a fairly aggressive data purge, use respnsibly print "Nullifying nulls" r.null(map=recoded_raster_layer, setnull="0-20") # Finally, write it to a GeoTiff print "Writing file: %s" % os.path.join(data_directory, output_file) r.out_gdal(input=recoded_raster_layer, format="GTiff", type="Byte", output=os.path.join(data_directory, output_file), createopt="INTERLEAVE=PIXEL, TFW=YES, PROFILE=GeoTIFF") # That's all folks! print "Congrats, it is finished."
scanNameShaded = scanName+'__shaded__'+scanNumber try: r.out_gdal(input=scanNameDEM, output=scanNameDEM+'.tif', format='GTiff', overwrite=False) """ # Problem with duplicates DEMs = gscript.parse_command('g.list', type='raster', pattern='*__DEM__*').keys() DEMs = sorted(DEMs) for DEM in DEMs: outname = DEM + '.tif' if os.path.isfile(outname): print "Not overwriting", outname else: print DEM r.out_gdal(input=DEM, output=outname, format='GTiff', overwrite=False) maps = gscript.parse_command('g.list', type='raster', pattern='*__shaded__*').keys() maps = sorted(maps) for mapi in maps: outname = mapi + '.tif' if os.path.isfile(outname): print "Not overwriting", outname else: print DEM r.out_gdal(input=mapi, output=outname, format='GTiff', overwrite=False) # Placeholder to make these into future functions def outputByType(self):
from mower import GrassSession DEM = "/home/mperry/projects/shortcreek/dem/dem.img" with GrassSession(DEM) as gs: from grass.pygrass.modules.shortcuts import raster # Import/Link to External GDAL data raster.external(input=DEM, output="dem") # Perform calculations raster.mapcalc(expression="demft=dem*3.28084") raster.slope_aspect(elevation="demft", slope="slope", aspect="aspect") # Export from GRASS to GDAL from grass.pygrass.gis import Mapset m = Mapset() for r in m.glist('rast'): if r == "dem": # don't save the original continue raster.out_gdal(r, format="GTiff", output="/tmp/{}.tif".format(r), overwrite=True)