Esempio n. 1
0
def run_flow(real_elev, scanned_elev, scanned_calib_elev, env, **kwargs):
    threshold = 30
    flowacc = 'flowacc'
    drain = 'drainage'
    stream = 'stream'
    basin = 'basin'

    env2 = get_environment(raster=scanned_calib_elev)
    change_detection(before=scanned_calib_elev, after=scanned_elev,
                              change='change', height_threshold=[150, 1000], cells_threshold=[20, 140], add=True, max_detected=10, debug=True, env=env)
    # detected points
    points = gscript.read_command('v.out.ascii', input='change',
                                      type='point', format='point').strip().splitlines()
    if points:
        x, y, cat = points[0].split('|')
        gscript.run_command('r.stream.snap', input='change', output='outlet',
                            stream_rast=stream, accumulation=flowacc, radius=10, env=env2)
        outlets = gscript.read_command('v.out.ascii', input='outlet',
                                       type='point', format='point').strip().splitlines()
        x2, y2, cat2 = outlets[0].split('|')
        gscript.run_command('r.water.outlet', input=drain, output=basin, coordinates=(x2, y2), env=env2)
        gscript.write_command('r.colors', map=basin, rules='-', stdin='0% indigo\n100% indigo', env=env2)
        # drain
        gscript.run_command('r.drain', input="hydrodem", output="drain", drain="drain",
                            start_coordinates=(x2, y2), env=env2)
    else:
        gscript.mapcalc('basin = null()', env=env)
        gscript.run_command('v.edit', tool='create', map='drain', env=env)
        gscript.run_command('r.watershed', elevation=scanned_elev, accumulation=flowacc,
                            stream=stream,  drainage=drain, threshold=threshold, env=env)
        gscript.run_command('r.hydrodem', input=scanned_elev, output="hydrodem", mod=30, env=env)
        gs.run_command("g.copy", raster=[scanned_elev, scanned_calib_elev], env=env)
 def _defineEnvironment(self):
     maps = gscript.read_command('i.group',
                                 flags='g',
                                 group=self.group,
                                 subgroup=self.group).strip()
     if maps:
         self.env = get_environment(raster=maps.splitlines()[0])
Esempio n. 3
0
def run_cutfill(real_elev, scanned_elev, env, **kwargs):
    # this doesn't need to be computed on the fly
    dem_env = get_environment(raster=real_elev)
    gs.run_command(
        "r.contour",
        input=real_elev,
        output="contours_dem",
        step=5,
        flags="t",
        env=dem_env,
    )

    # compute difference and set color table using standard deviations
    gs.mapcalc("diff = {r} - {s}".format(r=real_elev, s=scanned_elev), env=env)
    gs.mapcalc("absdiff = abs(diff)", env=env)
    univar = gs.parse_command("r.univar", flags="g", map="absdiff", env=env)
    std1 = float(univar["stddev"])
    std2 = 2 * std1
    maxv = float(univar["max"]) + 1
    rules = [
        f"-{maxv} 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"{maxv} black",
    ]
    gs.write_command("r.colors",
                     map="diff",
                     rules="-",
                     stdin="\n".join(rules),
                     env=env)
Esempio n. 4
0
    def CustomAction(self, eventName):
        env = get_environment(rast=self.settings['output']['scan'])  # noqa: F841
        myanalyses, functions = self._reloadAnalysisFile(funcPrefix=eventName)

        for func in functions:
            try:
                exec('myanalyses.' + func + "(eventHandler=wx.GetTopLevelParent(self), env=env)")
            except (CalledModuleError, Exception, ScriptError):
                print(traceback.print_exc())
Esempio n. 5
0
 def _defineEnvironment(self):
     try:
         gscript.read_command('i.group', flags='g', group=self.group, subgroup=self.group, env=self.env)
     except CalledModuleError:
         gscript.run_command('i.group', group=self.group, subgroup=self.group,
                             input=[self.group + '_' + ext for ext in 'r', 'g', 'b'], env=self.env)
     maps = gscript.read_command('i.group', flags='g', group=self.group, subgroup=self.group).strip()
     if maps:
         self.env = get_environment(raster=maps.splitlines()[0])
Esempio n. 6
0
 def OnProfileUpdate(self, event):
     # event can be received after frame is destroyed
     if not self.profileFrame:
         return
     env = get_environment(
         raster=self.tasks[self.current]['profile']['raster'])
     self.profileFrame.compute_profile(
         points=event.points,
         raster=self.tasks[self.current]['profile']['raster'],
         env=env)
Esempio n. 7
0
def xrun_crossection(scanned_elev, env, **kwargs):
    env3d = get_environment(raster_3d=voxel)
    analyses.cross_section(scanned_elev=scanned_elev,
                           voxel=voxel,
                           new='cross',
                           env=env3d)
    analyses.contours(scanned_elev=scanned_elev,
                      new='contours_scanned',
                      step=20.,
                      maxlevel=0,
                      env=env)
Esempio n. 8
0
    def PostProcessing(self, onDone=None):
        wx.BeginBusyCursor()
        wx.SafeYield()
        env = get_environment(
            rast=self.settings['output']['scan'])  # noqa: F841
        try:
            postprocess = imp.load_source(
                'postprocess',
                os.path.join(self._getTaskDir(),
                             self.tasks[self.current]['analyses']))
        except Exception as e:
            print(e)
            return

        functions = [
            func for func in dir(postprocess) if func.startswith('post_')
        ]
        for func in functions:
            exec('del postprocess.' + func)
        try:
            postprocess = imp.load_source(
                'postprocess',
                os.path.join(self._getTaskDir(),
                             self.tasks[self.current]['analyses']))
        except Exception as e:
            print(e)
            return
        functions = [
            func for func in dir(postprocess) if func.startswith('post_')
        ]
        for func in functions:
            try:
                exec('postprocess.' + func +
                     "(real_elev=self.settings['scan']['elevation'],"
                     " scanned_elev=self.settings['output']['scan'],"
                     " filterResults=self.scaniface.filter['counter'],"
                     " timeToFinish=self.endTime,"
                     " subTask=self.currentSubtask,"
                     " logDir=self.configuration['logDir'],"
                     " env=env)")
            except (CalledModuleError, Exception, ScriptError) as e:
                traceback.print_exc()
        wx.EndBusyCursor()
        if self.handsoff and not self.IsStandalone():
            ll = self.giface.GetLayerList()
            ll.DeleteLayer(self.handsoff)
            self.handsoff = None

        if onDone:
            onDone()
Esempio n. 9
0
def futures(params, giface, update):
    os.chdir('/home/tangible/Documents/asheville_TL')
    env2 = get_environment(raster='buncombe')

    cmd = ['r.futures.pga', 'subregions=buncombe', 'developed=urban_2011_buncombe',
           'predictors=road_dens_perc,forest_smooth_perc,dist_to_water_km,dist_to_protected_km',
           'devpot_params=potential.csv', 'development_pressure=devpressure_0_5', 'n_dev_neighbourhood=30',
           'development_pressure_approach=gravity', 'gamma=0.5', 'scaling_factor=0.1', 'demand=demand_TL_high.csv',
           'discount_factor=0.8', 'compactness_mean=0.1', 'compactness_range=0.05', 'patch_sizes=patches.txt',
           'num_neighbors=4', 'seed_search=2', 'random_seed=1', 'output=final', 'output_series=step'] + params
    userData = {}
    userData['update'] = update
    userData['env'] = env2
    giface.RunCmd(cmd, env=env2, onDone=onFuturesDone, userData=userData)
Esempio n. 10
0
def run_dem(real_elev, scanned_elev, blender_path, eventHandler, env,
            **kwargs):
    gscript.run_command('g.copy', raster=[scanned_elev, 'topo_saved'], env=env)
    info = gscript.raster_info(map=scanned_elev)
    env2 = get_environment(raster=scanned_elev,
                           res=(info['nsres'] + info['ewres']) / 4)
    gscript.run_command('r.resamp.interp',
                        input=scanned_elev,
                        output=scanned_elev + '_hires',
                        method='bilinear',
                        env=env2)
    blender_export_DEM(raster=scanned_elev + '_hires',
                       name='terrain',
                       time_suffix=False,
                       path=blender_path,
                       env=env2)
Esempio n. 11
0
def xdrawing_roads(draw_vector_append_name, env,  update, giface, **kwargs):
    gscript.run_command('v.generalize', input=draw_vector_append_name, output='smooth', threshold=10, method='snakes', env=env)
    env2 = get_environment(raster='buncombe')
    gscript.run_command('v.to.rast', input='smooth', output='road', type='line', use='val', env=env2)
    #gscript.mapcalc('roads_patch = if(isnull(road), roads, road)', env=env2)
    #gscript.run_command('r.neighbors', flags='c', input='roads_patch', output='road_dens_edit', size=25, method='average', env=env2)
    #gscript.mapcalc('road_dens_perc_edit = 100 * road_dens_edit', env=env2)
    #gscript.run_command('r.colors', map='road_dens_perc_edit,road_dens_perc', color='byr', env=env2)
    
    gscript.run_command('r.grow.distance', input='road', distance='buffer', env=env2)
    gscript.mapcalc('stimulus_roads = if(buffer > 500, 0, graph(buffer, 0, 0.7, 200,0.5, 500,0.3))', env=env2)
    gscript.run_command('r.colors', map='stimulus_roads', color='reds', env=env)

    params = []
    ff = gscript.find_file(name='appended', element='vector')
    if ff and ff['fullname'] and gscript.vector_info_topo('appended')['lines'] > 0:
        params.append('stimulus=stimulus_roads')
    
    futures(params, giface, update)
def run_drain(real_elev, scanned_elev, eventHandler, env, subTask, **kwargs):
    before = 'scan_saved'
    analyses.change_detection(before=before,
                              after=scanned_elev,
                              change='change',
                              height_threshold=[60, 220],
                              cells_threshold=[4, 80],
                              add=True,
                              max_detected=1,
                              debug=True,
                              env=env)
    point = gscript.read_command('v.out.ascii',
                                 input='change',
                                 type='point',
                                 format='point',
                                 env=env).strip()
    drain = 'drain_line'
    env2 = get_environment(raster=real_elev)
    if point:
        x, y, cat = point.split('|')
        gscript.run_command('r.drain',
                            input=real_elev,
                            output=drain,
                            drain=drain,
                            start_coordinates='{},{}'.format(x, y),
                            env=env2)
    else:
        gscript.run_command('v.edit', map=drain, tool='create', env=env)

    # copy results
    if point:
        postfix = datetime.now().strftime('%H_%M_%S')
        prefix = 'drain'
        gscript.run_command('g.copy',
                            vector=[
                                'change', '{}_change_{}_{}'.format(
                                    prefix, subTask, postfix)
                            ],
                            env=env)
Esempio n. 13
0
def run_slice(scanned_elev, env, **kwargs):
    env3d = get_environment(raster_3d=voxel)
    data = gs.read_command('v.out.ascii',
                           input='change',
                           type='point',
                           format='point',
                           separator='comma').strip().split()
    points = [point.split(',')[:2] for point in data]
    if len(points) == 2:
        gs.run_command('r3.slice',
                       input=voxel,
                       output='slice',
                       axes='axes',
                       coordinates=[
                           points[0][0], points[0][1], points[1][0],
                           points[1][1]
                       ],
                       slice_line='slice_line',
                       offset=[0, 0],
                       units=['m', 'cm'],
                       overwrite=True,
                       quiet=True,
                       env=env3d)
def run_drain(scanned_elev, env, points=None, **kwargs):
    drain = "drain"
    if not points:
        elev_no_points = "scan_saved"
        points = "points"
        import analyses
        from tangible_utils import get_environment

        env2 = get_environment(raster=elev_no_points)
        analyses.change_detection(
            "scan_saved",
            scanned_elev,
            points,
            height_threshold=[10, 100],
            cells_threshold=[5, 50],
            add=True,
            max_detected=5,
            debug=True,
            env=env,
        )
    else:
        elev_no_points = scanned_elev
        env2 = env
    # if points detected
    if gs.vector_info_topo("points")["points"]:
        gs.run_command(
            "r.drain",
            input=elev_no_points,
            output=drain,
            drain=drain,
            start_points=points,
            env=env2,
        )
    else:
        # create empty vector
        gs.run_command("v.edit", map=drain, tool="create", env=env)
def run_trails(real_elev, scanned_elev, blender_path, eventHandler, env,
               **kwargs):
    resulting = "trail"
    trail = "trail"
    before = "scan_saved"
    # trim the edges to avoid noise being detected as markers
    info = gs.raster_info("scan")
    edge = (info["north"] - info["south"]) / 20
    env2 = get_environment(
        raster=scanned_elev,
        n="n-{}".format(edge),
        s="s+{}".format(edge),
        e="e-{}".format(edge),
        w="w+{}".format(edge),
    )
    analyses.change_detection(
        before=before,
        after=scanned_elev,
        change="change",
        height_threshold=[min_threshold, max_threshold],
        cells_threshold=[10, 100],
        add=True,
        max_detected=max_number_of_markers,
        debug=True,
        env=env2,
    )
    points = {}
    # if we have 'trail_points' vector, use this:
    # data = gs.read_command('v.out.ascii', input='trail_points', type='point', format='point', env=env).strip()
    # c1, c2 = data.splitlines()
    # c1 = c1.split('|')
    # c2 = c2.split('|')
    # points[0] = (float(c1[0]), float(c1[1]))
    # points[1] = (float(c2[0]), float(c2[1]))
    # otherwise we will generate them on the fly:
    points[0], points[1] = create_end_points(env)

    gs.run_command("v.edit", tool="create", map=trail, env=env)
    # detected points
    points_raw = (gs.read_command("v.out.ascii",
                                  input="change",
                                  type="point",
                                  format="point").strip().split())
    i = 2
    for point in points_raw:
        point = point.split("|")
        point = (float(point[0]), float(point[1]))
        points[i] = point
        i += 1
    length = len(points)
    if length == 2:
        gs.mapcalc("{} = null()".format(resulting), env=env)
        event = updateProfile(points=[])
        eventHandler.postEvent(receiver=eventHandler.activities_panel,
                               event=event)
        return

    # distance matrix
    D = []
    for i in range(length):
        D.append([0] * length)
    for p1 in range(0, length - 1):
        for p2 in range(p1 + 1, length):
            d = dist(points, p1, p2)
            D[p1][p2] = d
            D[p2][p1] = d
    # 0 distance for start and end to make sure it's always connected
    D[0][1] = 0
    D[1][0] = 0

    # solve
    solution = solve_tsp_numpy(D, optim_steps=10)
    # rearange solutions to start in start point
    ind1 = solution.index(0)
    ind2 = solution.index(1)
    if ind2 > ind1:
        solution = solution[::-1]
    ind = solution.index(0)
    solution = solution[ind:] + solution[:ind]
    profile_points = []
    for i in solution:
        profile_points.append(points[i])

    # friction
    friction = "friction"
    gs.mapcalc("{} = 0".format(friction), env=env)
    tmp_dir = "tmp_dir"
    tmp_cost = "tmp_cost"
    tmp_drain = "tmp_drain"

    gs.run_command("v.edit", tool="create", map=trail, env=env)
    for i in range(len(solution) - 1):
        gs.run_command(
            "r.walk",
            elevation=before,
            friction=friction,
            output=tmp_cost,
            outdir=tmp_dir,
            start_coordinates=points[solution[i]],
            stop_coordinates=points[solution[i + 1]],
            flags="k",
            env=env,
        )
        gs.run_command(
            "r.drain",
            input=tmp_cost,
            direction=tmp_dir,
            output=tmp_drain,
            drain=tmp_drain,
            start_coordinates=points[solution[i + 1]],
            flags="d",
            env=env,
        )
        gs.run_command("v.patch",
                       input=tmp_drain,
                       output=trail,
                       flags="a",
                       env=env)

    env2 = get_environment(raster=before)
    # slope along line
    gs.run_command("v.to.rast",
                   input=trail,
                   type="line",
                   output="trail_dir",
                   use="dir",
                   env=env2)
    gs.run_command(
        "r.slope.aspect",
        elevation=before,
        slope="saved_slope",
        aspect="saved_aspect",
        env=env2,
    )
    gs.mapcalc(
        "slope_dir = abs(atan(tan({slope}) * cos({aspect} - {trail_dir})))".
        format(slope="saved_slope",
               aspect="saved_aspect",
               trail_dir="trail_dir"),
        env=env2,
    )
    # set new color table
    colors = [
        "0 green", "5 green", "5 yellow", "10 yellow", "10 red", "90 red"
    ]
    gs.write_command("r.colors",
                     map="slope_dir",
                     rules="-",
                     stdin="\n".join(colors),
                     env=env2)
    # increase thickness
    gs.run_command("r.grow",
                   input="slope_dir",
                   radius=1.1,
                   output=resulting,
                   env=env2)

    # update profile
    event = updateProfile(points=profile_points)
    eventHandler.postEvent(receiver=eventHandler.activities_panel, event=event)
Esempio n. 16
0
def run_trails(real_elev, scanned_elev, eventHandler, env, **kwargs):
    resulting = "trails2_slopedir"
    before = 'scan_saved'
    #env_crop = get_environment(raster=real_elev, n='n-100', s='s+100', e='e-100', w='w+100')
    analyses.change_detection(before=before,
                              after=scanned_elev,
                              change='change',
                              height_threshold=[60, 335],
                              cells_threshold=[3, 100],
                              add=True,
                              max_detected=10,
                              debug=True,
                              env=env)
    points = {}
    # start and end
    data = gscript.read_command('v.out.ascii',
                                input='trails2_points',
                                type='point',
                                format='point',
                                env=env).strip()
    c1, c2 = data.splitlines()
    c1 = c1.split('|')
    c2 = c2.split('|')
    points[0] = (float(c1[0]), float(c1[1]))
    points[1] = (float(c2[0]), float(c2[1]))

    # detected points
    points_raw = gscript.read_command('v.out.ascii',
                                      input='change',
                                      type='point',
                                      format='point').strip().split()
    i = 2
    for point in points_raw:
        point = point.split('|')
        point = (float(point[0]), float(point[1]))
        points[i] = point
        i += 1
    length = len(points)
    if length == 2:
        gscript.mapcalc("{} = null()".format(resulting), env=env)
        event = updateProfile(points=[])
        eventHandler.postEvent(receiver=eventHandler.activities_panel,
                               event=event)
        return

    # distance matrix
    D = []
    for i in range(length):
        D.append([0] * length)
    for p1 in range(0, length - 1):
        for p2 in range(p1 + 1, length):
            d = dist(points, p1, p2)
            D[p1][p2] = d
            D[p2][p1] = d
    # 0 distance for start and end to make sure it's always connected
    D[0][1] = 0
    D[1][0] = 0

    # solve
    solution = solve_tsp_numpy(D, optim_steps=10)
    # rearange solutions to start in start point
    ind1 = solution.index(0)
    ind2 = solution.index(1)
    if ind2 > ind1:
        solution = solution[::-1]
    ind = solution.index(0)
    solution = solution[ind:] + solution[:ind]

    # export line
    profile_points = []
    line = 'L {} 1\n'.format(len(solution))
    for i in solution:
        line += '{} {}\n'.format(points[i][0], points[i][1])
        profile_points.append(points[i])
    line += '1 1'
    gscript.write_command('v.in.ascii',
                          input='-',
                          stdin=line,
                          output='line',
                          format='standard',
                          flags='n',
                          env=env)

    env2 = get_environment(raster=before)
    # slope along line
    gscript.run_command('v.to.rast',
                        input='line',
                        type='line',
                        output='line_dir',
                        use='dir',
                        env=env2)
    gscript.run_command('r.slope.aspect',
                        elevation=before,
                        slope='saved_slope',
                        aspect='saved_aspect',
                        env=env2)
    gscript.mapcalc(
        "slope_dir = abs(atan(tan({slope}) * cos({aspect} - {line_dir})))".
        format(slope='saved_slope', aspect='saved_aspect',
               line_dir='line_dir'),
        env=env2)
    # set new color table
    colors = [
        '0 green', '7 green', '7 yellow', '15 yellow', '15 red', '90 red'
    ]
    gscript.write_command('r.colors',
                          map='slope_dir',
                          rules='-',
                          stdin='\n'.join(colors),
                          env=env2)
    # increase thickness
    gscript.run_command('r.grow',
                        input='slope_dir',
                        radius=2.1,
                        output=resulting,
                        env=env2)

    # update profile
    event = updateProfile(points=profile_points)
    eventHandler.postEvent(receiver=eventHandler.activities_panel, event=event)
    # copy results
    postfix = datetime.now().strftime('%H_%M_%S')
    prefix = 'trails2'
    gscript.run_command(
        'g.copy',
        raster=['slope_dir', '{}_slope_dir_{}'.format(prefix, postfix)],
        vector=['line', '{}_line_{}'.format(prefix, postfix)],
        env=env)
def run_road(real_elev, scanned_elev, eventHandler, env, **kwargs):
    env2 = get_environment(raster=real_elev)
    before = 'scan_saved'
    analyses.change_detection(before=before,
                              after=scanned_elev,
                              change='change',
                              height_threshold=[12, 80],
                              cells_threshold=[3, 70],
                              add=True,
                              max_detected=1,
                              debug=True,
                              env=env)
    point = gscript.read_command('v.out.ascii',
                                 input='change',
                                 type='point',
                                 format='point',
                                 env=env).strip()

    conn = 'transfer_connection'
    drain = 'transfer_drain'
    resulting = "transfer_slopedir"
    if point:
        x, y, cat = point.split('|')
        gscript.run_command('r.drain',
                            input='transfer_cost',
                            direction='transfer_costdir',
                            output=conn,
                            start_points='change',
                            drain=conn,
                            flags='d',
                            env=env2)

        gscript.run_command('v.to.rast',
                            input=conn,
                            type='line',
                            output=conn + '_dir',
                            use='dir',
                            env=env2)
        gscript.mapcalc(
            "slope_dir = abs(atan(tan({slope}) * cos({aspect} - {line_dir})))".
            format(slope='transfer_slope',
                   aspect='transfer_aspect',
                   line_dir=conn + '_dir'),
            env=env2)
        # set new color table
        colors = [
            '0 green', '5 green', '5 yellow', '12 yellow', '12 red', '90 red'
        ]
        gscript.write_command('r.colors',
                              map='slope_dir',
                              rules='-',
                              stdin='\n'.join(colors),
                              env=env2)
        # increase thickness

        gscript.run_command('r.grow',
                            input='slope_dir',
                            radius=1.8,
                            output=resulting,
                            env=env2)

        # drain
        gscript.run_command('r.drain',
                            input=real_elev,
                            output=drain,
                            start_points='change',
                            drain=drain,
                            env=env2)

        gscript.run_command('r.viewshed',
                            input=real_elev,
                            output='transfer_viewshed',
                            observer_elevation=67,
                            coordinates=[x, y],
                            flags='b',
                            env=env2)
        gscript.write_command('r.colors',
                              map='transfer_viewshed',
                              rules='-',
                              stdin='0 black',
                              env=env2)

        env3 = get_environment(raster='transfer_road')
        gscript.mapcalc(
            'visible_road = if(transfer_viewshed == 1 && ! isnull(transfer_road), 1, null())',
            env=env3)
        #road_full = float(gscript.parse_command('r.univar', map='transfer_road', flags='g', env=env3)['n'])
        road_full = 500  # number of road cells
        try:
            road_v = float(
                gscript.parse_command('r.univar',
                                      map='visible_road',
                                      flags='g',
                                      env=env3)['n'])
        except KeyError:
            road_v = 0
        event = updateDisplay(value=int(100 * road_v / road_full))

        with VectorTopo(conn, mode='r') as v:
            try:
                line = v.read(1)
                event2 = updateProfile(
                    points=[(line[0].x, line[0].y), (line[-1].x, line[-1].y)])
            except IndexError:
                event2 = updateProfile(points=[])
    else:
        gscript.run_command('v.edit', map=conn, tool='create', env=env)
        gscript.run_command('v.edit', map=drain, tool='create', env=env)
        gscript.mapcalc('{} = null()'.format(resulting), env=env)
        gscript.mapcalc('{} = null()'.format('transfer_viewshed'), env=env)
        event = updateDisplay(value=None)
        event2 = updateProfile(points=[])

    # update viewshed score
    eventHandler.postEvent(receiver=eventHandler.activities_panel, event=event)
    eventHandler.postEvent(receiver=eventHandler.activities_panel,
                           event=event2)

    # copy results
    if point:
        postfix = datetime.now().strftime('%H_%M_%S')
        prefix = 'transfer1'
        gscript.run_command(
            'g.copy',
            vector=['change', '{}_change_{}'.format(prefix, postfix)],
            raster=[
                'visible_road', '{}_visible_road_{}'.format(prefix, postfix)
            ],
            env=env)
        gscript.run_command(
            'g.copy',
            raster=['slope_dir', '{}_slope_dir_{}'.format(prefix, postfix)],
            env=env)
Esempio n. 18
0
def post_trails(real_elev, scanned_elev, filterResults, timeToFinish, logDir,
                env, **kwargs):
    env2 = get_environment(raster='scan_saved')
    gisenv = gscript.gisenv()
    logFile = os.path.join(
        logDir, 'log_{}_trails1.csv'.format(gisenv['LOCATION_NAME']))
    scoreFile = os.path.join(logDir,
                             'score_{}.csv'.format(gisenv['LOCATION_NAME']))
    slopes = gscript.list_grouped(
        type='raster', pattern="trails1_slope_dir_*_*_*")[gisenv['MAPSET']]
    lines = gscript.list_grouped(
        type='vector', pattern="trails1_line_*_*_*")[gisenv['MAPSET']]
    times = [each.split('_')[-3:] for each in slopes]
    score_sum = []
    score_max = []
    score_length = []
    score_points = []
    with open(logFile, 'w') as f:
        f.write(
            'time,slope_min,slope_max,slope_mean,slope_sum,length,point_count\n'
        )
        for i in range(len(slopes)):
            data_slopes = gscript.parse_command('r.univar',
                                                map=slopes[i],
                                                flags='g',
                                                env=env2)
            score_sum.append(float(data_slopes['sum']))
            score_max.append(float(data_slopes['max']))
            with VectorTopo(lines[i], mode='r') as v:
                try:
                    line = v.read(1)
                    point_count = len(line)
                    length = line.length()
                except IndexError:
                    length = 0
                    point_count = 0
                score_points.append(point_count)
                score_length.append(length)
            time = times[i]
            f.write(
                '{time},{sl_min},{sl_max},{sl_mean},{sl_sum},{length},{cnt}\n'.
                format(time='{}:{}:{}'.format(time[0], time[1], time[2]),
                       sl_min=data_slopes['min'],
                       sl_max=data_slopes['max'],
                       sl_mean=data_slopes['mean'],
                       sl_sum=data_slopes['sum'],
                       length=length,
                       cnt=point_count))
    with open(scoreFile, 'a') as f:
        # to make sure we don't get error if they skip quickly
        count = 3
        if len(score_points) < count:
            # shouldn't happen
            count = len(score_points)
        score_points = score_points[-count:]
        num_points = max(score_points)
        idx = score_points.index(num_points)
        slsum_score = score_sum[-count:][idx]
        slmax_score = score_max[-count:][idx]
        length_score = score_length[-count:][idx]

        # here convert to some scale?
        f.write("trails 1: sum slope: {}\n".format(slsum_score))
        f.write("trails 1: max slope: {}\n".format(slmax_score))
        f.write("trails 1: length line: {}\n".format(length_score))
        f.write("trails 1: filtered scans: {}\n".format(filterResults))
        f.write("trails 1: time: {}\n".format(timeToFinish))
Esempio n. 19
0
def run_trails(real_elev, scanned_elev, blender_path, eventHandler, env, **kwargs):
    env2 = get_environment(raster=scanned_elev, n='n-100', s='s+100', e='e-100', w='w+100')
    resulting = 'trail'
    trail = 'trail'
    before = 'scan_saved'
    topo_saved = 'topo_saved'
    #env_crop = get_environment(raster=real_elev, n='n-100', s='s+100', e='e-100', w='w+100')
    analyses.change_detection(before=before, after=scanned_elev,
                              change='change', height_threshold=[15, 100], cells_threshold=[5, 100], add=True, max_detected=13, debug=True, env=env2)
    points = {}
    # start and end
    data = gscript.read_command('v.out.ascii', input='trail_points', type='point', format='point', env=env).strip()
    c1, c2 = data.splitlines()
    c1 = c1.split('|')
    c2 = c2.split('|')
    points[0] = (float(c1[0]), float(c1[1]))
    points[1] = (float(c2[0]), float(c2[1]))

    gscript.run_command('v.edit', tool='create', map=trail, env=env)
    # detected points
    points_raw = gscript.read_command('v.out.ascii', input='change',
                                      type='point', format='point').strip().split()
    i = 2
    for point in points_raw:
        point = point.split('|')
        point = (float(point[0]), float(point[1]))
        points[i] = point
        i += 1
    length = len(points)
    if length == 2:
        gscript.mapcalc("{} = null()".format(resulting), env=env)
        event = updateProfile(points=[])
        eventHandler.postEvent(receiver=eventHandler.activities_panel, event=event)
        return

    # distance matrix
    D = []
    for i in range(length):
        D.append([0] * length)
    for p1 in range(0, length - 1):
        for p2 in range(p1 + 1, length):
            d = dist(points, p1, p2)
            D[p1][p2] = d
            D[p2][p1] = d
    # 0 distance for start and end to make sure it's always connected
    D[0][1] = 0
    D[1][0] = 0

    # solve
    solution = solve_tsp_numpy(D, optim_steps=10)
    # rearange solutions to start in start point
    ind1 = solution.index(0)
    ind2 = solution.index(1)
    if ind2 > ind1:
        solution = solution[::-1]
    ind = solution.index(0)
    solution = solution[ind :] + solution[:ind ]
    profile_points = []
    for i in solution:
        profile_points.append(points[i])
    #return
    # friction
    friction = 'friction'
    #gscript.mapcalc('{} = if(isnull(water), 0, null())'.format(friction), env=env)
    gscript.mapcalc('{} = 0'.format(friction), env=env)
    tmp_dir = 'tmp_dir'
    tmp_cost = 'tmp_cost'
    tmp_drain = 'tmp_drain'
    
    gscript.run_command('v.edit', tool='create', map=trail, env=env)
    for i in range(len(solution) - 1):
        gscript.run_command('r.walk', elevation=topo_saved, friction=friction, output=tmp_cost, outdir=tmp_dir,
                            start_coordinates=points[solution[i]], stop_coordinates=points[solution[i+1]], flags='k',
                            env=env)
        gscript.run_command('r.drain', input=tmp_cost, direction=tmp_dir, output=tmp_drain,
                            drain=tmp_drain, start_coordinates=points[solution[i+1]], flags='d', env=env)
        gscript.run_command('v.patch', input=tmp_drain, output=trail, flags='a', env=env)


    env2 = get_environment(raster=topo_saved)
    # slope along line
    gscript.run_command('v.to.rast', input=trail, type='line', output='trail_dir', use='dir', env=env2)
    gscript.run_command('r.slope.aspect', elevation=topo_saved, slope='saved_slope', aspect='saved_aspect', env=env2)
    gscript.mapcalc("slope_dir = abs(atan(tan({slope}) * cos({aspect} - {trail_dir})))".format(slope='saved_slope', aspect='saved_aspect',
                    trail_dir='trail_dir'), env=env2)
    # set new color table
    colors = ['0 green', '5 green', '5 yellow', '15 yellow', '15 red', '90 red']
    gscript.write_command('r.colors', map='slope_dir', rules='-', stdin='\n'.join(colors), env=env2)
    # increase thickness
    gscript.run_command('r.grow', input='slope_dir', radius=1.1, output=resulting, env=env2)
    

    # update profile
    event = updateProfile(points=profile_points)
    eventHandler.postEvent(receiver=eventHandler.activities_panel, event=event)
    
    gscript.mapcalc('toponds = if ( isnull(ponds), {t}, ponds + {t})'.format(t=topo_saved), env=env)
    gscript.run_command('v.generalize', input=trail, type='line', output=trail + 'gen', method='snakes', threshold=100, env=env)
    gscript.run_command('g.rename', vector=[trail + 'gen', trail], env=env)
    gscript.run_command('v.drape', input=trail, output=trail + '3d', elevation='toponds', env=env)
    blender_export_vector(vector=trail + '3d', name=trail, z=True, vtype='line', path=blender_path, time_suffix=False, env=env)
 def _defineEnvironment(self):
     self.env = None
     maps = gscript.read_command('i.group', flags='g', group=self.group, subgroup=self.group, quiet=True).strip()
     if maps:
         self.env = get_environment(raster=maps.splitlines()[0])
def run_felt(real_elev, scanned_elev, scanned_color, eventHandler, env,
             **kwargs):
    print('aaaa')

    compute_zoomed_region(real_elev,
                          scanned_elev,
                          kwargs['zoom_name'],
                          env=env)

    ##############################
    color_threshold = 90
    ###############################
    size_threshold = 10
    superpixels = 'superpixels'
    superpixels_filled = 'superpixels_filled'
    mean_color = 'mean_color'
    treatments = 'treatments'
    treatments_old = 'treatments_old'
    treatments_masked = 'treatments_masked'
    cross_test = 'cross_test'

    env = get_environment(raster=scanned_elev, n='n-200')
    gscript.run_command('i.superpixels.slic',
                        input=scanned_color,
                        output=superpixels,
                        step=8,
                        perturb=10,
                        compactness=1,
                        minsize=10,
                        memory=1000,
                        env=env)
    gscript.run_command('r.fill.stats',
                        flags='k',
                        input=superpixels,
                        output=superpixels_filled,
                        distance=3,
                        mode='mode',
                        cells=6,
                        env=env)
    gscript.mapcalc('{c} = ({r} + {g} + {b}) / 3.'.format(
        c=mean_color,
        r=scanned_color + '_r',
        g=scanned_color + '_g',
        b=scanned_color + '_b'),
                    env=env)
    data = gscript.read_command('r.univar',
                                flags='gt',
                                separator='comma',
                                map=mean_color,
                                zones=superpixels_filled,
                                env=env).strip().splitlines()
    data = np.genfromtxt(data, delimiter=',', skip_header=1)
    zones = list(data[(data[:, 7] < color_threshold)
                      & (data[:, 2] > size_threshold)][:, 0])
    #print "detected zones:", zones
    if not zones:
        gscript.mapcalc('{t} = null()'.format(t=treatments), env=env)

    condition = " || ".join(
        ['{c} == {n}'.format(c=superpixels_filled, n=int(z)) for z in zones])
    if not condition:
        event = updateDisplay(area=0)
        eventHandler.postEvent(receiver=eventHandler.pops_panel, event=event)
        return
    #gscript.mapcalc("{n} = if (({lide} > 0 || {inf} > 0) && ({c}), 1, null()) ".format(lide=lide, inf=inf, n=treatments, c=condition), env=env)
    gscript.mapcalc("{n} = if ({c}, 1, null()) ".format(n=treatments,
                                                        c=condition),
                    env=env)

    try:
        # is treatments_old doesn't exist, ignore this
        gscript.run_command('r.cross',
                            input=[treatments, treatments_old],
                            output=cross_test,
                            env=env)

        stats = gscript.read_command('r.stats',
                                     flags='cn',
                                     input=cross_test,
                                     env=env).strip().splitlines()
        changed_cells = total_cells = 0
        for line in stats:
            cat, ncells = line.split(' ')
            if cat in ('0', '1'):
                changed_cells += int(ncells)
            else:
                total_cells = int(ncells)

        if total_cells > 0:
            changed_ratio = changed_cells / float(total_cells)
            #print changed_ratio
            if changed_ratio < 0.2:
                return

    except CalledModuleError:
        gscript.mapcalc('{t} = null()'.format(t=treatments), env=env)
        gscript.mapcalc('{t} = null()'.format(t=treatments_old), env=env)
        event = updateDisplay(area=0)
        eventHandler.postEvent(receiver=eventHandler.pops_panel, event=event)


#    print 'changed cells:' + str(changed_cells)
#    print 'total cells:' + str(total_cells)

    gscript.run_command('g.copy', raster=[treatments, treatments_old], env=env)

    # price
    pops = kwargs['pops']
    gscript.mapcalc("{n} = if ({host} > 0, {t}, null())".format(
        host=pops['model']['host'],
        t=treatments,
        n=treatments + '_exclude_host_tmp'),
                    env=env)
    univar = gscript.parse_command('r.univar',
                                   map=treatments + '_exclude_host_tmp',
                                   flags='g',
                                   env=env)
    if univar and 'n' in univar:
        ncells = int(univar['n'])
        info = gscript.raster_info(treatments)
        res = (info['nsres'] + info['ewres']) / 2.
        area = ncells * res * res
    else:
        area = 0
    event = updateDisplay(area=area)
    eventHandler.postEvent(receiver=eventHandler.pops_panel, event=event)