Thursday, June 22, 2017

Python - Create Forecast Video and PDF

After generating water depth and water surface elevation layers from a processed DEM up to 20' feet @ 0.5' interval. This script converts flood layers into a Video animation and PDF image of each of the flood layers.

'''----------------------------------------------------------------------------
 Tool Name:   Create Forecast Video and PDF
 Source Name: createforecastvideoandpdf.py
 Version:     ArcGIS 10.3.1
 Author:      Prashant Kuranjekar
----------------------------------------------------------------------------'''
import os
import sys
import arcpy
import inspect
import apwrutils
import njtconfig
import datetime
import time
import dateutil
from dateutil import parser


def trace():
    import traceback, inspect
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    # script name + line number
    line = tbinfo.split(", ")[1]
    filename = inspect.getfile(inspect.currentframe())
    # Get Python syntax error
    synerror = traceback.format_exc().splitlines()[-1]
    return line, filename, synerror

class CreateForecastVideoandPDF(object):
 
    def __init__(self):
        self.bCallFromPYT = True
        """Define the tool (tool name is the name of the class)."""
        self.label = 'Forecast Processing'
        self.category=''
        self.description = 'Performs forecast processing.'
        self.canRunInBackground = True

    def getParameterInfo(self):
        """Define parameter definitions"""
        return

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        if arcpy.CheckExtension("Spatial") == "Available":
            return True
        else:
            return False

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parmater
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""
        debug=0 # temporary fc are deleted if debug = 0
        sOK = njtconfig.C_OK
        ds = time.clock()
        dds = time.clock()
        listtodel=[]
        starttime=None
        endtime=None
        processstatus=njtconfig.processStatus.Success
        maxforecasthour=999
        mxd=None
        bcreatevideo = True

        try:
            in_mxdpath = parameters[0]      
            in_workspace = parameters[1]
            in_facilitynameprefix = parameters[2]
            in_modelname = parameters[3]
            in_forecasttime = parameters[4]
            in_outputfolder = parameters[5]

            if len(parameters)>6:
                increatevideo = parameters[6]
            if len(parameters)>7:
                inframeduration = parameters[7]

            #Parse optional increatevideo
            screatevideo = str(increatevideo)
            if screatevideo.lower()=="false":
                bcreatevideo=False
            #Parse optional inframeduration
            if bcreatevideo:
                try:
                    dframeduration = float(inframeduration)
                except:
                    arcpy.AddMessage("Using default frame duration set to 2 s.")
                    dframeduration = 2

            #Template mxd location
            #mxdpath=r"C:\Project\Trunk\NJTTSMgr\mxd\Animation_NOAA150\Animation_NOAA150.mxd"
            mxd = arcpy.mapping.MapDocument(in_mxdpath)

            arcpy.env.workspace = in_outputfolder

            #Point to database
            if in_workspace.lower().endswith(".gdb"):
                whereclause = njtconfig.FN_MODELNAME + "='" + in_modelname + "' AND " + njtconfig.FN_FORECASTTIME + "=date'" + in_forecasttime + "'"
            elif in_workspace.lower().endswith(".sde"):
                whereclause = njtconfig.FN_MODELNAME + "='" + in_modelname + "' AND " + njtconfig.FN_FORECASTTIME + "='" + in_forecasttime + "'"
            else:
                 arcpy.AddError("Input workspace must be a filegeodatabase or a remote geodatabase.")
                 processstatus=processstatus=njtconfig.processStatus.InvalidWorkspace
                 return(njtconfig.C_NOTOK,processstatus)

            arcpy.AddMessage("Where clause: " + whereclause)

            videolayers=dict()
            videolayers.setdefault("Assets",njtconfig.LN_ASSETSFORECAST)
            videolayers.setdefault("Site Boundary",njtconfig.LN_SITEBOUNDARY)
            videolayers.setdefault("Flood Depth Contour",njtconfig.LN_FORECASTFLOODEXTENT)


            #Repoint mxd to data of interest
            #assets into baseassets
            #siteboundary into site boundary
            #floodbase contour into floodextent
                     

            for lyr in arcpy.mapping.ListLayers(mxd):
                if lyr.supports("DATASOURCE"):
                    if lyr.name in videolayers:
                        lyr.replaceDataSource(in_workspace,"SDE_WORKSPACE",videolayers[lyr.name],False)
                        if arcpy.Exists(lyr.dataSource)==False:
                            arcpy.AddError("Missing input data " + str(videolayers[lyr.name]) + ".")
                            processstatus=njtconfig.processStatus.MissingInput
                            return(njtconfig.C_NOTOK,processstatus)
         
                 
            #Apply querydef
            for lyr in arcpy.mapping.ListLayers(mxd):
                if lyr.isFeatureLayer and lyr.name in videolayers:
                    #arcpy.AddMessage("str(lyr.name)) #+ " " + str(len(arcpy.ListFields(lyr,njtconfig.FN_FORECASTTIME))) + " " + str(len(arcpy.ListFiles(njtconfig.FN_MODELNAME)))
                    if len(arcpy.ListFields(lyr.dataSource,njtconfig.FN_FORECASTTIME))==1 and len(arcpy.ListFields(lyr.dataSource,njtconfig.FN_MODELNAME))==1:
                        lyr.definitionQuery=whereclause
                        arcpy.AddMessage(lyr.name + ": count " + str((arcpy.management.GetCount(lyr)[0])))
                        if lyr.time.isTimeEnabled:
                            timefield = lyr.time.startTimeField                        
                            #arcpy.AddMessage(timefield)
                            if len(arcpy.ListFields(lyr.dataSource,timefield))==0:
                                arcpy.AddError("Missing input time field " +  timefield + " in " + lyr.dataSource + ".")
                                processstatus=njtconfig.processStatus.MissingInput
                                #return(njtconfig.C_NOTOK,processstatus)
                            else:
                                if lyr.name=='Assets':
                                    #arcpy.AddMessage("get time")
                                    #Get start and end time
                                    with arcpy.da.SearchCursor(lyr,timefield,sql_clause=(None, 'ORDER BY ' + timefield)) as cursor:
                                        for row in cursor:
                                            starttime=row[0]
                                            #arcpy.AddMessage(str(starttime))
                                            break
                                    with arcpy.da.SearchCursor(lyr,timefield,sql_clause=(None, 'ORDER BY ' + timefield + ' DESC')) as cursor:
                                        for row in cursor:
                                            endtime=row[0]
                                            #arcpy.AddMessage(str(endtime))
                                            break
                                #else:
                                #   arcpy.AddMessage(lyr.name)

         
            if starttime is None or endtime is None:
                arcpy.AddError("There are no time enabled features matching the input forecast and model name.")
                processstatus=njtconfig.processStatus.MissingInput
                return(njtconfig.C_NOTOK,processstatus)

            #Look for Forecasttimeod
            #Look for input layers
            #arcpy.AddMessage("Retrieving input layers and tables from input workspace...")
            arcpy.env.workspace = in_workspace
            #Look for feature dataset
            datasets = arcpy.ListDatasets()
            if datasets and len(datasets)>1:
                datasets = arcpy.ListDatasets('*' + njtconfig.C_FEATUREDATASET)
         
            featuredataset=""
            if datasets:
                for dataset in datasets:
                    #arcpy.AddMessage("dataset " + str(dataset))
                    featuredataset=dataset
         
            inputlayer = njtconfig.LN_FORECASTTIMEOD
            bhasmissinginputs=False

            if arcpy.ListFeatureClasses('*.' + inputlayer,'',featuredataset):
                in_forecasttimeod = arcpy.Describe(arcpy.ListFeatureClasses('*.' + inputlayer,'',featuredataset)[0]).catalogPath
            elif arcpy.ListFeatureClasses(inputlayer,'',featuredataset):
                in_forecasttimeod = inputlayer,arcpy.Describe(arcpy.ListFeatureClasses(inputlayer,'',featuredataset)[0]).catalogPath
            else:
                arcpy.AddError("Required feature class " + inputlayer + " does not exist in input geodatabase " + in_workspace + ".")
                bhasmissinginputs=True

            if bhasmissinginputs:
                    processstatus=njtconfig.processStatus.MissingInput
                    return(njtconfig.C_NOTOK,processstatus)
         
            #Retrieve text for forecast layout
            with arcpy.da.SearchCursor(in_forecasttimeod,[njtconfig.FN_MAXWATERLEVEL,njtconfig.FN_FORECASTHOURMAX,njtconfig.FN_MAXMAP,njtconfig.FN_MAXPCTAFFECTEDI,njtconfig.FN_STARTFORTIME,njtconfig.FN_ENDFORTIME],whereclause) as cursor:
                for row in cursor:
                    maxforecasthour = row[1]
                    maxwaterlevel = row[0]
                    pdffilename = row[2]
                    maxpctaffectedi=row[3]
                    starthour = row[4]
                    endhour=row[5]

         
            #Update map element
            elements = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "ModelName")
            if len(elements)>0:
                elm=elements[0]
                elm.text=in_modelname
                #arcpy.AddMessage(elm.text)
         
            tmpfilename="HOBO_NOAA-150_102912_1200_13.pdf"
            tmpforecasttime="2012/10/29 12:00 p.m."
            tmpmodelname="NOAA-150"
            tmphourstomaxwaterlevel = "13"
            tmpmaxwaterlevel = "8 Feet (NAVD88)"
            tmppercentaffected = "65%"
            elements = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "MainText")
            if len(elements)>0:
                mainelm=elements[0]
                maintext = mainelm.text
                maintext = maintext.replace(tmpfilename,pdffilename)
                maintext = maintext.replace(tmpforecasttime,in_forecasttime)
                maintext = maintext.replace(tmpmodelname,in_modelname)
                maintext = maintext.replace(tmphourstomaxwaterlevel,str(int(maxforecasthour))) #-int(starthour)))
                if maxwaterlevel<=1:
                    maintext = maintext.replace(tmpmaxwaterlevel,str(maxwaterlevel) + " Foot (NAVD88)")
                else:
                    maintext = maintext.replace(tmpmaxwaterlevel,str(maxwaterlevel) + " Feet (NAVD88)")
                maintext = maintext.replace(tmppercentaffected,str(maxpctaffectedi) + "%")

                mainelm.text = maintext
                arcpy.AddMessage(mainelm.text)
         

            #Loop through selected features for the forecast
            df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
            arcpy.AddMessage("Time interval " + df.time.timeStepInterval )
            arcpy.AddMessage("Start time " + str(starttime))
            arcpy.AddMessage("End time " + str(endtime))
            df.time.resetTimeExtent()
            df.time.timeWindowUnits="HOURS"
            df.time.startTime = starttime
            df.time.endTime = endtime
            df.time.currentTime = starttime
         
            #arcpy.AddMessage("df.time.startTime " + str(df.time.startTime))
            #arcpy.AddMessage("df.time.endTime " + str(df.time.endTime))
            #arcpy.AddMessage("df.time.currentime " + str(df.time.currentTime))

            arcpy.env.workspace = in_outputfolder
            i=starthour
            basefilename=in_facilitynameprefix + "_" + in_modelname + "_" + str(parser.parse(in_forecasttime).strftime("%m%d%y_%H%M"))
            if bcreatevideo:
                arcpy.AddMessage("Exporting images...")
            while df.time.currentTime <= endtime:
                arcpy.AddMessage("Exporting image " + str(i) + " " + str(parser.parse(str(df.time.currentTime)).strftime("%m%d%y %H%M")) + " " + in_modelname + "_image" + str(i) + ".jpg")
                fileName = os.path.join(in_outputfolder,in_modelname + "_image" + str(i) + ".jpg" )
                #arcpy.AddMessage(fileName)
                arcpy.mapping.ExportToJPEG(mxd, fileName, "PAGE_LAYOUT")
                #Create pdf for maximum forecast hour
                if i == maxforecasthour:
                    arcpy.AddMessage("Generating pdf file " + pdffilename + " at maximum forecast hour " + str(maxforecasthour) + "...")
                    arcpy.mapping.ExportToPDF(mxd, os.path.join(in_outputfolder,pdffilename), "PAGE_LAYOUT")
                df.time.currentTime = (df.time.currentTime + df.time.timeStepInterval)
                i=i+1

            arcpy.AddMessage(str(i) + " images exported using prefix " + in_modelname + "_image.")

            #Convert to video
            if bcreatevideo:
                videoduration = i * float(dframeduration) #2
                arcpy.AddMessage("Generating video (duration: " + str(videoduration) + "s) ...")
                avifilename = basefilename + ".avi"
                arcpy.RasterToVideo_conversion (in_outputfolder, avifilename,'JPG', 'Microsoft Video 1', 'TIME', videoduration, '75')

                arcpy.AddMessage(avifilename + " succesfully created: dt= " + str(apwrutils.Utils.GetDSMsg(dds,'%.1fs.')) + " dtTotal=" + str(apwrutils.Utils.GetDSMsg(ds,'%ds.')))

        except arcpy.ExecuteError:
            arcpy.AddWarning(str(arcpy.GetMessages(2)))
     
        except:
            arcpy.AddWarning(trace())
            sOK = apwrutils.C_NOTOK
            processstatus=njtconfig.processStatus.Error
         
        finally:

             #Cleanup
            #for jpg in arcpy.ListFiles("*.jpg"):
            #    arcpy.Delete_management(jpg)
            arcpy.AddMessage("Cleaning up...")
            if mxd:
                del mxd
               #Reset environments
            arcpy.ResetEnvironments()
            print ("Process status: " + str(processstatus))
        return (sOK,processstatus)

if(__name__=='__main__'):

    try:
        inMapTemplate = arcpy.GetParameterAsText(0)
        inWorkspace = arcpy.GetParameterAsText(1) #Input SQL Server Workspace
        inFacilityNamePrefix = arcpy.GetParameterAsText(2)
        inModelName = arcpy.GetParameterAsText(3)
        inForecastTime = arcpy.GetParameterAsText(4)
        inOutputFolder = arcpy.GetParameterAsText(5)
        inCreateVideo = arcpy.GetParameterAsText(6)
        inFrameDuration = arcpy.GetParameterAsText(7)

        oProcessor = CreateForecastVideoandPDF()
        params = (inMapTemplate,inWorkspace, inFacilityNamePrefix ,inModelName,inForecastTime,inOutputFolder,inCreateVideo,inFrameDuration)
           
        tResults=None
        tResults = oProcessor.execute(params, None)

        if(tResults!=None):
            processstatus = tResults[1]
            #Set output parameter
            arcpy.SetParameterAsText(8,processstatus)

        del oProcessor

    except arcpy.ExecuteError:
        print (str(arcpy.GetMessages(2)))
        arcpy.AddError(str(arcpy.GetMessages(2)))
    except:
        print (trace())
        arcpy.AddError(str(trace()))
        arcpy.AddError(str(arcpy.GetMessages(2)))
    finally:
        dt = datetime.datetime.now()
        print  ('Finished at ' + dt.strftime("%Y-%m-%d %H:%M:%S"))

Python - Facility Processing

This Facility Processing python script generate Water depth & Water Surface Elevation layers from a processed DEM up to 20 feet @ 0.5 ft interval.


# Preparing Analysis DEM
# Description: Converts Water polygon features to a raster dataset.
# Requirements: Spatial Analyst Extension

# Import system modules
import arcpy, math
from arcpy import env
from arcpy.sa import *
import datetime
import numpy as np


# Set environment settings
#env.workspace = arcpy.GetParameterAsText(0)
env.workspace = r'W:\Projects\NJ_Transit\FloodAnalysis\CSSEWS\2016_Facilities\Hoboken\SHP\WithSimplifyingPolygon\3Mby3M\0pt5Interval\Hobo_3M_0pt5ft.gdb'
Value = "20"
env.snapRaster = "t2r_3m"
DEM = "t2r_3m"
arcpy.env.overwriteOutput = True
ws = env.workspace
#----------------------------------------------------------------------------------------------------------
date1 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Started Processing removing water from the DEM" + " " + date1)
#----------------------------------------------------------------------------------------------------------

# Set local variables
inFeatures = "Water"
valField = "OBJECTID"
outRaster1 = "Watermask"
assignmentType = "CELL_CENTER"
priorityField = "None"
cellSize = DEM
#cellSize =  3.2808333
cellSize =  9.84252
# Execute PolygonToRaster
arcpy.PolygonToRaster_conversion(inFeatures, valField, outRaster1, assignmentType, priorityField, cellSize)

# Description: Find which cell values of the input raster are NoData

# Set local variables
inRaster = outRaster1

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Execute IsNull
outIsNull1 = IsNull(inRaster)
#Wateryn = IsNull(inRaster)

# Save the output
#outIsNull.save("W:/Projects/FacilityProcessingtest/ShpPython/Wateryn")

# Description: Performs a conditional if/else evaluation on each cell of an input raster.

# Local variables:
wateryn = outIsNull1
t2r_3m = DEM
demhobftnw = "demhobftnw"
Wateryn = "Wateryn"
T2R_3M = "T2R_3M"

# Process: Con
arcpy.gp.Con_sa(wateryn, t2r_3m, demhobftnw, "", "Value = 1")

#----------------------------------------------------------------------------------------------------------
date2 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing removing water from the DEM" + " " + date2)
arcpy.AddMessage("Started Processing Building rasters into the DEM" + " " + date2)
#----------------------------------------------------------------------------------------------------------
# From this Point Inserting Building Elevation.
# Description: Converts Building polygon features to a raster dataset.

# Set local variables
inFeatures = "ElevatedBuildings"
valField = "Elev"
outRaster2 = "buildingelev"
assignmentType = "CELL_CENTER"
priorityField = "None"
cellSize = DEM

# Execute PolygonToRaster
arcpy.PolygonToRaster_conversion(inFeatures, valField, outRaster2, assignmentType, priorityField, cellSize)

##

# Description: Find which cell values of the input raster are NoData

# Set local variables
inRaster = outRaster2

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Execute IsNull
outIsNull2 = IsNull(inRaster)
#Wateryn = IsNull(inRaster)

# Save the output
#outIsNull.save("W:/Projects/FacilityProcessingtest/ShpPython/Wateryn")

##

# Description: Performs a conditional if/else evaluation on each cell of an input raster.

# Local variables:
buildingyn = outIsNull2
buildingelev = "buildingelev"
demhobftnw = "demhobftnw"
demhobftadj = "demhobftadj"

# Process: Con
arcpy.gp.Con_sa(buildingyn, buildingelev, demhobftadj, demhobftnw, "Value = 0")

#----------------------------------------------------------------------------------------------------------

#This will be used as the outline polygon for later operations. This will give an extent of demhobftadj.

# Description: Performs a conditional if/else evaluation on each cell of an input raster.

# Local variables:
demhobftadj = "demhobftadj"
Input_true_raster_or_constant_value = "0"
demadjmask = "demadjmask"

# Process: Con
arcpy.gp.Con_sa(demhobftadj, Input_true_raster_or_constant_value, demadjmask, "", "")

##

#Description: Converts a raster dataset to polygon features

# Local variables:
demadjmask = "demadjmask"
fe0_shp = "fe0"

# Process: Raster to Polygon
arcpy.RasterToPolygon_conversion(demadjmask, fe0_shp, "NO_SIMPLIFY", "VALUE")

# Description: Delete unrequired fields from a feature class

# Local variables:
fe0 = "fe0"
fe0_2 = fe0

# Process: Delete Field
arcpy.DeleteField_management(fe0, "ID")

# Process: Delete Field
arcpy.DeleteField_management(fe0, "gridcode")

# Process: Add Field (2)
arcpy.AddField_management(fe0, "gridcode", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

# Process: Calculate Field
arcpy.CalculateField_management(fe0, "gridcode", 0, "PYTHON_9.3", "")

#----------------------------------------------------------------------------------------------------------
date3 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing Building rasters into the DEM" + " " + date3)
arcpy.AddMessage("Started Processing DEMToDepthofFlooding Script" + " " + date3)
#----------------------------------------------------------------------------------------------------------
### Creating flood depth contour bands for WSE 1-20
### Creating elevation contour bands and flood extent polygons
### This is called DEMtoDepthofFlooding Model
### Model Builder
### You can call the Model builder tool from a Python Snipet.
### Import custom toolbox
##arcpy.ImportToolbox("W:/Projects/FacilityProcessingtest/ShpArcGIS/DEMTODepthOfFlooding.tbx")
##
##try:
##    # Run tool in the custom toolbox.  The tool is identified by
##    #  the tool name and the toolbox alias.
##    arcpy.DEMToDepthofFlooding()
##except arcpy.ExecuteError:
##    print(arcpy.GetMessages(2))

# The above mentioned toolbox is converted into Python.

demhobftadj = "demhobftadj"
if demhobftadj == '#' or not demhobftadj:
    demhobftadj = "demhobftadj" # provide a default value if unspecified

# Local variables:
Output_raster = "Minus"
Flood_Depth = "dr"
Output_Contours = "cd"
Output_raster2 = "Con_Minus"
Polygons = "RTP"
Output_Flood_Extent = "fe"
#Step = float(0.5)

#for i in range(0.5,int(Value)+1, 0.5):
#for i in range(1,int(Value)+1):

for i in np.arange(0.5,int(Value)+0.5,0.5):
        k = int(i * 100)
        j = str(k).zfill(4)
        Output_raster_n = "{}{}".format(Output_raster, j)
        Flood_Depth_n = "{}{}".format(Flood_Depth, j)
        Output_Contours_n = "{}{}".format(Output_Contours, j)
        Output_raster2_n = "{}{}".format(Output_raster2, j)
        Polygons_n = "{}{}".format(Polygons, j)
        Output_Flood_Extent_n = "{}{}".format(Output_Flood_Extent, j)
        print i
        print j

        # Process: Convert to double
        OutputValue = float(i)

        # Process: Minus
        arcpy.gp.Minus_sa(OutputValue, demhobftadj, Output_raster_n)

        # Process: Con
        arcpy.gp.Con_sa(Output_raster_n, Output_raster_n, Flood_Depth_n, "", "Value > 0")

        # Process: Contour List
        arcpy.gp.ContourList_sa(Flood_Depth_n, Output_Contours_n, "0.5;1;1.5;2;2.5;3;3.5;4;4.5;5;5.5;6;6.5;7;7.5;8;8.5;9;9.5;10;10.5;11;11.5;12;12.5;13;13.5;14;14.5;15;15.5;16;16.5;17;17.5;18;18.5;19;19.5;20")

        test1 = arcpy.sa.RoundUp(arcpy.sa.FloatDivide(Output_raster_n,0.5))  # Divide the raster value by 2
        test2 = arcpy.sa.FloatDivide(test1 , 2) # Multiply the raster value by 2
        test3 = arcpy.sa.Times(test2, 10)
        test2.save(str(Output_raster2_n))

        arcpy.CopyRaster_management(test3, str(Output_raster2_n) + "_Times_32bit", "", "", "", "", "", "32_BIT_SIGNED")
        del test1, test2, test3

        # Process: Raster to Polygon (2)
        arcpy.RasterToPolygon_conversion(str(Output_raster2_n) + "_Times_32bit", Polygons_n, "NO_SIMPLIFY", "Value")

        arcpy.MakeFeatureLayer_management(Polygons_n, Polygons_n)

        # Process: Select
        arcpy.SelectLayerByAttribute_management(Polygons_n, "NEW_SELECTION", "gridcode > 0")
        #arcpy.Select_analysis(Polygons_n, "Select_" + str(Polygons_n), "gridcode > 0")

        # Process: Delete Field
        arcpy.DeleteField_management(Polygons_n, "gridcode")

        # Process: Add Field (2)
        arcpy.AddField_management(Polygons_n, "gridcode", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

        # Process: Calculate Field
        arcpy.CalculateField_management(Polygons_n, "gridcode", i, "PYTHON_9.3", "")

        # Process: Dissolve (2)
        arcpy.Dissolve_management(Polygons_n, Output_Flood_Extent_n, "gridcode", "", "MULTI_PART", "DISSOLVE_LINES")




#----------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------
# Description: Copy Feature to a new feature
# Next step creates a new feature class that will be used to append all individual flood extents into a single layer.
# Local variables:
fe0 = "fe0"
FloodAllW = "FloodAllW"

# Process: Copy Features
arcpy.CopyFeatures_management(fe0, FloodAllW, "", "0", "0", "0")

#Append all individual flood extents into the new feature class.  Make sure you use the right order when appending as that will simplify operations later.
# Local variables:
fe2000 = "fe2000"
FloodAllW__2_ = fe2000
fe1950 = "fe1950"
fe1900 = "fe1900"
fe1850 = "fe1850"
fe1800 = "fe1800"
fe1750 = "fe1750"
fe1700 = "fe1700"
fe1650 = "fe1650"
fe1600 = "fe1600"
fe1550 = "fe1550"
fe1500 = "fe1500"
fe1450 = "fe1450"
fe1400 = "fe1400"
fe1350 = "fe1350"
fe1300 = "fe1300"
fe1250 = "fe1250"
fe1200 = "fe1200"
fe1150 = "fe1150"
fe1100 = "fe1100"
fe1050 = "fe1050"
fe1000 = "fe1000"
fe0950 = "fe0950"
fe0900 = "fe0900"
fe0850 = "fe0850"
fe0800 = "fe0800"
fe0750 = "fe0750"
fe0700 = "fe0700"
fe0650 = "fe0650"
fe0600 = "fe0600"
fe0550 = "fe0550"
fe0500 = "fe0500"
fe0450 = "fe0450"
fe0400 = "fe0400"
fe0350 = "fe0350"
fe0300 = "fe0300"
fe0250 = "fe0250"
fe0200 = "fe0200"
fe0150 = "fe0150"
fe0100 = "fe0100"
fe0050 = "fe0050"
FloodAllW = "FloodAllW"

# Process: Append
arcpy.Append_management("fe2000;fe1950;fe1900;fe1850;fe1800;fe1750;fe1700;fe1650;fe1600;fe1550;fe1500;fe1450;fe1400;fe1350;fe1300;fe1250;fe1200;fe1150;fe1100;fe1050;fe1000;fe0950;fe0900;fe0850;fe0800;fe0750;fe0700;fe0650;fe0600;fe0550;fe0500;fe0450;fe0400;fe0350;fe0300;fe0250;fe0200;fe0150;fe0100;fe0050", FloodAllW, "TEST", "", "")

# intersect
# Local variables:
FloodAllW = "FloodAllW"
FloodAllWInt = "FloodAllWInt"

# Process: Intersect
arcpy.Intersect_analysis("FloodAllW #", FloodAllWInt, "ALL", "", "INPUT")

#----------------------------------------------------------------------------------------------------------
date4 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing DEMToDepthofFlooding Script" + " " + date4)
arcpy.AddMessage("Started Processing Selection of the First Occurence" + " " + date4)
#----------------------------------------------------------------------------------------------------------
# automate the selection of the first occurrence
# Sort resulting FC by ?gridcode? in ascending order.  Select only the first record with the same ?gridcode? (but none of the ?0? gridcode values) and export them into ?ElevationContourRing? feature class (new FC).  Make sure that the remaining polygons are the right ?contour bands?.

FloodAllWInt = "FloodAllWInt"
FloodAllWInt_WithoutZero = "FloodAllWInt_WithoutZero"
FloodAllWInt_WithoutZero__1_ = "FloodAllWInt_WithoutZero1"
FloodAllWInt_WithoutZero__2_ = FloodAllWInt_WithoutZero__1_
FloodAllWInt_WithoutZero__3_ = FloodAllWInt_WithoutZero__2_
FloodAllWInt_Sort = "FloodAllWInt_Sort"
FloodAllWInt2_Flag = FloodAllWInt_Sort
FloodAllWInt_Sort__2_ = FloodAllWInt2_Flag
FloodAllWInt_Sort_Layer = "FloodAllWInt_Sort_Layer"
ElevationContourRing = "ElevationContourRing"

# Process: Select
arcpy.Select_analysis(FloodAllWInt, FloodAllWInt_WithoutZero, "\"gridcode\" <> 0")

# Process: Copy Features
arcpy.CopyFeatures_management(FloodAllWInt_WithoutZero, FloodAllWInt_WithoutZero__1_, "", "0", "0", "0")

# Process: Add Field (2)
arcpy.AddField_management(FloodAllWInt_WithoutZero__1_, "AlterSort", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

# Process: Calculate Field (2)
arcpy.CalculateField_management(FloodAllWInt_WithoutZero__2_, "AlterSort", "!OBJECTID!", "PYTHON_9.3", "")

# Process: Sort
arcpy.Sort_management(FloodAllWInt_WithoutZero__3_, FloodAllWInt_Sort, "gridcode ASCENDING;AlterSort ASCENDING", "UR")

# Process: Add Field
arcpy.AddField_management(FloodAllWInt_Sort, "Flag", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

# Process: Calculate Field
arcpy.CalculateField_management(FloodAllWInt2_Flag, "Flag", "isDuplicate( !Gridcode!)", "PYTHON_9.3", "uniqueList = [] \\n\\ndef isDuplicate(inValue): \\n  if inValue in uniqueList: return 1 \\n  else: uniqueList.append(inValue) \\n  return 0\\n")

# Process: Make Feature Layer
arcpy.MakeFeatureLayer_management(FloodAllWInt_Sort__2_, FloodAllWInt_Sort_Layer, "Flag = 0", "", "OBJECTID OBJECTID VISIBLE NONE;Shape Shape VISIBLE NONE;FID_FloodAllW FID_FloodAllW VISIBLE NONE;gridcode gridcode VISIBLE NONE;Shape_Length Shape_Length VISIBLE NONE;Shape_Area Shape_Area VISIBLE NONE;Shape_length Shape_length VISIBLE NONE;Shape_area Shape_area VISIBLE NONE;AlterSort AlterSort VISIBLE NONE;Flag Flag VISIBLE NONE")

# Process: Copy Features (2)
arcpy.CopyFeatures_management(FloodAllWInt_Sort_Layer, ElevationContourRing, "", "0", "0", "0")

#----------------------------------------------------------------------------------------------------------
date5 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing Selection of the First Occurence" + " " + date5)
arcpy.AddMessage("Started Processing Simplifying polygon" + " " + date5)
#----------------------------------------------------------------------------------------------------------

#Simplify geometry before proceeding.

# Local variables:

ElevationContourRing = "ElevationContourRing"
ElevationContourRingSimply = "ElevationContourRingSimply"
ElevationContourRingSimply_Pnt = "ElevationContourRingSimply_Pnt"

# Process: Simplify Polygon
arcpy.SimplifyPolygon_cartography(ElevationContourRing, ElevationContourRingSimply, "POINT_REMOVE", "15", "1000", "RESOLVE_ERRORS", "KEEP_COLLAPSED_POINTS")

#OR

##ElevationContourRing = "ElevationContourRing"
##ElevationContourRingSimply = "ElevationContourRingSimply"
###Process: Copy Features
##arcpy.CopyFeatures_management(ElevationContourRing, ElevationContourRingSimply, "", "0", "0", "0")

#----------------------------------------------------------------------------------------------------------
date6 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing Simplifying polygon" + " " + date6)
arcpy.AddMessage("Started Processing ElevationContourToFloodDepth Script" + " " + date6)
#----------------------------------------------------------------------------------------------------------
### Creating flood contours from elevation contours and selected flood level
### Creating elevation contour bands and flood extent polygons
### This is called ElevationContourToFloodDepth Model
### Model builder
### You can call the Model builder tool from a Python Snipet.
### Import custom toolbox
##arcpy.ImportToolbox("W:/Projects/FacilityProcessingtest/ShpArcGIS/DEMTODepthOfFlooding.tbx")
##
##try:
##    # Run tool in the custom toolbox.  The tool is identified by
##    #  the tool name and the toolbox alias.
##    arcpy.ElevationContourToFloodDepth()
##except arcpy.ExecuteError:
##    print(arcpy.GetMessages(2))

# The above mentioned model builder is converted to Python

# Local variables:
ElevationContourRingSimply = "ElevationContourRingSimply"
if ElevationContourRingSimply == '#' or not ElevationContourRingSimply:
    ElevationContourRingSimply = "ElevationContourRingSimply" # provide a default value if unspecified


for i in np.arange(0.5,int(Value)+0.5,0.5):
    print i
    k = int(i * 100)
    print k
    j = str(k).zfill(4)
    print j

    # Process: Select
    arcpy.Select_analysis(ElevationContourRingSimply, "fdcb" + str(j), 'GRIDCODE <= ' + "%f" %i)

    # Process: Add Field
    arcpy.AddField_management("fdcb" + str(j), "WaterLevel", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

    # Process: Calculate Field
    arcpy.CalculateField_management("fdcb" + str(j), "WaterLevel", i, "VB", "")

    # Process: Calculate Field (2)
    arcpy.CalculateField_management("fdcb" + str(j), "GRIDCODE", "%f - [GRIDCODE] + 0.5" %i, "VB", "")

    # Process: Alter Field
    arcpy.AlterField_management("fdcb" + str(j), "GRIDCODE", "FloodDepth", "FloodDepth", "", "4", "NON_NULLABLE", "false")

    # Process: Delete Field
    arcpy.DeleteField_management("fdcb" + str(j), "FID_FloodAllW")


# Local variables:
# Description: Copy Feature to a new feature
# Next step creates a new feature class that will be used to append all individual flood depth contour band into a single layer.
# Copy ?fdcb1? into ?FloodContourBand? and append fdcb2-20 to it.
# Local variables:
fdcb0050 = "fdcb0050"
FloodContourBand = "FloodContourBand"

# Process: Copy
arcpy.Copy_management(fdcb0050, FloodContourBand, "FeatureClass")

#Append all individual flood depth contour bands into the new feature class.  Make sure you use the right order when appending as that will simplify operations later.
# Local variables:
fdcb0100 = "fdcb0100"
Output_Features = fdcb0100
fdcb0150 = "fdcb0150"
fdcb0200 = "fdcb0200"
fdcb0250 = "fdcb0250"
fdcb0300 = "fdcb0300"
fdcb0350 = "fdcb0350"
fdcb0400 = "fdcb0400"
fdcb0450 = "fdcb0450"
fdcb0500 = "fdcb0500"
fdcb0550 = "fdcb0550"
fdcb0600 = "fdcb0600"
fdcb0650 = "fdcb0650"
fdcb0700 = "fdcb0700"
fdcb0750 = "fdcb0750"
fdcb0800 = "fdcb0800"
fdcb0850 = "fdcb0850"
fdcb0900 = "fdcb0900"
fdcb0950 = "fdcb0950"
fdcb1000 = "fdcb1000"
fdcb1050 = "fdcb1050"
fdcb1100 = "fdcb1100"
fdcb1150 = "fdcb1150"
fdcb1200 = "fdcb1200"
fdcb1250 = "fdcb1250"
fdcb1300 = "fdcb1300"
fdcb1350 = "fdcb1350"
fdcb1400 = "fdcb1400"
fdcb1450 = "fdcb1450"
fdcb1500 = "fdcb1500"
fdcb1550 = "fdcb1550"
fdcb1600 = "fdcb1600"
fdcb1650 = "fdcb1650"
fdcb1700 = "fdcb1700"
fdcb1750 = "fdcb1750"
fdcb1800 = "fdcb1800"
fdcb1850 = "fdcb1850"
fdcb1900 = "fdcb1900"
fdcb1950 = "fdcb1950"
fdcb2000 = "fdcb2000"
FloodContourBand = "FloodContourBand"

# Process: Append
arcpy.Append_management("fdcb0100;fdcb0150;fdcb0200;fdcb0250;fdcb0300;fdcb0350;fdcb0400;fdcb0450;fdcb0500;fdcb0550;fdcb0600;fdcb0650;fdcb0700;fdcb0750;fdcb0800;fdcb0850;fdcb0900;fdcb0950;fdcb1000;fdcb1050;fdcb1100;fdcb1150;fdcb1200;fdcb1250;fdcb1300;fdcb1350;fdcb1400;fdcb1450;fdcb1500;fdcb1550;fdcb1600;fdcb1650;fdcb1700;fdcb1750;fdcb1800;fdcb1850;fdcb1900;fdcb1950;fdcb2000", FloodContourBand, "TEST", "", "")


#----------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------
#Calculating %flooded
# CopyFeatures
# Select feature by hand
#Create Demclip raster representing potential area (area that is within facility outline but not water).  Set ?mask? to ?SiteBoundary? polygon.
#----------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------

# Local variables:
demhobftadj = "demhobftadj"
Input_true_raster_or_constant_value = "1"
demclip = "demclip"

# Process: Con
arcpy.gp.Con_sa(demhobftadj, Input_true_raster_or_constant_value, demclip, "", "")


#----------------------------------------------------------------------------------------------------------
date7 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing ElevationContourToFloodDepth Script" + " " + date7)
arcpy.AddMessage("Started Processing CalculatePercentageFlooded Script" + " " + date7)
#----------------------------------------------------------------------------------------------------------

###Run the model builder tool. CalculatePercentageFlooded
### Write Python Script on this one.
### You can call the Model builder tool from a Python Snipet.
### Import custom toolbox
##arcpy.ImportToolbox("W:/Projects/FacilityProcessingtest/ShpArcGIS/DEMTODepthOfFlooding.tbx")
##
##try:
##    # Run tool in the custom toolbox.  The tool is identified by
##    #  the tool name and the toolbox alias.
##    arcpy.CalculatePercentageFlooded()
##except arcpy.ExecuteError:
##    print(arcpy.GetMessages(2))

# The above mentioned model Builder script has been converted into python.

Input_true_raster_or_constant_value = 1

rasters = arcpy.ListRasters("dr*", "")
i = 1

for raster in rasters:
    k = int(i * 50)
    j = str(k).zfill(4)

    print(raster)

    # Process: Con
    arcpy.gp.Con_sa(raster, Input_true_raster_or_constant_value, "Clipd" + str(j), "", "")

    # Process: Add Field
    arcpy.AddField_management("Clipd" + str(j), "FloodDepth", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

    # Process: Calculate Field
    arcpy.CalculateField_management("Clipd" + str(j), "FloodDepth", "!Value!", "PYTHON_9.3", "")

    i = i + 1
    print i


#----------------------------------------------------------------------------------------------------------
date8 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing CalculatePercentageFlooded Script" + " " + date8)
arcpy.AddMessage("Started Processing Percentage Flooded (raster Counts to CSV)" + " " + date8)
#----------------------------------------------------------------------------------------------------------

###Export all the raster count to a CSV file
###write a Model builder script for this task
##
### Creating flood contours from elevation contours and selected flood level
### Creating elevation contour bands and flood extent polygons
### This is called ElevationContourToFloodDepth Model
### Model builder
### You can call the Model builder tool from a Python Snipet.
### Import custom toolbox
##arcpy.ImportToolbox("W:/Projects/FacilityProcessingtest/ShpArcGIS/DEMTODepthOfFlooding.tbx")
##
##try:
##    # Run tool in the custom toolbox.  The tool is identified by
##    #  the tool name and the toolbox alias.
##    arcpy.RasCountsToCSV2()
##except arcpy.ExecuteError:
##    print(arcpy.GetMessages(2))

#Ras2CountCSV Model builder has been converted into Python

# Script arguments
PercentageFlooded = "PercentageFlooded"
if PercentageFlooded == '#' or not PercentageFlooded:
    PercentageFlooded = "PercentageFlooded" # provide a default value if unspecified

HobokenFlood_gdb = ws
if HobokenFlood_gdb == '#' or not ws:
    HobokenFlood_gdb = "ws" # provide a default value if unspecified


# Local variables:
demclip = "demclip"
demclip_View = "demclip_View"
demclip_View__2_ = demclip_View
#TotalCounts = demclip_View

# Process: Truncate Table
arcpy.TruncateTable_management(PercentageFlooded)

# Process: Make Table View (2)
arcpy.MakeTableView_management(demclip, demclip_View, "", "", "OBJECTID OBJECTID VISIBLE NONE;Value Value VISIBLE NONE;Count Count VISIBLE NONE")

with arcpy.da.SearchCursor(demclip_View, 'Count') as cursor:
    for row in cursor:
        TotalCounts = row[0]

rasters = arcpy.ListRasters("Clipd*", "")
i = 1

for raster in rasters:
    k = int(i * 50)
    j = str(k).zfill(4)

    print(raster)

    # Process: Make Table View
    arcpy.MakeTableView_management("Clipd" + str(j), "Clipd" + str(j) + "_View", "", "", "OBJECTID OBJECTID VISIBLE NONE;Value Value VISIBLE NONE;Count Count VISIBLE NONE;FloodDepth FloodDepth VISIBLE NONE")

    # Process: Append
    arcpy.Append_management("Clipd" + str(j) + "_View", PercentageFlooded, "NO_TEST")

    i = i + 1
    print i

# Process: Calculate Field
arcpy.CalculateField_management(PercentageFlooded, "FloodDepth", "!OBJECTID!*0.5", "PYTHON_9.3", "")

# Process: Calculate Field
arcpy.CalculateField_management(PercentageFlooded, "PctAffected", "(!Count! /%d) *100" %TotalCounts, "PYTHON_9.3", "")

#----------------------------------------------------------------------------------------------------------
date9 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing Percentage Flooded (raster Counts to CSV)" + " " + date9)
arcpy.AddMessage("Started Processing FloodOutline Script" + " " + date9)
#----------------------------------------------------------------------------------------------------------

#Flood outline polygon layer
#Select from ?FloodAllW? all flood extent features except for the total analysis extent (=0).  Export selected features into ?FloodOutline?.  Add field ?PctAffected?.  Populate with values in the above table.  Rename ?gridcode? to ?WaterLevel?.
# Local variables:
# Write a model builder script and convert it to the Python Script


# Local variables:
FloodAllW = "FloodAllW"
FloodAllW_FloodOutline = "FloodAllW_FloodOutline"
FloodOutline = "FloodOutline"
FloodOutline__1_ = FloodOutline
PercentageFlooded__2_ = "PercentageFlooded"
FloodOutline__2_ = FloodOutline__1_
FloodOutline__3_ = FloodOutline__2_
FloodOutline__4_ = FloodOutline__3_
FloodOutline__6_ = FloodOutline__4_
PercentAffected = FloodOutline__6_
HobokenFlood_gdb = ws

# Process: Copy Features
arcpy.CopyFeatures_management(FloodAllW, FloodAllW_FloodOutline, "", "0", "0", "0")

# Process: Select
arcpy.Select_analysis(FloodAllW_FloodOutline, FloodOutline, "gridcode <> 0")

FloodOutline = "FloodOutline"
FloodOutline__2_ = FloodOutline
PercentageFlooded = PercentageFlooded

# Process: Join Field
arcpy.JoinField_management(FloodOutline, "gridcode", PercentageFlooded, "FloodDepth", "FloodDepth;PctAffected")

# Process: Alter Field
arcpy.AlterField_management(FloodOutline__1_, "gridcode", "WaterLevel", "WaterLevel", "", "4", "NON_NULLABLE", "false")

# Process: Add Field
arcpy.AddField_management(FloodOutline__2_, "PctAffectedI", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

# Process: Calculate Field
arcpy.CalculateField_management(FloodOutline__3_, "PctAffectedI", "math.ceil( !PctAffected! )", "PYTHON_9.3", "")

# Process: Delete Field
arcpy.DeleteField_management(FloodOutline__4_, "FloodDepth")

# Process: Table to Table
arcpy.TableToTable_conversion(FloodOutline__6_, HobokenFlood_gdb, "PercentAffected", "", "WaterLevel \"WaterLevel\" true true false 4 DOUBLE 0 0 ,First,#,FloodOutline,WaterLevel,-1,-1;Shape_Length \"Shape_Length\" true true true 8 Double 0 0 ,First,#,FloodOutline,Shape_Length,-1,-1,FloodOutline,Shape_length,-1,-1;Shape_Area \"Shape_Area\" true true true 8 Double 0 0 ,First,#,FloodOutline,Shape_Area,-1,-1,FloodOutline,Shape_area,-1,-1;PctAffected \"PctAffected\" true true false 8 Double 0 0 ,First,#,FloodOutline,PctAffected,-1,-1;PctAffectedI \"PctAffectedI\" true true false 0 Long 0 0 ,First,#,FloodOutline,PctAffectedI,-1,-1", "")

#----------------------------------------------------------------------------------------------------------
date10 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing FloodOutline Script" + " " + date10)
arcpy.AddMessage("Started Processing FloodContourBand7" + " " + date10)
#----------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------
# Creating flood depth contour bands for display in OD
# In OD only first 5 ft are of interest for depth of flooding display.  To simplify and speed up display, all depths of flooding greater than 5 feet are grouped into a single layer ?flood depth band?.  Add field ?MergeItem? to ?FloodContourBand? FC and calculate it to be = OID (to get incremental sequence).
#----------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------
# Local variables:
FloodContourBand = "FloodContourBand"
PercentAffected = "PercentAffected"

for m in np.arange(6,int(Value)+0.5,0.5):
    print m
    z = int(m * 100)
    n = str(z).zfill(4)

    # Process: Join Field
    arcpy.JoinField_management(FloodContourBand, "WaterLevel", PercentAffected, "WaterLevel", "PctAffected;PctAffectedI")

    # Process: Sort
    arcpy.Sort_management(FloodContourBand, "FloodContourBand" + "_Sort" + str(n), "WaterLevel ASCENDING;FloodDepth ASCENDING", "UR")

    # Process: Add Field
    arcpy.AddField_management("FloodContourBand" + "_Sort" + str(n), "MergeItem", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

    # Process: Calculate Field
    arcpy.CalculateField_management("FloodContourBand" + "_Sort" + str(n), "MergeItem", "!OBJECTID!", "PYTHON_9.3", "")

    arcpy.MakeFeatureLayer_management("FloodContourBand" + "_Sort" + str(n), "FloodContourBand" + "_Sort" + str(n))


    # Process: Select
    arcpy.SelectLayerByAttribute_management("FloodContourBand" + "_Sort" + str(n), "NEW_SELECTION", 'FloodDepth <= ' + str(m) + ' AND  WaterLevel <= ' + str(m))
#    arcpy.SelectLayerByAttribute_management("FloodContourBand" + "_Sort" + str(n), "NEW_SELECTION", 'FloodDepth <= ' + "%d" %m + ' AND  WaterLevel <= ' + "%d" %m)


    # Process: Calculate Field (2)
    arcpy.CalculateField_management("FloodContourBand" + "_Sort" + str(n), "MergeItem", "myCalc( !FloodDepth!, !MergeItem! )", "PYTHON_9.3", "def myCalc(fld,mg):\\n  mer = mg\\n  global merge\\n  if (fld <=6):\\n    merge = mer\\n    return mer\\n  else:\\n    return merge")

    # Process: Dissolve
    arcpy.Dissolve_management("FloodContourBand" + "_Sort" + str(n), "FloodContourBand" + str(n), "WaterLevel;PctAffected;PctAffectedI;MergeItem", "", "MULTI_PART", "DISSOLVE_LINES")

    # Process: Join Field (2)
    arcpy.JoinField_management("FloodContourBand" + str(n), "MergeItem", "FloodContourBand" + "_Sort" + str(n), "MergeItem", "FloodDepth")

    # Process: Add Field
    arcpy.AddField_management("FloodContourBand" + str(n), "FloodDepths", "TEXT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

    # Process: Calculate Field
    #arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "myCalc( !FloodDepth! )", "PYTHON_9.3", "def myCalc(num):\\n  if (num == 1 ):\\n    return \"0-1\"\\n  elif num == 2:\\n    return \"1-2\"\\n  elif num == 3:\\n    return \"2-3\"\\n  elif num == 4:\\n    return \"3-4\"\\n  elif num == 5:\\n    return \"4-5\"\\n  elif num == 6:\\n    return \"5+\"")
    #arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "myCalc( !FloodDepth! )", "PYTHON_9.3", "def myCalc(num):\\n  if (num == 0.5 ):\\n    return \"0-0.5\"\\n  elif num == 1:\\n    return \"0.5-1\"\\n  elif num == 1.5:\\n    return \"1-1.5\"\\n  elif num == 2:\\n    return \"1.5-2\"\\n  elif num == 2.5:\\n    return \"2-2.5\"\\n  elif num == 3:\\n    return \"2.5+\"")
    arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "myCalc( !FloodDepth! )", "PYTHON_9.3", "def myCalc(num):\\n  if (num == 0.5 ):\\n    return \"0-1\"\\n  elif num == 1:\\n    return \"0-1\"\\n  elif num == 1.5:\\n    return \"1-2\"\\n  elif num == 2:\\n    return \"1-2\"\\n  elif num == 2.5:\\n    return \"2-3\"\\n  elif num == 3:\\n    return \"2-3\"\\n  elif num == 3.5:\\n    return \"3-4\"\\n  elif num == 4:\\n    return \"3-4\"\\n  elif num == 4.5:\\n    return \"4-5\"\\n  elif num == 5:\\n    return \"4-5\"\\n  elif num == 5.5:\\n    return \"5+\"\\n  elif num == 6:\\n    return \"5+\"")

##    # Process: Select Layer By Attribute
##    arcpy.SelectLayerByAttribute_management("FloodContourBand" + str(n), "NEW_SELECTION", "FloodDepth = 1")
##
##    # Process: Calculate Field
##    arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "\"0-1\"", "VB", "")
##
##    # Process: Select Layer By Attribute
##    arcpy.SelectLayerByAttribute_management("FloodContourBand" + str(n), "NEW_SELECTION", "FloodDepth = 2")
##
##    # Process: Calculate Field
##    arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "\"1-2\"", "VB", "")
##
##    # Process: Select Layer By Attribute
##    arcpy.SelectLayerByAttribute_management("FloodContourBand" + str(n), "NEW_SELECTION", "FloodDepth = 3")
##
##    # Process: Calculate Field
##    arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "\"2-3\"", "VB", "")
##
##    # Process: Select Layer By Attribute
##    arcpy.SelectLayerByAttribute_management("FloodContourBand" + str(n), "NEW_SELECTION", "FloodDepth = 4")
##
##    # Process: Calculate Field
##    arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "\"3-4\"", "VB", "")
##
##    # Process: Select Layer By Attribute
##    arcpy.SelectLayerByAttribute_management("FloodContourBand" + str(n), "NEW_SELECTION", "FloodDepth = 5")
##
##    # Process: Calculate Field
##    arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "\"4-5\"", "VB", "")
##
##    # Process: Select Layer By Attribute
##    arcpy.SelectLayerByAttribute_management("FloodContourBand" + str(n), "NEW_SELECTION", "FloodDepth = 6")
##
##    # Process: Calculate Field
##    arcpy.CalculateField_management("FloodContourBand" + str(n), "FloodDepths", "\"5+\"", "VB", "")

#----------------------------------------------------------------------------------------------------------
date11 = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
arcpy.AddMessage("Ended Processing FloodContourBand7" + " " + date11)
#----------------------------------------------------------------------------------------------------------