def main(): options, flags = gcore.parser() probability = options['probability'] output = options['output'] count = int(options['count']) gcore.use_temp_region() # probability map probab_01 = 'probability_01_' + str(os.getpid()) TMP_RAST.append(probab_01) info = grast.raster_info(probability) gcore.write_command('r.recode', flags='d', input=probability, output=probab_01, title="Recoded probability map to 0 to 1", rules='-', stdin='{minim}:{maxim}:0:1'.format(minim=info['min'], maxim=info['max'])) mean = gcore.parse_key_val(gcore.read_command('r.univar', map=probab_01, flags='g'), val_type=float)['mean'] resolution = count / (mean * (info['north'] - info['south'] + info['east'] - info['west'])) resolution = sqrt((mean * (info['north'] - info['south']) * (info['east'] - info['west'])) / count) gcore.run_command('g.region', res=resolution) random_name = 'random_' + str(os.getpid()) point_map = 'points_' + str(os.getpid()) point_grid = 'points_' + str(os.getpid()) TMP_RAST.append(random_name) TMP_RAST.append(point_map) TMP_VECT.append(point_grid) gcore.run_command('r.surf.random', output=random_name, min=0, max=1) grast.mapcalc(exp='{point_map} = if({rand} <= {prob}, 1, null())'.format(rand=random_name, prob=probab_01, point_map=point_map)) gcore.run_command('r.to.vect', flags='t', input=point_map, output=point_grid, type='point') gcore.run_command('v.perturb', input=point_grid, output=output, parameter=resolution / 2., seed=os.getpid())
def analyse_subregion(params): tmp_clump_cat, subregions, cat, clump, threshold = params grast.mapcalc( "{new} = if ({reg} == {cat}, {clump}, null())".format( new=tmp_clump_cat, reg=subregions, cat=cat, clump=clump), overwrite=True, ) env = os.environ.copy() env["GRASS_REGION"] = gcore.region_env(zoom=tmp_clump_cat) try: data = gcore.read_command( "r.object.geometry", input=tmp_clump_cat, flags="m", separator="comma", env=env, quiet=True, ).strip() data = np.loadtxt(StringIO(data), delimiter=",", usecols=(1, 2), skiprows=1) # in case there is just one record data = data.reshape((-1, 2)) return data[data[:, 0] > threshold] except CalledModuleError: gcore.warning( "Subregion {cat} has no changes in development, no patches found.". format(cat=cat)) return np.empty([0, 2])
def detect_markers(scanned_elev, points, slope_threshold, save_height, env): """Detects markers based on current scan only (no difference).""" slope = 'slope_tmp_get_marker' range = 'range_tmp_get_marker' slope_sum = 'slope_sum_tmp_get_marker' flowacc = 'flowacc_tmp_get_marker' raster_points = "raster_points_tmp_get_marker" save_height = True gcore.run_command('r.watershed', elevation=scanned_elev, accumulation=flowacc, env=env) gcore.run_command('r.slope.aspect', elevation=scanned_elev, slope=slope, env=env) gcore.run_command('r.neighbors', input=slope, method='median', output=slope_sum, size=5, flags='c', env=env) if save_height: gcore.run_command('r.neighbors', input=scanned_elev, method='range', output=range, size=13, env=env) if save_height: range_ = range else: range_ = 1 grast.mapcalc(exp='{raster_points} = if({flowacc} == 1 && {slope_sum} > {slope_threshold}, {range}, null())'.format( raster_points=raster_points, flowacc=flowacc, slope_sum=slope_sum, slope_threshold=slope_threshold, range=range_), env=env) options = {} if save_height: options['column'] = 'height' gcore.run_command('r.to.vect', input=raster_points, output=points, type='point', env=env, **options) gcore.run_command('g.remove', type='raster', pattern="*tmp_get_marker", flags='f')
def r_fluid_temperature_hp_outlet(out, fluid, peak, execute=True, **kwargs): """Return heat pump outlet temperature :math:`T_{outHP}` [°C] Parameters ---------- fluid: FluidProperties FluidProperties named tuple with the fluid characteristics peak: qh [W] peak hourly ground load Example ------- >>> fluid = FluidProperties(capacity=4200, massflow=0.050, ... inlettemp=40.2) >>> r_fluid_temperature_hp_outlet('fluid_tmp_hp_outlet', fluid, 'peak', ... execute=False) 'fluid_tmp_hp_outlet = 40.2 + peak / (0.05 * abs(peak) / 1000. * 4200)' """ res = ( "{out} = {fluid_inlettemp} + " "{peak} / " "({fluid_massflow} * abs({peak}) / 1000. * {fluid_capacity})" ) rcmd = res.format( out=out, peak=peak, fluid_inlettemp=fluid.inlettemp, fluid_massflow=fluid.massflow, fluid_capacity=fluid.capacity, ) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def r_power(out, tc, ground_conductivity, ground_temperature, fluid_limit_temperature, borehole_length, borehole_resistence, gmax, execute=True, **kwargs): """Return the potential power using the g.pot method in W Example ------- >>> r_power(out='power', tc=180./365., ... ground_conductivity='ground_conductivity', ... ground_temperature='ground_temperature', ... fluid_limit_temperature=-2., ... borehole_length=100., borehole_resistence=0.1, ... gmax='gmax', execute=False) # doctest: +ELLIPSIS 'power = ((8. * (ground_temperature - -2.0) * ground_conductivity * 100.0 * 0.493150684...) / (gmax + 4 * 3.141592653... * ground_conductivity * 0.1))' """ res = ("{out} = ((8. * ({ground_temperature} - {fluid_limit_temperature}) * " "{ground_conductivity} * {borehole_length} * {tc}) / " "({gmax} + 4 * {pi} * {ground_conductivity} * {borehole_resistence}))") rcmd = res.format(out=out, tc=tc, ground_conductivity=ground_conductivity, ground_temperature=ground_temperature, fluid_limit_temperature=fluid_limit_temperature, pi=pi, borehole_length=borehole_length, borehole_resistence=borehole_resistence, gmax=gmax) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def _r_get_length(out, yearly_load, long_term, monthly_load, medium_term, peak_load, short_term, borehole_resistence, fluid_temp, ground_temp, temperature_penality, execute=True, **kwargs): """Return a first attempt of the BHE field lenght Example ------- >>> _r_get_length('length', yearly_load='y_load', long_term='l_term', ... monthly_load='m_load', medium_term='m_term', ... peak_load='p_load', short_term='s_term', ... borehole_resistence='bh_resistence', ... fluid_temp='f_temp', ground_temp='g_temp', ... temperature_penality='temp_pen', execute=False) ... # doctest: +NORMALIZE_WHITESPACE 'length = ((y_load * l_term + m_load * m_term + p_load * s_term + p_load * bh_resistence) / (f_temp - g_temp - temp_pen))' """ res = ("{out} = (({yearly_load} * {long_term} +" " {monthly_load} * {medium_term} +" " {peak_load} * {short_term} +" " {peak_load} * {borehole_resistence}) /" " ({fluid_temp} - {ground_temp} - {temp_penality}))") rcmd = res.format(out=out, yearly_load=yearly_load, long_term=long_term, monthly_load=monthly_load, medium_term=medium_term, peak_load=peak_load, short_term=short_term, borehole_resistence=borehole_resistence, fluid_temp=fluid_temp, ground_temp=ground_temp, temp_penality=temperature_penality) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def depression(scanned_elev, new, env, filter_depth=0, repeat=2): """Run r.fill.dir to compute depressions""" suffix = str(uuid.uuid4()).replace('-', '')[:5] input_dem = scanned_elev output = "tmp_filldir" + suffix tmp_dir = "tmp_dir" + suffix for i in range(repeat): gcore.run_command('r.fill.dir', input=input_dem, output=output, direction=tmp_dir, env=env) input_dem = output grast.mapcalc( '{new} = if({out} - {scan} > {depth}, {out} - {scan}, null())'.format( new=new, out=output, scan=scanned_elev, depth=filter_depth), env=env) gcore.write_command('r.colors', map=new, rules='-', stdin='0% aqua\n100% blue', env=env) gcore.run_command('g.remove', flags='f', type='raster', name=[output, tmp_dir], env=env)
def _createNewMap(self, mapName, backgroundMap, mapType): name = mapName.split('@')[0] background = backgroundMap.split('@')[0] types = {'CELL': 'int', 'FCELL': 'float', 'DCELL': 'double'} if background: back = background else: back = 'null()' try: grast.mapcalc(exp="{name} = {mtype}({back})".format(name=name, mtype=types[mapType], back=back), overwrite=True, quiet=True) if background: self._backgroundRaster = backgroundMap if mapType == 'CELL': values = gcore.read_command('r.describe', flags='1n', map=backgroundMap, quiet=True).strip() if values: self.uploadMapCategories.emit(values=values.split('\n')) except CalledModuleError: raise ScriptError self._backupRaster(name) name = name + '@' + gcore.gisenv()['MAPSET'] self._editedRaster = name self.newRasterCreated.emit(name=name)
def r_log_dimless_time(out, field, length, execute=True, **kwargs): """Return the logarithm of dimensionless time: [ln(t10y/ts)] Example ------- >>> bhe = BoreholeExchanger( ... ground_loads=None, ... ground=GroundProperties(conductivity=None, ... diffusivity='g_diffusivity', ... temperature=None), ... fluid=None, ... borehole=None) >>> field = BoreholeField(distance='f_dist', number='f_numb', ... ratio='f_ratio', bhe=bhe) >>> r_log_dimless_time('ln_dimless_time', field, length='bh_length', ... execute=False) # doctest: +NORMALIZE_WHITESPACE 'ln_dimless_time = log(365.25 * 10 / ((bh_length / f_numb)^2 / (9 * g_diffusivity)))' """ res = ( "{out} = log(365.25 * 10 /" " (({length} / {field.number})^2 /" " (9 * {field.bhe.ground.diffusivity})))" ) rcmd = res.format(out=out, field=field, length=length) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def subsurface_slice(points, voxel, slice_, axes, slice_line, units, offset, env): topo = gvect.vector_info_topo(points) if topo: if topo['points'] != 2: grast.mapcalc(exp=slice_ + " = null()", overwrite=True) return coordinates = gcore.read_command('v.out.ascii', input=points, format='point', separator=',', env=env).strip() coords_list = [] i = 0 for coords in coordinates.split(os.linesep): coords_list.extend(coords.split(',')[:2]) i += 1 if i >= 2: break if axes: gcore.run_command('db.droptable', flags='f', table=axes, env=env) gcore.run_command('r3.slice', overwrite=True, input=voxel, output=slice_, coordinates=','.join(coords_list), axes=axes, slice_line=slice_line, units=units, offset=offset, env=env)
def new_development(development_end, development_diff): grast.mapcalc( exp="{res} = if({dev_end} > 0, 1, null())".format( res=development_diff, dev_end=development_end), overwrite=True, quiet=True, )
def r_bh_resistence(out, bh, ground_conductivity, execute=True, **kwargs): """Return the effective borehole thermal resistance: Rb [m K W-1] .. math:: R_{b} = R_{grout} + \frac{R_{conv} + R_{pipe}}{2} Example ------- >>> bh = Borehole(radius=0.06, ... pipe_inner_radius=0.01365, pipe_outer_radius=0.0167, ... k_pipe=0.42, k_grout=1.5, distance=0.0511, ... convection=1000.) >>> r_bh_resistence('bh_resistence', bh, ... ground_conductivity='g_conductivity', execute=False) ... # doctest: +NORMALIZE_WHITESPACE 'bh_resistence = (bh_resistence_grout + (0.0116597027906 + 0.0764205945189) / 2.)' """ bh_resistence_grout = out + '_grout' r_bh_resistence_grout(bh_resistence_grout, bh, ground_conductivity, execute=execute, **kwargs) res = ("{out} = ({bh_resistence_grout} +" " ({bh_resistence_convetive} + {bh_resistence_pipe}) / 2.)") rcmd = res.format(out=out, bh_resistence_grout=bh_resistence_grout, bh_resistence_convetive=bh_resistence_convetive(bh), bh_resistence_pipe=bh_resistence_pipe(bh)) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def main(): options, flags = gcore.parser() map_in = options["input"] map_out = options["output"] newmin = options["min"] newmax = options["max"] outtype = "double" if options["type"] == "CELL": outtype = "round" elif options["type"] == "FCELL": outtype = "float" rinfo = grast.raster_info(map_in) oldmin = rinfo["min"] oldmax = rinfo["max"] grast.mapcalc( "$map_out = ${outtype}((double($map_in - $oldmin) / ($oldmax - $oldmin)) * ($newmax - $newmin) + $newmin)", map_out=map_out, map_in=map_in, outtype=outtype, oldmin=oldmin, oldmax=oldmax, newmin=newmin, newmax=newmax, )
def r_norm_time(out, time, borehole_radius, ground_conductivity, ground_capacity, execute=True, **kwargs): """Normalized time in s Example ------- >>> r_norm_time('norm_time', 180 * 24 * 60 * 60, borehole_radius=0.075, ... ground_conductivity=2., ground_capacity=2.5, execute=False) 'norm_time = (0.075^2. / (4 * 2.0 / 2.5 * 0.000001 * 15552000))' >>> r_norm_time('norm_time', 50 * 365 * 24 * 60 * 60, borehole_radius=0.075, ... ground_conductivity='ground_conductivity', ... ground_capacity='ground_capacity', execute=False) 'norm_time = (0.075^2. / (4 * ground_conductivity / ground_capacity * 0.000001 * 1576800000))' """ res = ("{out} = ({borehole_radius}^2. / (4 * {ground_conductivity} / " "{ground_capacity} * 0.000001 * {time}))") rcmd = res.format(out=out, borehole_radius=borehole_radius, ground_conductivity=ground_conductivity, ground_capacity=ground_capacity, time=time) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def r_fluid_temperature_borehole(out, fluid, peak, execute=True, **kwargs): """Return the average fluid temperature in the borehole: :math:`T_m` [°C] Parameters ---------- peak: qh [W] peak hourly ground load Example ------- >>> fluid = FluidProperties(capacity=4200, massflow=0.050, ... inlettemp=40.2) >>> r_fluid_temperature_borehole('fluid_temp', fluid, 'peak', ... execute=False) 'fluid_temp = (40.2 + fluid_temp_hp_outlet) / 2.' """ res = "{out} = ({fluid_inlettemp} + {fluid_temperature_hp_outlet}) / 2." fluid_temperature_hp_outlet = out + "_hp_outlet" r_fluid_temperature_hp_outlet( fluid_temperature_hp_outlet, fluid, peak, execute=execute ) rcmd = res.format( out=out, fluid_inlettemp=fluid.inlettemp, fluid_temperature_hp_outlet=fluid_temperature_hp_outlet, ) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def difference(real_elev, scanned_elev, new, zexag=1, env=None): """Compute difference and set color table using standard deviations""" tmp = 'tmp_resampled' gcore.run_command('r.resamp.interp', input=real_elev, output=tmp, method='bilinear', env=env) grast.mapcalc(f"{new} = {tmp} - {scanned_elev}", env=env) univar = gcore.parse_command("r.univar", flags="g", map=real_elev, env=env) std1 = zexag * float(univar["stddev"]) std2 = zexag * 2 * std1 std3 = zexag * 3 * std1 rules = [ f"-1000000 black", f"-{std3} black", f"-{std2} 202:000:032", f"-{std1} 244:165:130", "0 247:247:247", f"{std1} 146:197:222", f"{std2} 5:113:176", f"{std3} black", f"1000000 black", ] gcore.write_command("r.colors", map=new, rules="-", stdin="\n".join(rules), env=env)
def main(): options, flags = gcore.parser() drape_map = options["color"] relief_map = options["shade"] brighten = int(options["brighten"]) output_map = options["output"] bgcolor = options["bgcolor"] rhis_extra_args = {} if bgcolor: rhis_extra_args["bgcolor"] = bgcolor if flags["c"]: rhis_extra_args["flags"] = "c" to_remove = [] try: unique_name = "tmp__rshade_%d" % os.getpid() tmp_base = "%s_drape" % unique_name tmp_r = tmp_base + ".r" tmp_g = tmp_base + ".g" tmp_b = tmp_base + ".b" if brighten: # steps taken from r.his manual page # how much they are similar with d.shade/d.his is unknown # perhaps even without brightness, there can be some differences # comparing to d.shade relief_map_tmp = "%s_relief" % unique_name # convert [-99, -99] to [0.01, 1.99] brighten = 1 + brighten / 100.0 grast.mapcalc("{n} = {c} * #{o}".format(n=relief_map_tmp, o=relief_map, c=brighten)) gcore.run_command("r.colors", map=relief_map_tmp, color="grey255") relief_map = relief_map_tmp to_remove.append(relief_map_tmp) gcore.run_command( "r.his", hue=drape_map, intensity=relief_map, red=tmp_r, green=tmp_g, blue=tmp_b, **rhis_extra_args, ) to_remove.extend([tmp_r, tmp_g, tmp_b]) gcore.run_command("r.composite", red=tmp_r, green=tmp_g, blue=tmp_b, output=output_map) remove(to_remove) # who knows if finally is called when exit except CalledModuleError as error: remove(to_remove) # TODO: implement module name to CalledModuleError gcore.fatal( _("Module %s failed. Check the above error messages.") % error.cmd)
def abs_diff_gt_tol(out, raster_a, raster_b, tol=1e-3, execute=True, **kwargs): res = "{out} = if(abs({raster_a} - {raster_b}) > {tol}, 1, 0)" rcmd = res.format(out=out, raster_a=raster_a, raster_b=raster_b, tol=tol) if execute: grast.mapcalc(rcmd, **kwargs) info = grast.raster_info(out) else: info = dict(max=0) return True if info["max"] == 1 else False
def classify_colors(new, group, compactness=2, threshold=0.3, minsize=10, useSuperPixels=True, env=None): segment = 'tmp_segment' segment_clump = 'tmp_segment_clump' # we expect this name of signature signature = 'signature' classification = 'tmp_classification' filtered_classification = 'tmp_filtered_classification' reject = 'tmp_reject' if useSuperPixels: try: gcore.run_command('i.superpixels.slic', input=group, output=segment, compactness=compactness, minsize=minsize, env=env) except CalledModuleError as e: print('i.superpixels.slic failed') print(e) else: gcore.run_command('i.segment', group=group, output=segment, threshold=threshold, minsize=minsize, env=env) gcore.run_command('r.clump', input=segment, output=segment_clump, env=env) gcore.run_command('i.smap', group=group, subgroup=group, signaturefile=signature, output=classification, goodness=reject, env=env) percentile = float( gcore.parse_command('r.univar', flags='ge', map=reject, env=env)['percentile_90']) grast.mapcalc('{new} = if({classif} < {thres}, {classif}, null())'.format( new=filtered_classification, classif=classification, thres=percentile), env=env) segments = segment if useSuperPixels else segment_clump gcore.run_command('r.mode', base=segments, cover=filtered_classification, output=new, env=env)
def main(): options, flags = gcore.parser() drape_map = options['color'] relief_map = options['shade'] brighten = int(options['brighten']) output_map = options['output'] bgcolor = options['bgcolor'] rhis_extra_args = {} if bgcolor: rhis_extra_args['bgcolor'] = bgcolor if flags['c']: rhis_extra_args['flags'] = 'c' to_remove = [] try: unique_name = 'tmp__rshade_%d' % os.getpid() tmp_base = '%s_drape' % unique_name tmp_r = tmp_base + '.r' tmp_g = tmp_base + '.g' tmp_b = tmp_base + '.b' if brighten: # steps taken from r.his manual page # how much they are similar with d.shade/d.his is unknown # perhaps even without brightness, there can be some differences # comparing to d.shade relief_map_tmp = '%s_relief' % unique_name # convert [-99, -99] to [0.01, 1.99] brighten = 1 + brighten / 100. grast.mapcalc('{n} = {c} * #{o}'.format(n=relief_map_tmp, o=relief_map, c=brighten)) gcore.run_command('r.colors', map=relief_map_tmp, color='grey255') relief_map = relief_map_tmp to_remove.append(relief_map_tmp) gcore.run_command('r.his', hue=drape_map, intensity=relief_map, red=tmp_r, green=tmp_g, blue=tmp_b, **rhis_extra_args) to_remove.extend([tmp_r, tmp_g, tmp_b]) gcore.run_command('r.composite', red=tmp_r, green=tmp_g, blue=tmp_b, output=output_map) remove(to_remove) # who knows if finally is called when exit except CalledModuleError as error: remove(to_remove) # TODO: implement module name to CalledModuleError gcore.fatal( _("Module %s failed. Check the above error messages.") % error.cmd)
def diff_development(development_start, development_end, subregions, development_diff): grast.mapcalc( exp= "{res} = if({subregions} && {dev_end} && (isnull({dev_start}) ||| !{dev_start}), 1, null())" .format(res=development_diff, subregions=subregions, dev_end=development_end, dev_start=development_start), overwrite=True, quiet=True)
def r_tc(out, heating_season, execute=True, **kwargs): """ Example ------- >>> r_tc('tc', 180, execute=False) 'tc = 180 / 365.' """ res = ("{out} = {heating_season} / 365.") rcmd = res.format(out=out, heating_season=heating_season) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def depression(scanned_elev, new, env, filter_depth=0, repeat=2): """Run r.fill.dir to compute depressions""" suffix = str(uuid.uuid4()).replace('-', '')[:5] input_dem = scanned_elev output = "tmp_filldir" + suffix tmp_dir = "tmp_dir" + suffix for i in range(repeat): gcore.run_command('r.fill.dir', input=input_dem, output=output, direction=tmp_dir, env=env) input_dem = output grast.mapcalc('{new} = if({out} - {scan} > {depth}, {out} - {scan}, null())'.format(new=new, out=output, scan=scanned_elev, depth=filter_depth), env=env) gcore.write_command('r.colors', map=new, rules='-', stdin='0% aqua\n100% blue', env=env) gcore.run_command('g.remove', flags='f', type='raster', name=[output, tmp_dir], env=env)
def match_scan(base, scan, matched, env): """Vertically match scan to base using linear regression""" coeff = gcore.parse_command('r.regression.line', mapx=scan, mapy=base, flags='g', env=env) grast.mapcalc(exp="{matched} = {a} + {b} * {scan}".format(matched=matched, scan=scan, a=coeff['a'], b=coeff['b']), env=env)
def r_energy(out, power, execute=True, **kwargs): """Return the potential energy using the g.pot method in MWh/year Example ------- >>> r_energy('energy', 'power', execute=False) 'energy = 0.00876 * power' """ res = "{out} = 0.00876 * {power}" rcmd = res.format(out=out, power=power) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def patch_analysis_per_subregion(development_diff, subregions, threshold, tmp_clump, tmp_clump_cat): gcore.run_command('r.clump', input=development_diff, output=tmp_clump, overwrite=True, quiet=True) cats = gcore.read_command("r.describe", flags="1", map=subregions, quiet=True).strip().splitlines() subregions_data = {} env = os.environ.copy() for cat in cats: grast.mapcalc('{new} = if ({reg} == {cat}, {clump}, null())'.format(new=tmp_clump_cat, reg=subregions, cat=cat, clump=tmp_clump), overwrite=True) env['GRASS_REGION'] = gcore.region_env(zoom=tmp_clump_cat) data = gcore.read_command('r.object.geometry', input=tmp_clump_cat, flags='m', separator='comma', env=env, quiet=True).strip() data = np.loadtxt(StringIO(data), delimiter=',', usecols=(1, 2), skiprows=1) subregions_data[cat] = data[data[:, 0] > threshold] return subregions_data
def _createNewMap(self, mapName, backgroundMap, mapType): """Creates a new raster map based on specified background and type.""" name = mapName.split("@")[0] background = backgroundMap.split("@")[0] types = {"CELL": "int", "FCELL": "float", "DCELL": "double"} if background: back = background else: back = "null()" try: grast.mapcalc( exp="{name} = {mtype}({back})".format(name=name, mtype=types[mapType], back=back), overwrite=True, quiet=True, ) if background: self._backgroundRaster = backgroundMap gcore.run_command("r.colors", map=name, raster=self._backgroundRaster, quiet=True) if mapType == "CELL": values = gcore.read_command("r.describe", flags="1n", map=name, quiet=True).strip() if values: self.uploadMapCategories.emit( values=values.split("\n")) except CalledModuleError: raise ScriptError self._backupRaster(name) name = name + "@" + gcore.gisenv()["MAPSET"] self._editedRaster = name self._mapType = mapType self.newRasterCreated.emit(name=name) gisenv = gcore.gisenv() self._giface.grassdbChanged.emit( grassdb=gisenv["GISDBASE"], location=gisenv["LOCATION_NAME"], mapset=gisenv["MAPSET"], action="new", map=name.split("@")[0], element="raster", )
def r_distance_depth_ratio(out, field, length, execute=True, **kwargs): """Return the distance-depth ratio: B/H Example ------- >>> field = BoreholeField(distance='f_dist', number='f_numb', ... ratio='f_ratio', bhe=None) >>> r_distance_depth_ratio('dist_depth_ratio', field, ... length='bh_length', execute=False) 'dist_depth_ratio = f_dist / (bh_length / f_numb)' """ res = "{out} = {field.distance} / ({length} / {field.number})" rcmd = res.format(out=out, field=field, length=length) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def main(): options, flags = gcore.parser() drape_map = options['color'] relief_map = options['shade'] brighten = int(options['brighten']) output_map = options['output'] bgcolor = options['bgcolor'] rhis_extra_args = {} if bgcolor: rhis_extra_args['bgcolor'] = bgcolor if flags['c']: rhis_extra_args['flags'] = 'c' to_remove = [] try: unique_name = 'tmp__rshade_%d' % os.getpid() tmp_base = '%s_drape' % unique_name tmp_r = tmp_base + '.r' tmp_g = tmp_base + '.g' tmp_b = tmp_base + '.b' if brighten: # steps taken from r.his manual page # how much they are similar with d.shade/d.his is unknown # perhaps even without brightness, there can be some differences # comparing to d.shade relief_map_tmp = '%s_relief' % unique_name # convert [-99, -99] to [0.01, 1.99] brighten = 1 + brighten / 100. grast.mapcalc('{n} = {c} * #{o}'.format( n=relief_map_tmp, o=relief_map, c=brighten)) gcore.run_command('r.colors', map=relief_map_tmp, color='grey255') relief_map = relief_map_tmp to_remove.append(relief_map_tmp) gcore.run_command('r.his', hue=drape_map, intensity=relief_map, red=tmp_r, green=tmp_g, blue=tmp_b, **rhis_extra_args) to_remove.extend([tmp_r, tmp_g, tmp_b]) gcore.run_command('r.composite', red=tmp_r, green=tmp_g, blue=tmp_b, output=output_map) remove(to_remove) # who knows if finally is called when exit except CalledModuleError, error: remove(to_remove) # TODO: implement module name to CalledModuleError gcore.fatal(_("Module %s failed. Check the above error messages.") % error.cmd)
def change_detection_area(before, after, change, height_threshold, filter_slope_threshold, add, env): """Detects change in area. Result are areas with value equals the max difference between the scans as a positive value.""" slope = 'slope_tmp_get_change' before_after_regression = 'before_after_regression_tmp' # slope is used to filter areas of change with high slope (edge of model) gcore.run_command('r.slope.aspect', elevation=before, slope=slope, env=env) if add: after, before = before, after # regression reg_params = gcore.parse_command('r.regression.line', flags='g', mapx=before, mapy=after, env=env) grast.mapcalc( exp='{before_after_regression} = {a} + {b} * {before}'.format( a=reg_params['a'], b=reg_params['b'], before=before, before_after_regression=before_after_regression), env=env) grast.mapcalc( exp= "{change} = if({slope} < {filter_slope_threshold} && {before_after_regression} - {after} > {min_z_diff}, {before_after_regression} - {after}, null())" .format(change=change, slope=slope, filter_slope_threshold=filter_slope_threshold, before_after_regression=before_after_regression, after=after, min_z_diff=height_threshold), env=env) gcore.run_command( 'g.remove', type='raster', name=['slope_tmp_get_change', 'before_after_regression_tmp'], flags='f', env=env)
def _createNewMap(self, mapName, backgroundMap, mapType): """Creates a new raster map based on specified background and type.""" name = mapName.split('@')[0] background = backgroundMap.split('@')[0] types = {'CELL': 'int', 'FCELL': 'float', 'DCELL': 'double'} if background: back = background else: back = 'null()' try: grast.mapcalc(exp="{name} = {mtype}({back})".format( name=name, mtype=types[mapType], back=back), overwrite=True, quiet=True) if background: self._backgroundRaster = backgroundMap gcore.run_command('r.colors', map=name, raster=self._backgroundRaster, quiet=True) if mapType == 'CELL': values = gcore.read_command('r.describe', flags='1n', map=name, quiet=True).strip() if values: self.uploadMapCategories.emit( values=values.split('\n')) except CalledModuleError: raise ScriptError self._backupRaster(name) name = name + '@' + gcore.gisenv()['MAPSET'] self._editedRaster = name self._mapType = mapType self.newRasterCreated.emit(name=name) gisenv = gcore.gisenv() self._giface.grassdbChanged.emit(grassdb=gisenv['GISDBASE'], location=gisenv['LOCATION_NAME'], mapset=gisenv['MAPSET'], action='new', map=name.split('@')[0], element='raster')
def change_detection_area(before, after, change, height_threshold, filter_slope_threshold, add, env): """Detects change in area. Result are areas with value equals the max difference between the scans as a positive value.""" slope = 'slope_tmp_get_change' before_after_regression = 'before_after_regression_tmp' # slope is used to filter areas of change with high slope (edge of model) gcore.run_command('r.slope.aspect', elevation=before, slope=slope, env=env) if add: after, before = before, after # regression reg_params = gcore.parse_command('r.regression.line', flags='g', mapx=before, mapy=after, env=env) grast.mapcalc(exp='{before_after_regression} = {a} + {b} * {before}'.format(a=reg_params['a'], b=reg_params['b'], before=before, before_after_regression=before_after_regression), env=env) grast.mapcalc(exp="{change} = if({slope} < {filter_slope_threshold} && {before_after_regression} - {after} > {min_z_diff}, {before_after_regression} - {after}, null())".format( change=change, slope=slope, filter_slope_threshold=filter_slope_threshold, before_after_regression=before_after_regression, after=after, min_z_diff=height_threshold), env=env) gcore.run_command('g.remove', type='raster', name=['slope_tmp_get_change', 'before_after_regression_tmp'], flags='f', env=env)
def patch_analysis_per_subregion(development_diff, subregions, threshold, tmp_clump, tmp_clump_cat): gcore.run_command("r.clump", input=development_diff, output=tmp_clump, overwrite=True, quiet=True) cats = (gcore.read_command("r.describe", flags="1n", map=subregions, quiet=True).strip().splitlines()) subregions_data = {} env = os.environ.copy() for cat in cats: grast.mapcalc( "{new} = if ({reg} == {cat}, {clump}, null())".format( new=tmp_clump_cat, reg=subregions, cat=cat, clump=tmp_clump), overwrite=True, ) env["GRASS_REGION"] = gcore.region_env(zoom=tmp_clump_cat) try: data = gcore.read_command( "r.object.geometry", input=tmp_clump_cat, flags="m", separator="comma", env=env, quiet=True, ).strip() data = np.loadtxt(StringIO(data), delimiter=",", usecols=(1, 2), skiprows=1) # in case there is just one record data = data.reshape((-1, 2)) subregions_data[cat] = data[data[:, 0] > threshold] except CalledModuleError: gcore.warning( "Subregion {cat} has no changes in development, no patches found." .format(cat=cat)) subregions_data[cat] = np.empty([0, 2]) return subregions_data
def r_bhe_length(out, bhe, infovars, execute=True, **kwargs): """Return the total length calculation assuming no borehole thermal interference: L [m] Example ------- >>> bhe = BoreholeExchanger( ... ground_loads=GroundLoads(hourly='g_loads_6h', ... monthly='g_loads_1m', ... yearly='g_loads_1y'), ... ground=GroundProperties(conductivity='g_conductivity', ... diffusivity='g_diffusivity', ... temperature='g_temperature'), ... fluid=FluidProperties(capacity=4200, massflow=0.050, ... inlettemp=40.2), ... borehole=Borehole(radius=0.06, ... pipe_inner_radius=0.01365, ... pipe_outer_radius=0.0167, ... k_pipe=0.42, k_grout=1.5, distance=0.0511, ... convection=1000.) ... ) >>> infovars = InfoVars('l_term', 'm_term', 's_term', 'f_temp', 'res') >>> r_bhe_length('bhe_length', bhe, infovars, execute=False) ... # doctest: +NORMALIZE_WHITESPACE 'bhe_length = ((g_loads_1y * l_term + g_loads_1m * m_term + g_loads_6h * s_term + g_loads_6h * res) / (f_temp - g_temperature))' """ # compute the BHE length res = ( "{out} = (({bhe.ground_loads.yearly} * {iv.long_term} +" " {bhe.ground_loads.monthly} * {iv.medium_term} +" " {bhe.ground_loads.hourly} * {iv.short_term} +" " {bhe.ground_loads.hourly} * {iv.resistence}) /" " ({iv.fluid_temp} - {bhe.ground.temperature}))" ) rcmd = res.format(out=out, bhe=bhe, iv=infovars) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def r_norm_thermal_alteration(out, tc, uc, us, execute=True, **kwargs): """Normalized thermal alteration Example ------- >>> r_norm_thermal_alteration(out='gmax', tc=180./365., ... uc=1.114797374429E-06, ... us=1.130280671296E-04, execute=False) ... # doctest: +ELLIPSIS 'gmax = (-0.619 * 0.493150684... * log(0.000113028...) + (0.532 * 0.4931506849... - 0.962) * log(1.11479737...e-06) - 0.455 * 0.493150684... - 1.619)' >>> r_norm_thermal_alteration(out='gmax', tc=180./365., uc='uc', ... us='us', execute=False) # doctest: +ELLIPSIS 'gmax = (-0.619 * 0.493150684... * log(us) + (0.532 * 0.4931506849... - 0.962) * log(uc) - 0.455 * 0.493150684... - 1.619)' """ res = ("{out} = (-0.619 * {tc} * log({us}) + " "(0.532 * {tc} - 0.962) * log({uc}) - 0.455 * {tc} - 1.619)") rcmd = res.format(out=out, tc=tc, us=us, uc=uc) if execute: grast.mapcalc(rcmd, **kwargs) return rcmd
def _log(out, value, execute=True, show=False, **kwargs): """Return the natural log of a number/raster Example ------- >>> _log('log_elev', 'elevation', execute=False, show=True) log_elev = log(elevation) 'log_elev' >>> _log('log_elev', 1, execute=False) 0.0 """ if isinstance(value, str): # use rmapcalc and return raster name rcmd = "{out} = log({name})".format(out=out, name=value) if show: print(rcmd) if execute: grast.mapcalc(rcmd, **kwargs) return out else: return log(value)
def change_detection(before, after, change, height_threshold, cells_threshold, add, max_detected, debug, env): diff_thr = 'diff_thr_' + str(uuid.uuid4()).replace('-', '') diff_thr_clump = 'diff_thr_clump_' + str(uuid.uuid4()).replace('-', '') coeff = gcore.parse_command('r.regression.line', mapx=after, mapy=before, flags='g', env=env) grast.mapcalc('diff = {a} + {b} * {after} - {before}'.format(a=coeff['a'], b=coeff['b'],before=before,after=after), env=env) try: if add: grast.mapcalc("{diff_thr} = if(({a} + {b} * {after} - {before}) > {thr1} &&" " ({a} + {b} * {after} - {before}) < {thr2}, 1, null())".format(a=coeff['a'], b=coeff['b'], diff_thr=diff_thr, after=after, before=before, thr1=height_threshold[0], thr2=height_threshold[1]), env=env) else: grast.mapcalc("{diff_thr} = if(({before} - {a} + {b} * {after}) > {thr}, 1, null())".format(diff_thr=diff_thr, a=coeff['a'], b=coeff['b'], after=after, before=before, thr=height_threshold), env=env) gcore.run_command('r.clump', input=diff_thr, output=diff_thr_clump, env=env) stats = gcore.read_command('r.stats', flags='cn', input=diff_thr_clump, sort='desc', env=env).strip().splitlines() if debug: print 'DEBUG: {}'.format(stats) if len(stats) > 0 and stats[0]: cats = [] found = 0 for stat in stats: if found >= max_detected: break if float(stat.split()[1]) < cells_threshold[1] and float(stat.split()[1]) > cells_threshold[0]: # larger than specified number of cells found += 1 cat, value = stat.split() cats.append(cat) if cats: rules = ['{c}:{c}:1'.format(c=c) for c in cats] gcore.write_command('r.recode', input=diff_thr_clump, output=change, rules='-', stdin='\n'.join(rules), env=env) gcore.run_command('r.volume', flags='f', input=change, clump=diff_thr_clump, centroids=change, env=env) else: gcore.warning("No change found!") gcore.run_command('v.edit', map=change, tool='create', env=env) else: gcore.warning("No change found!") gcore.run_command('v.edit', map=change, tool='create', env=env) gcore.run_command('g.remove', flags='f', type=['raster'], name=[diff_thr, diff_thr_clump], env=env) except: gcore.run_command('g.remove', flags='f', type=['raster'], name=[diff_thr, diff_thr_clump], env=env)
def main(): options, flags = gcore.parser() aspect = options['aspect'] speed = options['speed'] probability = options['probability'] if options['particle_base']: particle_base = options['particle_base'] + '_' else: particle_base = None if options['particles']: particles = options['particles'] min_size = float(options['min_size']) max_size = float(options['max_size']) comet_length = int(options['comet_length']) else: particles = min_size = max_size = comet_length = None try: total_time = int(options['total_time']) step = int(options['step']) age = int(options['age']) count = int(options['count']) except ValueError: gcore.fatal(_("Parameter should be integer")) gcore.use_temp_region() # create aspect in x and y direction aspect_x = 'aspect_x_' + str(os.getpid()) aspect_y = 'aspect_y_' + str(os.getpid()) xshift_tmp = 'xshift_tmp_' + str(os.getpid()) yshift_tmp = 'yshift_tmp_' + str(os.getpid()) TMP_RAST.append(aspect_x) TMP_RAST.append(aspect_y) grast.mapcalc(exp="{aspect_x} = cos({aspect})".format(aspect_x=aspect_x, aspect=aspect)) grast.mapcalc(exp="{aspect_y} = sin({aspect})".format(aspect_y=aspect_y, aspect=aspect)) grast.mapcalc(exp="{xshift} = {aspect_x}*{speed}*{t}".format(xshift=xshift_tmp, t=step, speed=speed, aspect_x=aspect_x), overwrite=True) grast.mapcalc(exp="{yshift} = {aspect_y}*{speed}*{t}".format(yshift=yshift_tmp, t=step, speed=speed, aspect_y=aspect_y), overwrite=True) # initialize vector_tmp1 = 'vector_tmp1_' + str(os.getpid()) vector_tmp2 = 'vector_tmp2_' + str(os.getpid()) vector_tmp3 = 'vector_tmp3_' + str(os.getpid()) vector_region = 'vector_region_' + str(os.getpid()) TMP_VECT.extend([vector_tmp1, vector_tmp2, vector_tmp3, vector_region]) random_tmp = 'random_tmp_' + str(os.getpid()) TMP_RAST.extend([xshift_tmp, yshift_tmp, random_tmp]) gcore.run_command('v.in.region', output=vector_region, type='area') loop = 0 vector_1 = particle_base + "{0:03d}".format(loop) generate_points(name=vector_1, probability_map=probability, count=count) grast.mapcalc(exp="{random} = int(rand(1, {maxt}))".format(random=random_tmp, maxt=age + 1)) gcore.run_command('v.what.rast', map=vector_1, raster=random_tmp, column='t') write_vect_history('v.particles', options, flags, vector_1) vector_names = [vector_1, ] for time in range(0, total_time + step, step): vector_1 = particle_base + "{0:03d}".format(loop) vector_2 = particle_base + "{0:03d}".format(loop + 1) vector_names.append(vector_2) gcore.run_command('v.what.rast', map=vector_1, raster=xshift_tmp, column='xshift') gcore.run_command('v.what.rast', map=vector_1, raster=yshift_tmp, column='yshift') gcore.run_command('v.transform', layer=1, input=vector_1, output=vector_2, columns='xshift:xshift,yshift:yshift', quiet=True) # increase age gcore.info("Increasing age...") sql = 'UPDATE {table} SET t=t+1;'.format(table=vector_2) gcore.run_command('db.execute', sql=sql) # remove old points gcore.info("Removing old points...") gcore.run_command('v.select', overwrite=True, ainput=vector_2, atype='point', binput=vector_region, btype='area', operator='within', output=vector_tmp1) gcore.run_command('v.extract', input=vector_tmp1, layer=1, type='point', where="t <= " + str(age) + " AND xshift IS NOT NULL", output=vector_tmp2, overwrite=True) # generate new points gcore.info("Generating new points...") count_to_generate = count - gvect.vector_info(vector_tmp2)['points'] if count_to_generate > 0: generate_points(name=vector_tmp3, probability_map=probability, count=count_to_generate, overwrite=True) gcore.info("Patchig new and old points...") gcore.run_command('v.patch', flags='e', input=[vector_tmp2, vector_tmp3], output=vector_2, overwrite=True) sql = 'UPDATE {table} SET t={t} WHERE t IS NULL;'.format(table=vector_2, t=0) gcore.run_command('db.execute', sql=sql) write_vect_history('v.particles', options, flags, vector_2) loop += 1 # Make sure the temporal database exists tgis.init() tgis.open_new_space_time_dataset(particle_base[:-1], type='stvds', temporaltype='relative', title="title", descr='desc', semantic='mean', dbif=None, overwrite=gcore.overwrite()) # TODO: we must start from 1 because there is a bug in register_maps_in_space_time_dataset tgis.register_maps_in_space_time_dataset( type='vect', name=particle_base[:-1], maps=','.join(vector_names), start=str(1), end=None, unit='seconds', increment=step, interval=False, dbif=None) # create one vector map with multiple layers fd, path = tempfile.mkstemp(text=True) tmpfile = open(path, 'w') k = 0 for vector in vector_names: k += 1 layers = [x for x in range(k - comet_length + 1, k + 1) if x > 0] categories = list(range(len(layers), 0, -1)) text = '' for layer, cat in zip(layers, categories): text += '{l} {c}\n'.format(l=layer, c=cat) coords = gcore.read_command('v.to.db', flags='p', quiet=True, map=vector, type='point', option='coor', separator=" ").strip() for coord in coords.split('\n'): coord = coord.split() tmpfile.write('P 1 {n_cat}\n{x} {y}\n'.format(n_cat=len(categories), x=coord[1], y=coord[2])) tmpfile.write(text) tmpfile.close() gcore.run_command('v.in.ascii', flags='n', overwrite=True, input=path, output=particles, format='standard', separator=" ") os.close(fd) os.remove(path) k = 0 sql = [] sizes = get_sizes(max_size, min_size, comet_length) temporal_maps = [] for vector in vector_names: k += 1 table = 't' + str(k) gcore.run_command('v.db.addtable', map=particles, table=table, layer=k, column="width double precision") temporal_maps.append(particles + ':' + str(k)) for i in range(comet_length): sql.append("UPDATE {table} SET width={w:.1f} WHERE cat={c}".format(table=table, w=sizes[i][1], c=sizes[i][0])) gcore.write_command('db.execute', input='-', stdin=';\n'.join(sql)) tgis.open_new_space_time_dataset(particles, type='stvds', temporaltype='relative', title="title", descr='desc', semantic='mean', dbif=None, overwrite=True) # TODO: we must start from 1 because there is a bug in register_maps_in_space_time_dataset tgis.register_maps_in_space_time_dataset( type='vect', name=particles, maps=','.join(temporal_maps), start=str(1), end=None, unit='seconds', increment=step, interval=False, dbif=None) write_vect_history('v.particles', options, flags, particles)
gcore.run_command('r3.borehole', overwrite=True, input=voxel, output=new, coordinates=','.join(coords_list), size=size, offset_size=offset, axes=axes, unit=unit, env=env) def classify_colors(new, group, compactness=2, threshold=0.3, minsize=10, useSuperPixels=True, env=None): segment = 'tmp_segment' segment_clump = 'tmp_segment_clump' # we expect this name of signature signature = 'signature' classification = 'tmp_classification' filtered_classification = 'tmp_filtered_classification' reject = 'tmp_reject' if useSuperPixels: try: gcore.run_command('i.superpixels.slic', input=group, output=segment, compactness=compactness, minsize=minsize, env=env) except CalledModuleError, e: print 'i.superpixels.slic failed' print e else: gcore.run_command('i.segment', group=group, output=segment, threshold=threshold, minsize=minsize, env=env) gcore.run_command('r.clump', input=segment, output=segment_clump, env=env) gcore.run_command('i.smap', group=group, subgroup=group, signaturefile=signature, output=classification, goodness=reject, env=env) percentile = float(gcore.parse_command('r.univar', flags='ge', map=reject, env=env)['percentile_90']) grast.mapcalc('{new} = if({classif} < {thres}, {classif}, null())'.format(new=filtered_classification, classif=classification, thres=percentile), env=env) segments = segment if useSuperPixels else segment_clump gcore.run_command('r.mode', base=segments, cover=filtered_classification, output=new, env=env)