Пример #1
0
 def shift_and_rescale(image, mask_arr):
     basename = os.path.splitext(os.path.basename(image))[0]
     image = arcpy.sa.Raster(image)
     mask = arcpy.NumPyArrayToRaster(mask_arr.astype(np.uint8) * 255)
     arcpy.env.outputCoordinateSystem = image
     os.makedirs(resources.temp_shifted, exist_ok=True)
     shifted = os.path.join(resources.temp_shifted,
                            "{}.tif".format(basename))
     arcpy.Shift_management(mask,
                            shifted,
                            image.extent.XMin - mask.extent.XMin,
                            image.extent.YMin - mask.extent.YMin,
                            in_snap_raster=image)
     # match LIDAR resolution
     os.makedirs(resources.temp_rescaled, exist_ok=True)
     rescaled = os.path.join(resources.temp_rescaled,
                             "{}.tif".format(basename))
     arcpy.Rescale_management(shifted, rescaled, image.meanCellWidth,
                              image.meanCellHeight)
     return rescaled
    if char in s:
        c = char[0]
        for ch in s:
            if ch == c:
                if s[index:index+len(char)] == char:
                    return index

            index += 1

    return -1

if find_str(pathLandsat, "199") != -1:
    foundDate = pathLandsat[find_str(pathLandsat, "199")+2:find_str(pathLandsat, "199")+8]
if find_str(pathLandsat, "200") != -1:
    foundDate = pathLandsat[find_str(pathLandsat, "200")+2:find_str(pathLandsat, "200")+8]
if find_str(pathLandsat, "201") != -1:
    foundDate = pathLandsat[find_str(pathLandsat, "201")+2:find_str(pathLandsat, "201")+8]
    
    
arcpy.Shift_management('intermedClipped',acoPath+ '\\FA_'+foundDate+cellSizeX+'_'+'m',yShift,xShift,pathLandsat)

#Cleans up by deleting intermediate files.
arcpy.Delete_management("intermedMir")
arcpy.Delete_management("intermedRot")
arcpy.Delete_management("intermedMir")
arcpy.Delete_management("intermedClass")
arcpy.Delete_management("intermedScale")
arcpy.Delete_management("intermedClipped")
arcpy.Delete_management("dataMask")

        logic3 = (result_std[iteration-1] - result_std[iteration])/(result_std[iteration-1]+1e-4) < 0.02
        logic4 = logic2 and logic3

        if logic1 or logic4:
            DEM_final = "DEMsh" + str(iteration-1)
            sum_ShiftX = np.sum(ShiftX)
            sum_ShiftY = np.sum(ShiftY)

            # final shift vector [unit: m]
            shiftVec = [sum_ShiftX, sum_ShiftY]
            np.savetxt(file_shiftVec, shiftVec, delimiter=',')

            arcpy.AddMessage("********************Final Result********************")
            arcpy.AddMessage("Note: results are saved in {0}".format(dirOutputs))
            arcpy.AddMessage("The final shifted DEM: {0}".format(DEM_final))
            arcpy.AddMessage("The final shift X: {0:.1f}".format(sum_ShiftX))
            arcpy.AddMessage("The final shift Y: {0:.1f}".format(sum_ShiftY))
            break

    # Output shifted DEM
    DEM_after = "DEMsh" + str(iteration)
    arcpy.Shift_management(DEM_before, DEM_after, str(ShiftX1), str(ShiftY1))
    DEM_before = DEM_after

for i in range(iteration-1):
    iter_tag = i+1
    indata_del = "DEMsh"+str(iter_tag)
    arcpy.Delete_management(indata_del)
    
endTime = time.clock()
arcpy.AddMessage("Running time: {0}".format(int(endTime-startTime)))
Пример #4
0
    return -1


if find_str(pathOriginal, "201") != -1:
    foundDate = pathOriginal[find_str(pathOriginal, "201") +
                             2:find_str(pathOriginal, "201") + 8]
if find_str(pathOriginal, "200") != -1:
    foundDate = pathOriginal[find_str(pathOriginal, "200") +
                             2:find_str(pathOriginal, "200") + 8]
if find_str(pathOriginal, "199") != -1:
    foundDate = pathOriginal[find_str(pathOriginal, "199") +
                             2:find_str(pathOriginal, "199") + 8]
print "Done naming"

arcpy.env.snapRaster = pathOriginal

arcpy.Shift_management('intermedScale',
                       acoPath + '\\FA_' + foundDate + '_' + cellSizeX + 'm',
                       yShift, xShift, pathOriginal)

#Cleans up by deleting intermediate files.
arcpy.Delete_management("intermedMir")
arcpy.Delete_management("intermedRot")
arcpy.Delete_management("intermedMir")
arcpy.Delete_management("intermedClass")
arcpy.Delete_management("intermedScale")
arcpy.Delete_management("intermedClipped")
arcpy.Delete_management("dataMask")

print "Done"
Пример #5
0
def main(in_raster=None, out_raster=None, area_raster=None):
    """
    A calculation of rugosity, based on the difference between surface
    area and planar area, as described in Jenness, J. 2002. Surface Areas
    and Ratios from Elevation Grid (surfgrids.avx) extension for ArcView 3.x,
    v. 1.2. Jenness Enterprises.

    NOTE: the VRM method implemented in ruggeddness is generally considered
          superior to this method.
    """
    out_workspace = os.path.dirname(out_raster)
    # make sure workspace exists
    utils.workspace_exists(out_workspace)

    utils.msg("Set scratch workspace to {}...".format(out_workspace))

    # force temporary stats to be computed in our output workspace
    arcpy.env.scratchWorkspace = out_workspace
    arcpy.env.workspace = out_workspace
    pyramid_orig = arcpy.env.pyramid
    arcpy.env.pyramid = "NONE"
    # TODO: currently set to automatically overwrite, expose this as option
    arcpy.env.overwriteOutput = True

    bathy = Raster(in_raster)
    desc = arcpy.Describe(bathy)
    # get the cell size of the input raster; use same calculation as was
    # performed in BTM v1: (mean_x + mean_y) / 2
    cell_size = (desc.meanCellWidth + desc.meanCellHeight) / 2.0
    corner_dist = math.sqrt(2 * cell_size**2)
    flat_area = cell_size**2
    utils.msg("Cell size: {}\nFlat area: {}".format(cell_size, flat_area))

    try:
        # Create a set of shifted grids, with offets n from the origin X:

        #        8 | 7 | 6
        #        --|---|---
        #        5 | X | 4
        #        --|---|---
        #        3 | 2 | 1

        positions = [(1, -1), (0, -1), (-1, -1), (1, 0), (-1, 0), (1, 1),
                     (0, 1), (-1, 1)]

        corners = (1, 3, 6, 8)  # dist * sqrt(2), as set in corner_dist
        orthogonals = (2, 4, 5, 7)  # von Neumann neighbors, straight dist
        shift_rasts = [None]  # offset to align numbers
        temp_rasts = []

        for (n, pos) in enumerate(positions, start=1):
            utils.msg("Creating Shift Grid {} of 8...".format(n))
            # scale shift grid by cell size
            (x_shift, y_shift) = map(lambda (n): n * cell_size, pos)

            # set explicit path on shift rasters, otherwise suffer
            # inexplicable 999999 errors.
            shift_out = os.path.join(out_workspace, "shift_{}.tif".format(n))
            shift_out = utils.validate_path(shift_out)
            temp_rasts.append(shift_out)
            arcpy.Shift_management(bathy, shift_out, x_shift, y_shift)
            shift_rasts.append(arcpy.sa.Raster(shift_out))

        edge_rasts = [None]
        # calculate triangle length grids

        # edges 1-8: pairs of bathy:shift[n]
        for (n, shift) in enumerate(shift_rasts[1:], start=1):
            utils.msg("Calculating Triangle Edge {} of 16...".format(n))
            # adjust for corners being sqrt(2) from center
            if n in corners:
                dist = corner_dist
            else:
                dist = cell_size
            edge_out = os.path.join(out_workspace, "edge_{}.tif".format(n))
            edge_out = utils.validate_path(edge_out)
            temp_rasts.append(edge_out)
            edge = compute_edge(bathy, shift, dist)
            edge.save(edge_out)
            edge_rasts.append(arcpy.sa.Raster(edge_out))

        # edges 9-16: pairs of adjacent shift grids [see layout above]
        # in BTM_v1, these are labeled A-H
        adjacent_shift = [(1, 2), (2, 3), (1, 4), (3, 5), (6, 4), (5, 8),
                          (6, 7), (7, 8)]
        for (n, pair) in enumerate(adjacent_shift, start=9):
            utils.msg("Calculating Triangle Edge {} of 16...".format(n))
            # the two shift rasters for this iteration
            (i, j) = pair
            edge_out = os.path.join(out_workspace, "edge_{}.tif".format(n))
            edge_out = utils.validate_path(edge_out)
            temp_rasts.append(edge_out)
            edge = compute_edge(shift_rasts[i], shift_rasts[j], cell_size)
            edge.save(edge_out)
            edge_rasts.append(arcpy.sa.Raster(edge_out))

        # areas of each triangle
        areas = []
        for (n, pair) in enumerate(adjacent_shift, start=1):
            utils.msg("Calculating Triangle Area {} of 8...".format(n))
            # the two shift rasters; n has the third side
            (i, j) = pair
            area_out = os.path.join(out_workspace, "area_{}.tif".format(n))
            area_out = utils.validate_path(area_out)
            temp_rasts.append(area_out)

            area = triangle_area(edge_rasts[i], edge_rasts[j],
                                 edge_rasts[n + 8])
            area.save(area_out)
            areas.append(arcpy.sa.Raster(area_out))

        utils.msg("Summing Triangle Area...")
        arcpy.env.pyramid = pyramid_orig
        arcpy.env.rasterStatistics = "STATISTICS"
        total_area = (areas[0] + areas[1] + areas[2] + areas[3] + areas[4] +
                      areas[5] + areas[6] + areas[7])
        if area_raster:
            save_msg = "Saving Surface Area Raster to " + \
                "{}.".format(area_raster)
            utils.msg(save_msg)
            total_area.save(area_raster)

        area_ratio = total_area / cell_size**2

        out_raster = utils.validate_path(out_raster)
        save_msg = "Saving Surface Area to Planar Area ratio to " + \
            "{}.".format(out_raster)
        utils.msg(save_msg)
        area_ratio.save(out_raster)

    except Exception as e:
        utils.msg(e, mtype='error')

    try:
        # Delete all intermediate raster data sets
        utils.msg("Deleting intermediate data...")
        for path in temp_rasts:
            arcpy.Delete_management(path)

    except Exception as e:
        utils.msg(e, mtype='error')
Пример #6
0
def Guidos_Post(city, inDir, workFld):
    import traceback, time, arcpy, os, subprocess
    from arcpy import env
    arcpy.CheckOutExtension('Spatial')

#-------- DIRECTORY SETUP ------------------------------------------------
    """ Working Directory """
    if arcpy.Exists(str(workFld) + '/' + city + '_GUIDOS.gdb') == False:
        arcpy.CreateFileGDB_management(str(workFld), str(city) + '_GUIDOS.gdb')
    else:
        pass
    workDir = str(workFld) + '/' + city + '_GUIDOS.gdb'
    arcpy.env.workspace = workDir

    """ Report File Directory """
    reportfileDir = str(workFld) + '/Logs'
    """ Frequent Directory """
    freqDir = str(workFld) + '/' + city +'_Freq.gdb'
    """ Final Geodatabase """
    finalDir = str(workFld) + '/' + city + '_Final.gdb'

    """ Projection File Directory """
    prjDir = str(inDir) + '/Prj'

    """ Split Raster Directory """
    if os.path.isdir(str(workFld) + '/' + city + '_Split') == True:
        pass
    else:
        os.makedirs(str(workFld) + '/' + city + '_Split')
    splitDir = str(workFld) + '/' + city + '_Split'

    """ Set Workspace Environments """
    arcpy.env.workspace = workDir
    arcpy.env.scratch = str(inDir) + '/Scratch.gdb'
    arcpy.env.overwriteOutput = True

    #-----------------------------------------------------------------------------
    # BEGIN ANALYSIS
	#-----------------------------------------------------------------------------
    try:
        #-------- LOGFILE CREATION ---------------------------------------------
        """ Create report file for each metric """
##        try:
        loglist = sorted(f for f in os.listdir(reportfileDir) if f.startswith(str(city) + '_Conn'))
        tmpName = loglist[-1]
##        except:
##            tmpName = city + '_Conn_' + time.strftime('%Y%m%d_%H-%M')  + '.txt'
        reportfileName = reportfileDir + '/' + tmpName

        try:
			reportFile = open(reportfileName, 'a')
        except:
			reportFile = open(reportfileName, 'w')
			print 'No log for GUIDOS_Prep'

        try:
            loglist = sorted (f for f in os.listdir(reportfileDir) if f.startswith(str(city) + '_Reuse'))
            tmpName = loglist[-1]
        except:
            tmpName = city + '_Reuse_' + time.strftime('%Y%m%d_%H-%M')  + '.txt'
        reportfileName = reportfileDir + '/' + tmpName

        try:
			ReuseRF = open(reportfileName, 'a')
        except:
            ReuseRF = open(reportfileName, 'w')
            print 'Creating Reuse Log'

        print 'Connectivity Start Time: ' + time.asctime()
        reportFile.write("For each piece, convert the raster from a tiled TIFF to a striped TIFF.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        #-------- PROCESSING LAYERS ----------------------------------------------
        """ Set Environments """
        #Figure out the correct UTM Zone
        prjNumb = arcpy.Describe(str(freqDir) + '/LC').spatialReference.name
        prjNumb = prjNumb[-3:]
        prjfileUTM = prjDir + '/NAD 1983 UTM Zone ' + prjNumb + '.prj'

        AllRast = 'yes'

        """ -------- RUN GUIDOS ---------------------------------------------- """
        arcpy.env.workspace = splitDir
    	guidlist = arcpy.ListRasters('S_FWW*')
    	""" For each raster piece, run GUIDOS """
    	for r in guidlist:
			guidexe = str(inDir) + '/mspa_win64.exe'
			inrast = str(splitDir) + '/' + str(r)
			outrast = 'G_' + str(r)
			outdir = str(splitDir) + '/'
			argu = (guidexe, '-i', inrast, '-o', outrast, '-eew', '30', '-internal', '0', '-odir', outdir, '-transition', '0')
			subprocess.call(argu)

			""" If GUIDOS worked, Reproject the rasters """
			if arcpy.Exists(outrast) == True:
				# Project the output raster
				oLeft = arcpy.GetRasterProperties_management(r, "LEFT").getOutput(0)
				oBottom = arcpy.GetRasterProperties_management(r, "BOTTOM").getOutput(0)
				nBottom = arcpy.GetRasterProperties_management(outrast, 'BOTTOM').getOutput(0)

				xMove = float(oLeft) + 0.5
				yMove = float(oBottom) - float(nBottom)

				arcpy.Shift_management(outrast, 'Sh_' + str(r), xMove, yMove, r)

				numb = r.replace('S_FWW_WB_', '')

				arcpy.env.extent = "MAXOF"
				arcpy.env.snapRaster = str(splitDir) + '/' + str(r)
				descLC = arcpy.Describe(str(freqDir) + '/LC')
				arcpy.ProjectRaster_management('Sh_' + str(r), 'Conn_' + str(numb), descLC.spatialReference, '', '', '', '', descLC.spatialReference)
			else:
				""" If GUIDOS didn't work, quit after loop """
				AllRast = 'no'
				print str(outrast) + ' not run properly'

        reportFile.write("For each piece, run the GUIDOS (Graphical User Interface for the Description of image Objects and their Shapes) v2.1 MSPA (Morphological Spatial Pattern Analysis) Standalone Tool (http://forest.jrc.ec.europa.eu/download/software/guidos) using 8 neighbor connectivity, 30 pixel edge, transition off, and intext off.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        reportFile.write("Project each GUIDOS piece into UTM, shifting to the location of the original piece.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """-------- If all the GUIDOS Rasters worked, Post-Process ------------ """
        if AllRast == 'yes':
            """-------- Split the Raster As Needs, Process Each Piece ----------------- """
            """ Check if the raster should be split """
            columns = arcpy.GetRasterProperties_management(splitDir + '/FWW_WB.tif', 'COLUMNCOUNT').getOutput(0)
            xsplit = int(float(columns) / 8000) + 1
            rows = arcpy.GetRasterProperties_management(splitDir + '/FWW_WB.tif', 'ROWCOUNT').getOutput(0)
            ysplit = int (float(rows) / 8000) + 1

            """-------- If no split, run the analysis --------------------------------- """
            if xsplit*ysplit == 1:
                """ Copy Raster """
                arcpy.CopyRaster_management(splitDir + '/Conn.TIF', workDir + '/Conn')
                reportFile.write("Copy Tiff into Working GDB.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

                """-------- If split, run the analysis on each piece and recombine --------- """
            else:
                """ Set Environments """
                arcpy.env.extent = 'FWW_WB.tif'
                arcpy.env.snapRaster = 'FWW_WB.tif'

                """ Split the Raster """
                arcpy.SplitRaster_management('FWW_WB.tif', splitDir, 'NoO_WB_', 'NUMBER_OF_TILES', 'TIFF', '', str(xsplit) + ' ' + str(ysplit), '',  '', '')
                reportFile.write("Split the reclassified land cover into the same pieces as previous but with no overlap.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

                """ Clip the overlap off the tiles """
                pieces = int(xsplit) * int(ysplit)
                for tiles in range(int(pieces)):
                    if arcpy.Exists('NoO_WB_' + str(tiles) + '.TIF') == True:
                        """ Set Environments """
                        arcpy.env.extent = 'NoO_WB_' + str(tiles) + '.TIF'
                        arcpy.env.snapRaster = 'NoO_WB_' + str(tiles) + '.TIF'

                        """ Extract the Area of Interest """
                        EbM = arcpy.sa.ExtractByMask('Conn_' + str(tiles) + '.TIF', 'NoO_WB_' + str(tiles) + '.TIF')
                        EbM.save(workDir + '/Conn_' + str(tiles))
                    else:
                        pass
                reportFile.write("Clip each GUIDOS output to the corresponding piece of the second raster split to eliminate overlap.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

                """ Set Environments """
                arcpy.env.extent = workDir + '/FWW_WB'
                arcpy.env.snapRaster = workDir + '/FWW_WB'
                arcpy.env.workspace = workDir

                """ Mosaic tiles together """
                RastList = arcpy.ListRasters('Conn_*')
                arcpy.MosaicToNewRaster_management(RastList, workDir, 'Conn', '', '8_BIT_UNSIGNED', 1, 1, '', '')
                reportFile.write("Mosaic all of the clipped GUIDOS output tiles into one raster.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

            """ Burn water into the Output Raster """
            watercon = arcpy.sa.Con(freqDir + '/LC', 10, 'Conn', 'value = 10')
            watercon.save('Conn_WithWat')
            reportFile.write("Using the original land cover, burn water pixels into raster using a conditional statement if Land Cover Value = 10; for true: 10; for false: GUIDOS raster.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

            """--------- Clip the EA Boundaries to the County Lines, if necessary ----- """
            if arcpy.Exists(str(freqDir) + '/Bnd_Cty') == False:
                """ Copy Counties to Frequent and Project """
                arcpy.MakeFeatureLayer_management(str(inDir) + '/Input.gdb/Counties_Alb', 'Cty')
                arcpy.SelectLayerByLocation_management('Cty', 'CONTAINS', 'BG_Alb', '', 'NEW_SELECTION')
                arcpy.FeatureClassToFeatureClass_conversion(str(inDir) + '/Input.gdb/Counties_Alb', str(freqDir), 'Counties_Alb')
                arcpy.SelectLayerByAttribute_management('Cty', 'CLEAR_SELECTION')
                descLC = arcpy.Describe(str(freqDir) + '/LC')
                arcpy.Project_management('Counties_Alb', 'Counties', descLC.spatialReference)

                """ Clip Boundary to County Lines """
                arcpy.Clip_analysis(str(freqDir) + '/Bnd', str(freqDir) + '/Counties', str(freqDir) + '/Bnd_Cty')
                reportFile.write("Clip the EnviroAtlas Community Boundary to the county lines for the community to limit the output to land area.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')
                ReuseRF.write("Bnd_Cty--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')
            else:
                reportFile.write("Clip the EnviroAtlas Community Boundary to the county lines for the community to limit the output to land area.--Bnd_Cty" + '--\n')

        	"""-------- Check that the Analysis Area is covered by the LC -------------- """
        	""" Create a Polygon Version of the LC """
            if arcpy.Exists(freqDir + '/LC_Poly') == False:
                arcpy.env.snapRaster = str(freqDir) + '/LC'
                arcpy.env.extent = str(freqDir) + '/LC'
                ReC = arcpy.sa.Reclassify(str(freqDir) + '/LC', 'Value', arcpy.sa.RemapValue([[0,0],[10,1],[20,1],[21,1],[22,1],[30,1],[40,1],[52,1],[70,1],[80,1],[82,1],[91,1],[92,1]]))
                ReC.save(str(freqDir) + '/AreaIO')
                arcpy.RasterToPolygon_conversion(str(freqDir) + '/AreaIO', str(freqDir) + '/LC_Poly', 'SIMPLIFY')
                arcpy.env.extent = workDir + '/FWW_WB'
                arcpy.env.snapRaster = workDir + '/FWW_WB'

            """ Buffer the LC Polygon by -500m """
            if arcpy.Exists(freqDir + '/Bnd_Cty_500m') == False:
    			arcpy.Buffer_analysis(str(freqDir) + '/Bnd_Cty', str(freqDir) + '/Bnd_Cty_500m', '500 meters')
    			arcpy.EliminatePolygonPart_management(str(freqDir) + '/Bnd_Cty_500m', str(freqDir) + '/Bnd_Cty_500m_EP', 'PERCENT', '', '30', 'CONTAINED_ONLY')
    			arcpy.Delete_management(str(freqDir) + '/Bnd_Cty_500m')
    			arcpy.Rename_management(str(freqDir) + '/Bnd_Cty_500m_EP', str(freqDir) + '/Bnd_Cty_500m')

            """ Identify whether LC is large enough """
            arcpy.MakeFeatureLayer_management(str(freqDir) + '/LC_Poly', 'LClyr')
            arcpy.MakeFeatureLayer_management(str(freqDir) + '/Bnd_Cty_500m', 'BC_500lyr')

            arcpy.SelectLayerByLocation_management('BC_500lyr', 'COMPLETELY_WITHIN', 'LClyr', '', 'NEW_SELECTION')
            bigEnough = float(arcpy.GetCount_management('BC_500lyr').getOutput(0))
            arcpy.SelectLayerByAttribute_management('BC_500lyr', 'CLEAR_SELECTION')

            """ If the LC isn't large enough, edit erroneous BGS """
            if bigEnough == 0:
    			arcpy.Clip_analysis(freqDir + '/Bnd_Cty', freqDir + '/LC_Poly', 'Bnd_Cty_LC')
    			reportFile.write("Because the community boundary extends beyond the Land Cover, clip the boundary to the land cover.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

            """ Clip the Raster to Bnd_Cty """
            try:
    			EbM = arcpy.sa.ExtractByMask('Conn_WithWat', 'Bnd_Cty_LC')
            except:
    			EbM = arcpy.sa.ExtractByMask('Conn_WithWat', freqDir + '/Bnd_Cty')
            EbM.save('Conn_Bnd')
            reportFile.write("Extract by Mask the area of the projected raster that is within the clipped EnviroAtlas Community Boundary.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

            """ Add Colormap """
            arcpy.AddColormap_management('Conn_Bnd', '', str(inDir) + '/Templates/GUIDOS2.clr')

            """ Convert to TIFF for sharing """
            arcpy.CopyRaster_management('Conn_Bnd', splitDir + '/' + str(city) + '_Conn.tif')
            reportFile.write("Add a default GUIDOS colormap to the final raster from any of the original GUIDOS output tiles.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

            """ Convert to Web Mercator """
            prjfileWM = prjDir + '/WGS 1984 Web Mercator (auxiliary sphere).prj'
            if arcpy.Exists(freqDir + '/Bnd_WM') == False:
                arcpy.Project_management(freqDir + '/Bnd', freqDir + '/Bnd_WM', prjfileWM)
            arcpy.env.extent = freqDir + '/Bnd_WM'
            arcpy.ProjectRaster_management('Conn_Bnd', 'Conn_WM', prjfileWM)
            reportFile.write("Convert raster into TIFF format for distribution.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

            """ Copy to Final Directory """
            arcpy.CopyRaster_management('Conn_WM', finalDir + '/' + str(city) + '_Conn')
    ##            reportFile.write("Step 15--Copy to Final GDB--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

            print 'GUIDOS End Time: ' + time.asctime()

        else:
            print 'Some MSPA functions did not complete. Please run manually.'
        #-------------------------------------------------------------------------

        #-------- COMPELETE LOGFILES ---------------------------------------------
        reportFile.close()
    	ReuseRF.close()

	#-----------------------------------------------------------------------------
    # END ANALYSIS
	#-----------------------------------------------------------------------------
    except:
        """ This part of the script executes if anything went wrong in the main script above """
        #-------- PRINT ERRORS ---------------------------------------------------
        print "\nSomething went wrong.\n\n"
        print "Python Traceback Message below:"
        print traceback.format_exc()
        print "\nArcMap Error Messages below:"
        print arcpy.GetMessages(2)
        print "\nArcMap Warning Messages below:"
        print arcpy.GetMessages(1)

        #-------- COMPLETE LOGFILE ------------------------------------------------
        reportFile.write("\nSomething went wrong.\n\n")
        reportFile.write("Pyton Traceback Message below:")
        reportFile.write(traceback.format_exc())
        reportFile.write("\nArcMap Error Messages below:")
        reportFile.write(arcpy.GetMessages(2))
        reportFile.write("\nArcMap Warning Messages below:")
        reportFile.write(arcpy.GetMessages(1))

        reportFile.write( "\n\nEnded at " + time.asctime() + '\n')
        reportFile.write("\n---End of Log File---\n")

        if reportFile:
            reportFile.close()
def postproc_v(width, bed, dem, res_folder):

    result = arcpy.Raster(os.path.join(res_folder, "lisflood_res"))

    arcpy.env.workspace = res_folder

    elev_rasters = arcpy.ListRasters("elev_zone*")
    Vx_rasters = []
    Vy_rasters = []
    Vch_rasters = []
    tmp_elev_rasters = []
    # Loop to create lists of the qx, qy and elevation raster (with -9999 instead of NoData) results
    for elev_raster in elev_rasters:
        # create a temp version of elev_zone* by replacing NoData by -9999 for the full extent
        # (used latter for the HighestPosition / Pick process
        with arcpy.EnvManager(extent=result):
            tmp_elev_raster = arcpy.sa.Con(
                arcpy.sa.IsNull(elev_raster) == 1, -9999, elev_raster)
        tmp_elev_raster.save(
            os.path.join(arcpy.env.scratchWorkspace,
                         "tmp_e_" + elev_raster[5:]))
        tmp_elev_rasters.append(
            os.path.join(arcpy.env.scratchWorkspace,
                         "tmp_e_" + elev_raster[5:]))
        qx_raster = os.path.join(res_folder, "res",
                                 elev_raster[5:] + "_Qx.asc")
        qy_raster = os.path.join(res_folder, "res",
                                 elev_raster[5:] + "_Qy.asc")
        print(elev_raster[5:])
        ### Computing the velocity
        # replace NoData by 0 (so the mean is than correctly computed)
        qx_raster = arcpy.sa.Con(arcpy.sa.IsNull(qx_raster) == 1, 0, qx_raster)
        qy_raster = arcpy.sa.Con(arcpy.sa.IsNull(qy_raster) == 1, 0, qy_raster)
        # The average of both cells (2 cells horizontally for qx, 2 vertically for qy) must be taken
        # Focal Statistics with a 1x2 (or 2x1) compute the average. The results are than shifted to snap the elevation raster
        # NbrRectangle(2,1) take the original cell and its right one, so the shift is to the right (positive)
        # NbrRectangle(1,2) take the original cell and its bottom one, so the shift is downward (negative)
        mean = arcpy.sa.FocalStatistics(qx_raster,
                                        arcpy.sa.NbrRectangle(2, 1, "CELL"),
                                        "MEAN", "NODATA")
        arcpy.Shift_management(
            mean, os.path.join(arcpy.env.scratchWorkspace, "qxmean"),
            qx_raster.meanCellWidth / 2., 0, result)
        mean = arcpy.sa.FocalStatistics(qy_raster,
                                        arcpy.sa.NbrRectangle(1, 2, "CELL"),
                                        "MEAN", "NODATA")
        arcpy.Shift_management(
            mean, os.path.join(arcpy.env.scratchWorkspace, "qymean"), 0,
            -qy_raster.meanCellHeight / 2., result)
        arcpy.DefineProjection_management(
            os.path.join(arcpy.env.scratchWorkspace, "qxmean"), bed)
        arcpy.DefineProjection_management(
            os.path.join(arcpy.env.scratchWorkspace, "qymean"), bed)

        # converting the q in v in the channel
        area = (result - bed) * width
        v = (arcpy.sa.Abs(
            arcpy.Raster(os.path.join(arcpy.env.scratchWorkspace, "qxmean"))) +
             arcpy.sa.Abs(
                 arcpy.Raster(
                     os.path.join(arcpy.env.scratchWorkspace,
                                  "qymean")))) / area
        v.save(
            os.path.join(arcpy.env.scratchWorkspace, "vch_" + elev_raster[5:]))
        Vch_rasters.append(
            os.path.join(arcpy.env.scratchWorkspace, "vch_" + elev_raster[5:]))
        # converting the qx in vx in the floodplain
        area = arcpy.sa.Con(arcpy.sa.IsNull(width),
                            (result - dem) * result.meanCellHeight)
        area2 = arcpy.sa.SetNull(area, area, "VALUE <= 0")
        v = arcpy.Raster(os.path.join(arcpy.env.scratchWorkspace,
                                      "qxmean")) / area2
        v.save(
            os.path.join(arcpy.env.scratchWorkspace, "vx_" + elev_raster[5:]))
        Vx_rasters.append(
            os.path.join(arcpy.env.scratchWorkspace, "vx_" + elev_raster[5:]))
        # converting the qy in vy in the floodplain
        area = arcpy.sa.Con(arcpy.sa.IsNull(width),
                            (result - dem) * result.meanCellWidth)
        area2 = arcpy.sa.SetNull(area, area, "VALUE <= 0")
        v = arcpy.Raster(os.path.join(arcpy.env.scratchWorkspace,
                                      "qymean")) / area2
        v.save(
            os.path.join(arcpy.env.scratchWorkspace, "vy_" + elev_raster[5:]))
        Vy_rasters.append(
            os.path.join(arcpy.env.scratchWorkspace, "vy_" + elev_raster[5:]))

    ### Merging the qx and qy results by taking the value where the elevation is the maximum
    ### based on the usage of HighestPosition (with the elevation), then Pick
    # create a raster indicating which zone has the maximum elevation
    max_id = arcpy.sa.HighestPosition(tmp_elev_rasters)
    # Pick merge the vx, vy and vch rasters
    with arcpy.EnvManager(extent=max_id):
        vx_raster = arcpy.sa.Pick(max_id, Vx_rasters)
        vy_raster = arcpy.sa.Pick(max_id, Vy_rasters)
        vch_raster = arcpy.sa.Pick(max_id, Vch_rasters)
        vx_raster.save(os.path.join(res_folder, "vx"))
        vy_raster.save(os.path.join(res_folder, "vy"))
        vch_raster.save(os.path.join(res_folder, "v_channel"))

    # cleaning temp results
    arcpy.Delete_management("qymean")
    arcpy.Delete_management("qxmean")
    for raster in tmp_elev_rasters:
        arcpy.Delete_management(raster)
    for raster in Vx_rasters:
        arcpy.Delete_management(raster)
    for raster in Vy_rasters:
        arcpy.Delete_management(raster)
    for raster in Vch_rasters:
        arcpy.Delete_management(raster)