Beispiel #1
0
def ClearSelectedFeatures(fc):
    """
    Removes a selection from the provided feature class
    :param fc: a feature class
    :return: None
    """
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        m = p.activeMap
        for lyr in m.listLayers(fc):
            if lyr.getSelectionSet():
                arcpy.AddMessage("clearing {} selected features for "
                                 "layer: '{}'".format(
                                     len(lyr.getSelectionSet()), lyr.name))
                arcpy.management.SelectLayerByAttribute(lyr, 'CLEAR_SELECTION')
        del m
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        for lyr in arcpy.mapping.ListLayers(mxd, fc):
            if lyr.getSelectionSet():
                arcpy.AddMessage("clearing {} selected features for "
                                 "layer: '{}'".format(
                                     len(lyr.getSelectionSet()), lyr.name))
                arcpy.management.SelectLayerByAttribute(lyr, 'CLEAR_SELECTION')
        del mxd
Beispiel #2
0
def AddAnthroToMap(workspace, anthro_feature):
    """
    Adds anthropogenic features to the map document by replacing the existing
    state-wide layer with the clipped (project-specific) feature (replacing
    existing maintains the subtype templates for editing). Note that clipped
    anthro features must have 'Anthro_' and '_clip' (not cap sensitive) as
    prefix and suffix.
    :param workspace: the gdb with the clipped (project-specific) anthro features
    :param anthro_feature: the anthro feature to be added to the map document
    :return: None
    """

    if arcpy.ListInstallations(
    )[0] == 'arcgispro':  #switch for arcpro and gis desktop
        p = arcpy.mp.ArcGISProject("CURRENT")
        m = p.activeMap
        try:
            for existingLayer in m.listLayers():
                if existingLayer.name == anthro_feature[7:-5]:
                    #workspace_type = "FILEGDB_WORKSPACE"
                    #dataset_name = anthro_feature
                    new_conn_prop = existingLayer.connectionProperties
                    new_conn_prop['connection_info']['database'] = workspace
                    new_conn_prop['dataset'] = anthro_feature
                    #existingLayer.replaceDataSource(workspace, workspace_type,
                    # dataset_name)
                    existingLayer.updateConnectionProperties(
                        existingLayer.connectionProperties, new_conn_prop)
            #arcpy.RefreshActiveView()
        except arcpy.ExecuteError:
            for existingLayer in m.listLayers():
                if existingLayer.name == anthro_feature:
                    arcpy.mp.RemoveLayer(existingLayer)
            refLayer = m.ListLayers("Analysis_Area")[0]
            m.insertLayer(m, refLayer, anthro_feature, "AFTER")
        del p, m
    else:
        # Add layer to map
        arcpy.AddMessage("Adding layer to map document")
        mxd = arcpy.mapping.MapDocument("CURRENT")
        df = mxd.activeDataFrame
        layer = arcpy.mapping.Layer(anthro_feature)
        try:
            for existingLayer in arcpy.mapping.ListLayers(mxd, "", df):
                if existingLayer.name == layer.name[7:-5]:
                    workspace_type = "FILEGDB_WORKSPACE"
                    dataset_name = anthro_feature
                    existingLayer.replaceDataSource(workspace, workspace_type,
                                                    dataset_name)
            arcpy.RefreshActiveView()
        except arcpy.ExecuteError:
            for existingLayer in arcpy.mapping.ListLayers(mxd, "", df):
                if existingLayer.name == layer.name:
                    arcpy.mapping.RemoveLayer(df, existingLayer)
            refLayer = arcpy.mapping.ListLayers(mxd, "Analysis_Area", df)[0]
            arcpy.mapping.InsertLayer(df, refLayer, layer, "AFTER")
        del mxd, df, layer
def AdoptParameter(provided_input, parameter_name, preserve_existing=True):
    """
    Copies the provided input into the geodatabase as the parameter_name
    parameter. If a feature class already exists with the parameter_name,
    a unique copy will be saved (with preserve_existing=True).
    Workspace must be defined as project's unique geodatabase before
    calling this function.
    :param provided_input: a feature class or shapefile
    :param parameter_name: the name to save the provided_input as string
    :param preserve_existing: True to avoid overwriting
    :return: the name of the adopted parameter as a string
    """
    # Save a copy of the existing feature class if it already exists
    if preserve_existing:
        if arcpy.Exists(parameter_name):
            new_parameter_name = arcpy.CreateUniqueName(parameter_name)
            arcpy.CopyFeatures_management(parameter_name, new_parameter_name)

    # Copy providedInput to temporary memory to allow overwriting
    arcpy.CopyFeatures_management(provided_input, "in_memory/tmp_provided")

    # Delete existing layers in the TOC of the paramaterName
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        m = p.activeMap
        for _ in m.listLayers():
            arcpy.Delete_management(parameter_name)
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        for _ in arcpy.mapping.ListLayers(mxd, parameter_name):
            arcpy.Delete_management(parameter_name)

    # Delete feature classes in the geodatabase
    for _ in arcpy.ListFeatureClasses(parameter_name):
        arcpy.Delete_management(parameter_name)

    # Execute renaming
    adopted_parameter = arcpy.CopyFeatures_management(
        "in_memory/tmp_provided", parameter_name
        )

    # Clean up
    arcpy.Delete_management("in_memory")

    return adopted_parameter
Beispiel #4
0
def getWorkflowManagerToolboxLocation():
    # Import the workflow manager toolbox
    wmxToolbox = None
    
    installations = arcpy.ListInstallations()
    for installation in installations:
        installInfo = arcpy.GetInstallInfo(installation)
        if installInfo != None:
            tbx = installInfo["InstallDir"] + os.sep + "ArcToolbox" + os.sep + "Toolboxes" + os.sep + "Workflow Manager Administration Tools.tbx"
            tbx = os.path.normpath(tbx)
            if os.path.exists(tbx):
                wmxToolbox = tbx
                break

    if wmxToolbox == None:
        raise InstallationError("Workflow Manager Administration Tools toolbox not found")

    return wmxToolbox
Beispiel #5
0
def AddToMap(feature_or_raster, layer_file=None, zoom_to=False):
    """
    Adds provided to the map document after removing any layers of the same
    name.
    :param feature_or_raster: feature class or raster dataset
    :param layer_file: layer file
    :param zoom_to: True to zoom to the added object
    :return: None
    """
    # Add layer to map
    arcpy.AddMessage("Adding layer to map document")
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        m = p.activeMap
        layer_path = arcpy.Describe(
            feature_or_raster
        ).catalogPath  #arcpy.Describe calls metadata, so this gives full path
        for existingLayer in m.listLayers(m):
            if existingLayer.name == feature_or_raster:
                m.remove_layer(existingLayer)
        m.addDataFromPath(layer_path)
        # TODO: revisit layer file application in Pro.
        if layer_file:
            arcpy.ApplySymbologyFromLayer_management(feature_or_raster,
                                                     layer_file)
        #if zoom_to:
        #   m.extent = layer.getSelectedExtent()
        del p, m

    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        df = mxd.activeDataFrame
        layer_path = arcpy.Describe(feature_or_raster).catalogPath
        layer = arcpy.mapping.Layer(layer_path)
        for existingLayer in arcpy.mapping.ListLayers(mxd, "", df):
            if existingLayer.name == layer.name:
                arcpy.mapping.RemoveLayer(df, existingLayer)
        arcpy.mapping.AddLayer(df, layer)
        if layer_file:
            arcpy.ApplySymbologyFromLayer_management(layer.name, layer_file)
        if zoom_to:
            df.extent = layer.getSelectedExtent()
        del mxd, df, layer
Beispiel #6
0
def RenameFeatureClass(in_data, out_data):
    """
    Deletes existing layers and feature classes of the out_data name and
    renames provided feature class. Provided feature class may not have
    the same name as the out_data. The in_data will be deleted.
    :param in_data: a feature class
    :param out_data: the name to save the output as a string
    :return: the name of the output as a string
    """
    # Delete any existing instances of the file to be overwritten
    # Delete layers in the TOC
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        m = p.activeMap
        try:
            for layer in m.listLayers(out_data):
                arcpy.Delete_management(layer)
            for feature in arcpy.ListFeatureClasses(out_data):
                arcpy.Delete_management(feature)
        except arcpy.ExecuteError:
            arcpy.AddMessage("Renaming failed to delete existing feature")
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        try:
            for layer in arcpy.mapping.ListLayers(mxd, out_data):
                arcpy.Delete_management(layer)
            # Delete feature classes in the geodatabase
            for feature in arcpy.ListFeatureClasses(out_data):
                arcpy.Delete_management(feature)
        except arcpy.ExecuteError:
            arcpy.AddMessage("Renaming failed to delete existing feature")
    # Execute renaming
    out_fc = arcpy.CopyFeatures_management(in_data, out_data)
    arcpy.Delete_management(in_data)

    return out_fc
Beispiel #7
0
def main():
    # GET PARAMETER VALUES
    Map_Units_Dissolve_Provided = arcpy.GetParameterAsText(0)
    Transects_Provided = arcpy.GetParameterAsText(1)  # optional
    Project_Folder = arcpy.GetParameterAsText(2)
    Project_Name = arcpy.GetParameterAsText(3)  # optional

    # DEFINE DIRECTORIES & PATH NAMES FOR FOLDERS & GBDs
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    # Construct pathname to workspace
    projectGDB = arcpy.Describe(Map_Units_Dissolve_Provided).path
    arcpy.AddMessage("Project geodatabase: " + projectGDB)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = projectGDB
    scratch_folder = os.path.join(arcpy.Describe(projectGDB).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(
            arcpy.Describe(projectGDB).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    # Filenames for feature classes or rasters used by this script
    MAP_UNITS_DISSOLVE = "Map_Units_Dissolve"
    # Filenames for feature classes or rasters created by this script
    TRANSECTS_SJ = "Transects_SpatialJoin"

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

    # FUNCTION CALLS
    if Transects_Provided:
        # Update message
        arcpy.AddMessage("Executing spatial join of Transects and "
                         "Map_Unit_Dissolve layer")

        # hqtlib.AddTransectFields(Transects)
        Map_Units_Dissolve = MAP_UNITS_DISSOLVE
        out_name = TRANSECTS_SJ
        hqtlib.TransectJoin(Map_Units_Dissolve, Transects_Provided, out_name)

    else:
        # arcpy.AddError("ERROR:: Please provide the transects feature "
        #                "class or shapefile. See User's Guide.")
        # sys.exit(0)

        # Check out Spatial Analyst extension
        hqtlib.CheckOutSpatialAnalyst()

        # Check Map_Units_Dissolve layer
        required_fields = ["Transects"]
        no_null_fields = ["Transects"]
        expected_fcs = None
        hqtlib.CheckPolygonInput(Map_Units_Dissolve_Provided, required_fields,
                                 expected_fcs, no_null_fields)

        Map_Units = Map_Units_Dissolve_Provided
        field_name = "Transects"
        out_name = "Transects"
        transects = hqtlib.GenerateTransects(
            projectGDB, Map_Units, field_name,
            out_name)  ##swapped "workspace" for "project GDB"
        hqtlib.AddTransectFields(transects)

        # Identify the map unit associated with each transect
        hqtlib.TransectJoin(MAP_UNITS_DISSOLVE, transects, TRANSECTS_SJ)

    # Remove unnecessary fields
    allowable_fields = [
        "Bearing1", "Bearing2", "Bearing3", "UTM_E", "UTM_N", "Map_Unit_ID",
        "Map_Unit_Name", "Indirect", "Acres", "PropLek", "PropMesic",
        "Current_Breed", "Current_Summer", "Current_Winter", "Projected_Breed",
        "Projected_Summer", "Projected_Winter", "Permanent_Breed",
        "Permanent_Summer", "Permanent_Winter", "Transects"
    ]
    util.SimplifyFields(TRANSECTS_SJ, allowable_fields)

    # Add Transects to map
    util.AddToMap(TRANSECTS_SJ)

    # Export data to Excel
    table = TRANSECTS_SJ
    hqtlib.ExportToExcel(table, Project_Folder, Project_Name)

    # Save map document
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #8
0
def main():
    # GET PARAMETER VALUES
    workspace = arcpy.GetParameterAsText(0)
    Provided_Disturbance = arcpy.GetParameterAsText(1)
    includes_anthro_mod = arcpy.GetParameterAsText(2)  # optional
    Proposed_Modified_Features_Provided = arcpy.GetParameterAsText(
        3)  # optional

    # Update boolean parameters
    includes_anthro_mod = ccslib.Str2Bool(includes_anthro_mod)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)

    # Instantiate a ccsStandard object
    ccsStandard = ccslib.ccsStandard(workspace, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    arcpy.env.scratchWorkspace = workspace
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    AnthroAttributeTable = ccsStandard.AnthroAttributeTable
    coordinate_system = ccsStandard.CoorSystem
    # Filenames for feature classes and rasters created by this script
    PROPOSED_SURFACE_DISTURBANCE_DEBITS = "Proposed_Surface_Disturbance_Debits"
    PROPOSED_MODIFIED_FEATURES = "Proposed_Modified_Features"

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

    # FUNCTION CALLS
    # Check tool version
    ccslib.CheckToolVersion()

    # Update includes_anthro_mod if Proposed_Modified_Features is
    # provided
    if Proposed_Modified_Features_Provided and not includes_anthro_mod:
        includes_anthro_mod = True

    # Check input features for existence of features and feature type;
    # create template if Proposed_Surface_Disturbance is not provided
    if Provided_Disturbance:
        # Check provided input
        ccslib.CheckPolygonInput(Provided_Disturbance)

        # Check provided input for 'Feature' field, error and exit if so
        existing_fields = [
            field.name.lower()
            for field in arcpy.ListFields(Provided_Disturbance)
        ]
        if 'feature' in existing_fields:
            arcpy.AddError("ERROR:: The provided proposed surface "
                           "disturbance layer includes a field named "
                           "'Feature' in the attribute table. Please "
                           "rename this field and re-run this tool. ")
            sys.exit(0)

        # Create a local copy of the provided disturbance in case it is
        # the output of the projected input from re-running Debit Tool 1
        PSD_copy = arcpy.CopyFeatures_management(Provided_Disturbance,
                                                 "in_memory/PSD_provided")

        # Update message
        arcpy.AddMessage("Projecting provided feature(s) to " +
                         coordinate_system.name)

        # Project input to standard coordinate system
        inputFeature = PSD_copy
        out_name = PROPOSED_SURFACE_DISTURBANCE_DEBITS
        Proposed_Surface_Disturbance = ccslib.ProjectInput(
            inputFeature, out_name, coordinate_system)
        zoom_to = True

    else:
        # Update message
        arcpy.AddMessage("Creating template for digitizing proposed "
                         "surface disturbance \nDigitize features in "
                         "feature class named "
                         "Proposed_Surface_Disturbance_Debits created within "
                         "the project's unique geodatabase")

        # Create a template
        out_name = PROPOSED_SURFACE_DISTURBANCE_DEBITS
        Proposed_Surface_Disturbance = ccslib.CreateTemplate(
            workspace, out_name, coordinate_system)
        zoom_to = False

    if includes_anthro_mod:
        # Create a template for digitizing anthropogenic features proposed for
        # modification
        out_name = "Proposed_Modified_Features_tmp"
        Template_Features = ccslib.CreateTemplate(workspace, out_name,
                                                  coordinate_system)

        if Proposed_Modified_Features_Provided:
            # Do not zoom to proposed surface disturbance
            zoom_to = False

            # Merge with the provided layer, if provided
            fileList = [Proposed_Modified_Features_Provided, Template_Features]
            out_name = "in_memory/tmp_Modified"
            merged_features = ccslib.MergeFeatures(fileList, out_name)

            # Rename the provided as merged (cannot merge two files with
            # equivalent filenames) as Proposed_Modified_Features
            in_data = merged_features
            out_data = PROPOSED_MODIFIED_FEATURES
            Proposed_Modified_Features = arcpy.CopyFeatures_management(
                in_data, out_data)

        else:
            # Save the template as Proposed_Modified_Features
            in_data = Template_Features
            out_data = PROPOSED_MODIFIED_FEATURES
            Proposed_Modified_Features = ccslib.RenameFeatureClass(
                in_data, out_data)

        # Update message
        arcpy.AddMessage("Adding fields Type and Subtype to "
                         "the Proposed_Modified_Features layer")

        # Add fields Type and Subtype
        inputFeature = Proposed_Modified_Features
        fieldsToAdd = ["Type", "Subtype"]
        fieldTypes = ["TEXT", "TEXT"]
        ccslib.AddFields(inputFeature,
                         fieldsToAdd,
                         fieldTypes,
                         copy_existing=True)

        # Clean up
        arcpy.Delete_management(Template_Features)

        # Create Domain for Subtype attributes and assign to Subtype field
        featureList = [Proposed_Modified_Features]
        ccslib.AddSubtypeDomains(featureList, workspace, AnthroAttributeTable)

        # Add layer to map for editing
        layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
        ccslib.AddToMap(Proposed_Modified_Features, layerFile)

    # Add layer to map document
    layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
    ccslib.AddToMap(Proposed_Surface_Disturbance, layerFile, zoom_to)

    # Update message
    arcpy.AddMessage("Adding fields to Proposed_Surface_Disturbance")

    # Add fields for Type, Subtype, Surface Disturbance, and Reclassifed Subtype
    input_feature = Proposed_Surface_Disturbance
    fields = ["Type", "Subtype", "Surface_Disturbance", "Reclassified_Subtype"]
    fieldTypes = ["TEXT", "TEXT", "TEXT", "TEXT"]
    ccslib.AddFields(input_feature, fields, fieldTypes, copy_existing=True)

    # Add Domains to Proposed_Surface_Disturbance_Debits layer
    featureList = [Proposed_Surface_Disturbance]
    domain_name = "Type"
    code_list = [
        row[0] for row in arcpy.da.SearchCursor(AnthroAttributeTable, "Type")
    ]

    # Create Domain for Subtype attributes and assign to Subtype field
    ccslib.AddSubtypeDomains(featureList, workspace, AnthroAttributeTable)

    # Create Domain for Type attributes and assign to Type field
    ccslib.AddCodedTextDomain(featureList, workspace, domain_name, code_list)

    # Create Domain for Type attributes and assign to Surface Disturbance field
    domain_name = "Surface_Disturbance"
    code_list = [
        "Term_Reclaimed", "Term_Retired", "Term_Reclassified", "Permanent"
    ]
    ccslib.AddCodedTextDomain(featureList, workspace, domain_name, code_list)

    # Create Domain for Type attributes and assign to Reclassified Subtype
    # field
    domain_name = "Reclassified_Subtype"
    code_list = [
        row[0]
        for row in arcpy.da.SearchCursor(AnthroAttributeTable, "Subtype")
    ]
    ccslib.AddCodedTextDomain(featureList, workspace, domain_name, code_list)

    if includes_anthro_mod:
        # Extend type domain to Proposed_Modified_Features
        try:
            arcpy.AssignDomainToField_management(Proposed_Modified_Features,
                                                 "Type", "Type")
        except arcpy.ExecuteError:
            arcpy.AddMessage("Type domain not updated for "
                             "Proposed_Modified_Features")

    # Save map document and exit
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #9
0
inDTM = arcpy.GetParameterAsText(1)
outGDB = arcpy.GetParameterAsText(2)
temp = []

try:
    print "Starting at " + time.strftime("%c")

    ## This section returns the system information for the user.  This is used to help
    ## debug any potential errors returned by the tool.  This information does not compromise
    ## the annonymity of the user or their system.
    ##---------------------------------------------------------------------------------------

    # Get information about ArcGIS version installed...
    arcpy.SetProgressorLabel("Reading installation information...")
    arcpy.AddMessage("--------------------------------")
    installList = arcpy.ListInstallations()
    for install in installList:
        arcpy.AddMessage("Product: ArcGIS for " + install + " " +
                         arcpy.GetInstallInfo(install)["Version"] + " SP " +
                         arcpy.GetInstallInfo()["SPNumber"] + ", Build " +
                         arcpy.GetInstallInfo()["BuildNumber"])
        print("Product: ArcGIS for " + install + " " +
              arcpy.GetInstallInfo(install)["Version"] + " SP " +
              arcpy.GetInstallInfo()["SPNumber"] + ", Build " +
              arcpy.GetInstallInfo()["BuildNumber"])
        arcpy.AddMessage("Installed on: " +
                         arcpy.GetInstallInfo()["InstallDate"] + " " +
                         arcpy.GetInstallInfo()["InstallTime"])
        print("Installed on: " + arcpy.GetInstallInfo()["InstallDate"] + " " +
              arcpy.GetInstallInfo()["InstallTime"])
        arcpy.AddMessage("Using " + arcpy.ProductInfo() + " license level")
Beispiel #10
0
def main():
    # GET PARAMETER VALUES
    Map_Units_Provided = arcpy.GetParameterAsText(0)
    Transects_Provided = arcpy.GetParameterAsText(1)  # optional
    Project_Folder = arcpy.GetParameterAsText(2)
    Project_Name = arcpy.GetParameterAsText(3)  # optional

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Construct pathname to workspace
    projectGDB = arcpy.Describe(Map_Units_Provided).path
    arcpy.AddMessage("Project geodatabase: " + projectGDB)

    # Instantiate a idStandard object
    cheStandard = cohqt.cheStandard(projectGDB, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = projectGDB
    scratch_folder = os.path.join(arcpy.Describe(projectGDB).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(
            arcpy.Describe(projectGDB).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    # Filenames for feature classes or rasters used by this script
    MAP_UNITS = "Map_Units"

    # Filenames for feature classes or rasters created by this script
    TRANSECTS_SJ = "Transects_SpatialJoin"

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

    # FUNCTION CALLS

    # Check Map_Units_Dissolve layer
    required_fields = ["Transects"]
    no_null_fields = None
    expected_fcs = None
    hqtlib.CheckPolygonInput(Map_Units_Provided, required_fields, expected_fcs,
                             no_null_fields)

    # Update Map Units layer with provided layer and add to map
    Map_Units = util.AdoptParameter(Map_Units_Provided,
                                    MAP_UNITS,
                                    preserve_existing=False)
    layerFile = cheStandard.getLayerFile("MapUnits.lyr")
    util.AddToMap(Map_Units, layerFile)

    if Transects_Provided:
        # Update message
        arcpy.AddMessage("Executing spatial join of Transects and "
                         "Map_Unit_Dissolve layer")

        out_name = TRANSECTS_SJ
        transects = Transects_Provided
        hqtlib.TransectJoin(Map_Units, transects, out_name)

    else:
        # arcpy.AddError("ERROR:: Please provide the transects feature"
        #                "class or shapefile provided by the SETT")
        # sys.exit(0)

        # Check out Spatial Analyst extension
        hqtlib.CheckOutSpatialAnalyst()

        # Generate transects
        field_name = "Transects"
        out_name = "Transects"
        transects = hqtlib.GenerateTransects(projectGDB, Map_Units, field_name,
                                             out_name)

        # Add transect fields
        hqtlib.AddTransectFields(transects)
        util.AddToMap(out_name)

        # Identify the map unit associated with each transect
        out_name = TRANSECTS_SJ
        transects = transects
        hqtlib.TransectJoin(Map_Units, transects, out_name)

    # Remove unnecessary fields
    allowable_fields = [
        "Bearing1", "Bearing2", "Bearing3", "UTM_E", "UTM_N", "Map_Unit_ID",
        "Map_Unit_Name", "Precip", "Transects"
    ]
    util.SimplifyFields(TRANSECTS_SJ, allowable_fields)

    # Add Transects to map
    util.AddToMap(TRANSECTS_SJ)

    # Export data to Excel
    table = TRANSECTS_SJ
    hqtlib.ExportToExcel(table, Project_Folder, Project_Name)

    # Save map document and exit
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #11
0
def main():
    # GET PARAMETER VALUES
    Map_Units_Provided = arcpy.GetParameterAsText(0)  # optional
    Proposed_Modified_Features_Provided = arcpy.GetParameterAsText(1)  # optional
    Project_Folder = arcpy.GetParameterAsText(2)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Construct pathname to workspace
    if Map_Units_Provided:
        workspace = arcpy.Describe(Map_Units_Provided).path
    elif Proposed_Modified_Features_Provided:
        workspace = arcpy.Describe(Proposed_Modified_Features_Provided).path
    else:
        arcpy.AddMessage("Please provide either a Map_Units or " +
                         "Proposed_Modified_Features layer.")
        sys.exit(0)
    arcpy.AddMessage("Project geodatabase: " + workspace)
    Project_Folder = arcpy.Describe(workspace).path
    arcpy.AddMessage("Project folder:" + Project_Folder)
    
    # Instantiate a ccsStandard object
    ccsStandard = ccslib.ccsStandard(workspace, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    scratch_folder = os.path.join(
        arcpy.Describe(workspace).path, 'scratch'
        )
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management( arcpy.Describe(workspace).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    AnthroAttributeTable = ccsStandard.AnthroAttributeTable
    # Filenames for feature class and rasters created by this script
    INDIRECT_IMPACT_AREA = "Indirect_Impact_Area"
    ANALYSIS_AREA = "Analysis_Area"
    # Filenames for feature classes or rasters used by this script
    MAP_UNITS = "Map_Units"
    PROPOSED_MODIFIED_FEATURES = "Proposed_Modified_Features"
    CREDIT_PROJECT_AREA = "Credit_Project_Area"

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

    # FUNCTION CALLS
    # Check provided layers
    if not Map_Units_Provided and not Proposed_Modified_Features_Provided:
        arcpy.AddError("ERROR:: Please provide a 'Map_Units' and/or "
                       "'Proposed_Modified_Features' feature.")
        sys.exit(0)

    if not Proposed_Modified_Features_Provided:
        # Ensure Proposed_Modified_Features does not exist
        if arcpy.Exists("Proposed_Modified_Features"):
            arcpy.AddError("ERROR:: A 'Proposed_Modified_Features' layer "
                           "was detected in the project's geodatabase. "
                           "Provide the 'Proposed_Modified_Features' layer "
                           "and re-run Credit Tool 2.")
            sys.exit(0)

    if Map_Units_Provided:
        # Clear selection, if present
        ccslib.ClearSelectedFeatures(Map_Units_Provided)

        # Check provided layer
        feature = Map_Units_Provided
        required_fields = ["Map_Unit_ID", "Map_Unit_Name", "Meadow"]
        no_null_fields = ["Map_Unit_ID", "Meadow"]
        expected_fcs = [CREDIT_PROJECT_AREA]
        ccslib.CheckPolygonInput(feature, required_fields, expected_fcs,
                                 no_null_fields)

        # Update Map Units layer with provided layer
        provided_input = Map_Units_Provided
        parameter_name = MAP_UNITS
        preserve_existing = False
        Map_Units = ccslib.AdoptParameter(provided_input, parameter_name,
                                          preserve_existing)

        # Add Map Units layer to map
        layerFile = ccsStandard.getLayerFile("Map_Units.lyr")
        ccslib.AddToMap(Map_Units, layerFile)

        # Provide location of Credit Project Area
        Credit_Project_Area = CREDIT_PROJECT_AREA

    # Set up flag for projects that propose to modify anthro features
    includes_anthro_mod = False

    if Proposed_Modified_Features_Provided:
        # Update flag
        includes_anthro_mod = True

        # Clear selection, if present
        ccslib.ClearSelectedFeatures(Proposed_Modified_Features_Provided)

        # Check provided layer
        required_fields = ["Type", "Subtype"]
        no_null_fields = required_fields
        expected_fcs = None
        ccslib.CheckPolygonInput(Proposed_Modified_Features_Provided,
                                 required_fields, expected_fcs, no_null_fields)

        # Update Proposed_Modified_Features with provided layer
        provided_input = Proposed_Modified_Features_Provided
        parameterName = PROPOSED_MODIFIED_FEATURES
        preserve_existing = False
        Proposed_Modified_Features = ccslib.AdoptParameter(
            provided_input, parameterName, preserve_existing
            )

        # Add Proposed Modified Features layer to map
        layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
        ccslib.AddToMap(Proposed_Modified_Features, layerFile)

        # Update message
        arcpy.AddMessage("Creating the area of indirect benefit")

        # Create Credit_Project_Area for projects that propose to modify
        # anthropogenic features
        # Create the Indirect_Impact_Area
        in_data = Proposed_Modified_Features
        out_name = INDIRECT_IMPACT_AREA
        Indirect_Impact_Area = ccslib.CreateIndirectImpactArea(
            in_data, AnthroAttributeTable, out_name
            )

        # Add field "Indirect"
        input_feature = Indirect_Impact_Area
        fieldsToAdd = ["Indirect"]
        fieldTypes = ["TEXT"]
        ccslib.AddFields(input_feature, fieldsToAdd, fieldTypes)

        # Update field 'Indirect' to equal 'True'
        with arcpy.da.UpdateCursor(Indirect_Impact_Area,
                                   fieldsToAdd) as cursor:
            for row in cursor:
                row[0] = "True"
                cursor.updateRow(row)

        if Map_Units_Provided:
            # Merge with Credit_Project_Boundary
            fileList = [Map_Units_Provided, Indirect_Impact_Area]
            out_name = "in_memory/Credit_Project_Boundary"
            Project_Area = arcpy.Union_analysis(fileList, out_name)
        else:
            Project_Area = Indirect_Impact_Area
                
        # Eliminate areas of non-habitat to create Credit_Project_Area
        out_name = CREDIT_PROJECT_AREA
        habitat_bounds = ccsStandard.HabitatBounds
        Credit_Project_Area = ccslib.EliminateNonHabitat(
            Project_Area, out_name, habitat_bounds
            )

    # Update message
    arcpy.AddMessage("Copying Credit_Project_Area as shapefile into project"
                     " folder")

    # Export feature class to shapefile in project folder so it can be sent to
    # NDOW for Dist_Lek layer
    arcpy.FeatureClassToShapefile_conversion(Credit_Project_Area,
                                             Project_Folder)

    # Update message
    arcpy.AddMessage("Creating Analysis Area")

    # Create Analysis Area
    out_name = ANALYSIS_AREA
    Analysis_Area = ccslib.CreateAnalysisArea(Credit_Project_Area,
                                              AnthroAttributeTable,
                                              out_name)

    # Add Analysis_Area to map
    layerFile = ccsStandard.getLayerFile("Analysis_Area.lyr")
    ccslib.AddToMap(Analysis_Area, layerFile, zoom_to=True)

    # Update message
    arcpy.AddMessage("Clipping all anthropogenic features to Analysis Area "
                     "and adding templates for digitizing new anthropogenic "
                     "features")

    # Clip all provided anthropogenic feature layers and add to map
    clip_features = Analysis_Area
    anthroFeaturePath = ccsStandard.AnthroFeaturePath
    ccslib.ClipAnthroFeaturesCredit(clip_features, anthroFeaturePath)
    featureList = arcpy.ListFeatureClasses("Anthro_*_Clip")

    # If the project proposes to modify anthropogenic features,
    # add a 'Subtype_As_Modified" field
    if includes_anthro_mod:
        fieldsToAdd = ["Subtype_As_Modified"]
        fieldTypes = ["TEXT"]
        for feature in featureList:
            ccslib.AddFields(feature, fieldsToAdd, fieldTypes)
            # Apply domains
            field = fieldsToAdd[0]
            domainName = feature[7:-5] + "_Subtypes"
            try:
                arcpy.AssignDomainToField_management(feature, field, domainName)
            except arcpy.ExecuteError:
                arcpy.AddMessage(domainName + " not updated. Use caution "
                                 "when populating attribute field")
            # Copy current subtype to Subtype as Modified field
            arcpy.CalculateField_management(feature, field, "!Subtype!",
                                            "PYTHON_9.3")

    # Add each feature to map for editing
    for feature in featureList:
        ccslib.AddAnthroToMap(workspace, feature)

    # Clean up
    arcpy.Delete_management("in_memory")

    # Save map document
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #12
0
import arcpy

print 'List Installations'
for install in arcpy.ListInstallations():
    print(install)
Beispiel #13
0
def main():
    # GET PARAMETER VALUES
    Proposed_Surface_Disturbance_Eligible = arcpy.GetParameterAsText(0)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    # Construct pathname to workspace
    workspace = arcpy.Describe(Proposed_Surface_Disturbance_Eligible).path
    arcpy.AddMessage("Project geodatabase: " + workspace)

    # Instantiate a ccsStandard object
    ccsStandard = ccslib.ccsStandard(workspace, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    scratch_folder = os.path.join(arcpy.Describe(workspace).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(
            arcpy.Describe(workspace).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE VARIABLES FOR INPUT DATA

    # Filenames for feature classes or rasters used by this script
    ELIGIBLE_PROPOSED_FEATURES = "Proposed_Surface_Disturbance_Eligible"

    # Filenames for feature classes or rasters created by this script
    ANALYSIS_AREA = "Analysis_Area"

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

    # FUNCTION CALLS
    # Check tool version
    ccslib.CheckToolVersion()

    # Clear selection, if present
    ccslib.ClearSelectedFeatures(Proposed_Surface_Disturbance_Eligible)

    # Check Proposed_Surface_Disturbance_Eligible
    feature = Proposed_Surface_Disturbance_Eligible
    required_fields = ["Type", "Subtype", "Surface_Disturbance"]
    no_null_fields = required_fields
    expected_fcs = None
    ccslib.CheckPolygonInput(feature, required_fields, expected_fcs,
                             no_null_fields)

    # Update Proposed_Surface_Disturbance_Elligible layer with provided layer
    provided_input = Proposed_Surface_Disturbance_Eligible
    parameter_name = ELIGIBLE_PROPOSED_FEATURES
    Proposed_Surface_Disturbance_Eligible = ccslib.AdoptParameter(
        provided_input, parameter_name, preserve_existing=False)

    # Replace Proposed_Surface_Disturbance_Elibible layer on map
    layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
    ccslib.AddToMap(Proposed_Surface_Disturbance_Eligible, layerFile)

    # Update message
    arcpy.AddMessage("Clipping all anthropogenic features to Analysis Area "
                     "and adding templates for digitizing new anthropogenic "
                     "features")

    # Clip all provided anthropogenic feature layers and add to map
    clip_features = ANALYSIS_AREA
    anthroFeaturePath = ccsStandard.AnthroFeaturePath
    proposed_anthro = Proposed_Surface_Disturbance_Eligible
    fieldsToAdd = ["Overlap_Status", "Returned", "Subtype_As_Modified"]
    fieldTypes = ["TEXT", "TEXT", "TEXT"]
    mod_field = fieldsToAdd[0]
    removed_code = "Removed"
    retained_code = "Retained"
    ccslib.ClipAnthroFeaturesDebit(clip_features, anthroFeaturePath,
                                   proposed_anthro, fieldsToAdd, fieldTypes,
                                   mod_field, removed_code, retained_code)

    # Apply domains for Overlap_Status field and populate default
    featureList = arcpy.ListFeatureClasses("Anthro_*_Clip")
    domain_name = fieldsToAdd[0]
    code_list = ["Retained", "Removed"]
    ccslib.AddCodedTextDomain(featureList,
                              workspace,
                              domain_name,
                              code_list,
                              assign_default=True,
                              populate_default=True)

    # Apply domains for Returned field
    domain_name = fieldsToAdd[1]
    code_list = ["True", "False"]
    ccslib.AddCodedTextDomain(featureList,
                              workspace,
                              domain_name,
                              code_list,
                              assign_default=True,
                              populate_default=True)

    # Add all Subtype anthro domains because ArcGIS doesn't transfer them
    # consistently
    desc_c = arcpy.Describe(workspace)
    current_domains = desc_c.domains
    desc_w = arcpy.Describe(ccsStandard.AnthroFeaturePath)
    anthro_domains = desc_w.domains
    for domain_name in anthro_domains:
        if domain_name not in current_domains and "Subtype" in domain_name:
            source_workspace = ccsStandard.AnthroFeaturePath
            code_field = 'code'
            description_field = 'description'
            domain_table = arcpy.DomainToTable_management(
                source_workspace, domain_name, domain_name, code_field,
                description_field)
            arcpy.TableToDomain_management(domain_table, code_field,
                                           description_field, workspace,
                                           domain_name)
            arcpy.Delete_management(domain_table)

    # Apply domains for each anthro feature
    for feature in featureList:
        # Apply for each Subtype field
        field = "Subtype"
        domainName = feature[7:-5] + "_Subtypes"
        arcpy.AssignDomainToField_management(feature, field, domainName)
        subtypes = arcpy.da.ListSubtypes(feature)
        if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '':
            pass
        else:
            st_codes = [
                str(stcode) for stcode, stdict in list(subtypes.items())
            ]
            arcpy.AssignDomainToField_management(feature, field, domainName,
                                                 st_codes)

        # Apply for each Subtype As Modified Field
        field = fieldsToAdd[-1]
        domainName = feature[7:-5] + "_Subtypes"
        arcpy.AssignDomainToField_management(feature, field, domainName)
        subtypes = arcpy.da.ListSubtypes(feature)
        if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '':
            pass
        else:
            st_codes = [
                str(stcode) for stcode, stdict in list(subtypes.items())
            ]
            arcpy.AssignDomainToField_management(feature, field, domainName,
                                                 st_codes)

        # Copy current subtype to Subtype as Modified field
        arcpy.CalculateField_management(feature, field, "!Subtype!",
                                        "PYTHON_9.3")

    # Add each feature to map for editing
    for feature in featureList:
        ccslib.AddAnthroToMap(workspace, feature)

    # Save map document and exit
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #14
0
def main():
    # GET PARAMETER VALUES
    Analysis_Area = arcpy.GetParameterAsText(0)
    Current_Anthro_Features_Provided = arcpy.GetParameterAsText(1)  # optional
    Dist_Lek = arcpy.GetParameterAsText(2)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    # Construct pathname to workspace
    workspace = arcpy.Describe(Analysis_Area).path
    arcpy.AddMessage("Project geodatabase: " + workspace)

    # Instantiate a ccsStandard object
    ccsStandard = ccslib.ccsStandard(workspace, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    scratch_folder = os.path.join(arcpy.Describe(workspace).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(
            arcpy.Describe(workspace).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE VARIABLES FOR INPUT DATA
    AnthroAttributeTable = ccsStandard.AnthroAttributeTable
    emptyRaster = ccsStandard.EmptyRaster
    inputDataPath = ccsStandard.InputDataPath

    # Filenames for feature classes and raster used by this script
    ELIGIBLE_PROPOSED_FEATURES = "Proposed_Surface_Disturbance_Eligible"
    DEBIT_PROJECT_AREA = "Debit_Project_Area"

    # Filenames for feature classes and rasters created by this script
    CURRENT_ANTHRO_FEATURES = "Current_Anthro_Features"
    PROJECTED_ANTHRO_FEATURES = "Projected_Anthro_Features"
    PERMANENT_ANTHRO_FEATURES = "Permanent_Anthro_Features"
    CURRENT_ANTHRO_DISTURBANCE = "Current_Anthro_Disturbance"
    PROJECTED_ANTHRO_DISTURBANCE = "Projected_Anthro_Disturbance"
    PERMANENT_ANTHRO_DISTURBANCE = "Permanent_Anthro_Disturbance"
    MAP_UNITS = "Map_Units"

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

    # FUNCTION CALLS
    # Check tool version
    ccslib.CheckToolVersion()

    # Check out Spatial Analyst extension
    ccslib.CheckOutSpatialAnalyst()

    # Check Analysis_Area
    expected_fcs = [ELIGIBLE_PROPOSED_FEATURES, DEBIT_PROJECT_AREA]
    ccslib.CheckPolygonInput(Analysis_Area, expected_fcs=expected_fcs)

    # Create Current_Anthro_Features layer, or copy provided into geodatabase
    if Current_Anthro_Features_Provided:
        # Clear selection, if present
        ccslib.ClearSelectedFeatures(Current_Anthro_Features_Provided)

        # Check Current_Anthro_Features
        required_fields = [
            "Type", "Subtype", "Overlap_Status", "Returned",
            "Subtype_As_Modified"
        ]
        no_null_fields = None
        expected_fcs = None
        ccslib.CheckPolygonInput(Current_Anthro_Features_Provided,
                                 required_fields, expected_fcs, no_null_fields)

        # Update message
        arcpy.AddMessage("Copying Current_Anthro_Features to project "
                         "geodatabase")

        # Copy Current_Anthro_Features to geodatabase
        provided_input = Current_Anthro_Features_Provided
        parameter_name = CURRENT_ANTHRO_FEATURES
        Current_Anthro_Features = ccslib.AdoptParameter(provided_input,
                                                        parameter_name,
                                                        preserve_existing=True)

    else:
        # Update message
        arcpy.AddMessage("Merging all clipped anthropogenic features to "
                         "create the Current_Anthro_Features layer")

        # Merge features (selecting only polygon features)
        fileList = arcpy.ListFeatureClasses("Anthro*Clip",
                                            feature_type="Polygon")
        out_name = CURRENT_ANTHRO_FEATURES
        Current_Anthro_Features = ccslib.MergeFeatures(fileList, out_name)

    # Simplify fields. critical to remove any fields named
    # 'Surface_Disturbance' in Current_Anthro_Features before joining
    # Proposed_Surface_Disturbance to create Projected_Anthro_Features
    allowable_fields = [
        "Type", "Subtype", "SubtypeID", "Subtype_As_Modified",
        "Overlap_Status", "Returned"
    ]
    ccslib.SimplifyFields(Current_Anthro_Features, allowable_fields)

    # Remove subtypes from Current_Anthro_Features
    feature = Current_Anthro_Features
    subtypes = arcpy.da.ListSubtypes(feature)
    try:
        if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '':
            pass
        else:
            for subtype in subtypes:
                arcpy.RemoveSubtype_management(feature, subtype)
                arcpy.AddMessage("Subtype removed")
    except arcpy.ExecuteError:
        arcpy.AddMessage("Could not remove Subtype Domain from "
                         "Current_Anthro_Features")

    # Add Domains for Type and Subtype
    try:
        arcpy.RemoveDomainFromField_management(feature, "Type")
        arcpy.AssignDomainToField_management(feature, "Type", "Type")
    except arcpy.ExecuteError:
        arcpy.AddMessage("Could not update Type Domain for "
                         "Current_Anthro_Features")
    try:
        arcpy.RemoveDomainFromField_management(feature, "Subtype")
        arcpy.AssignDomainToField_management(feature, "Subtype", "Subtype")
    except arcpy.ExecuteError:
        arcpy.AddMessage("Could not update Subtype Domain for "
                         "Current_Anthro_Features")
    try:
        arcpy.RemoveDomainFromField_management(feature, "Subtype_As_Modified")
        arcpy.AssignDomainToField_management(feature, "Subtype", "Subtype")
    except arcpy.ExecuteError:
        arcpy.AddMessage("Could not update Type Domain for "
                         "Current_Anthro_Features")

    # Calculate Current_Anthro_Disturbance
    extent_fc = Analysis_Area
    anthro_features = Current_Anthro_Features
    term = ccsStandard.DebitTerms[0]
    Current_Anthro_Disturbance = ccslib.CalcAnthroDist(extent_fc,
                                                       anthro_features,
                                                       emptyRaster,
                                                       AnthroAttributeTable,
                                                       term)
    Current_Anthro_Disturbance.save(CURRENT_ANTHRO_DISTURBANCE)

    # Update message
    arcpy.AddMessage("Current_Anthro_Disturbance Calculated")
    arcpy.AddMessage("Removing any anthropogenic features from the "
                     "Current_Anthro_Features layer that will be "
                     "replaced or upgraded from one subtype to another "
                     "by the debit project")

    # Calculate post-project anthropogenic disturbance
    mod_field = "Overlap_Status"
    removed_code = "Removed"
    subtype_mod_field = "Subtype_As_Modified"
    out_name = PROJECTED_ANTHRO_FEATURES
    Projected_Anthro_Features = ccslib.SelectProposed(
        Current_Anthro_Features, ELIGIBLE_PROPOSED_FEATURES, mod_field,
        removed_code, subtype_mod_field, out_name)

    # Simplify fields (do not remove Surface Disturbance or Reclassified
    # Subtype field for use in SelectPermanent())
    allowable_fields = [
        "Type", "Subtype", "SubtypeID", "Overlap_Status", "Returned",
        "Subtype_As_Modified"
        "Surface_Disturbance", "Reclassified_Subtype"
    ]
    ccslib.SimplifyFields(Projected_Anthro_Features, allowable_fields)

    # Calculate Projected_Anthro_Disturbance
    extent_fc = Analysis_Area
    anthro_features = Projected_Anthro_Features
    term = ccsStandard.DebitTerms[1]
    Projected_Anthro_Disturbance = ccslib.CalcAnthroDist(
        extent_fc, anthro_features, emptyRaster, AnthroAttributeTable, term)
    Projected_Anthro_Disturbance.save(PROJECTED_ANTHRO_DISTURBANCE)

    # Update message
    arcpy.AddMessage("Projected_Anthro_Disturbance Calculated")
    arcpy.AddMessage("Creating Permanent Anthro Features and calculating "
                     "disturbance")

    # Calculate permanent anthropogenic disturbance
    # Select permanent anthropogenic features from Projected Anthro Features
    mod_field = "Overlap_Status"
    returned_field = "Returned"
    subtype_mod_field = "Subtype_As_Modified"
    duration_field = "Surface_Disturbance"
    permanent_codes = ["Term_Reclassified", "Permanent"]
    reclass_code = "Term_Reclassified"
    reclass_subtype_field = "Reclassified_Subtype"
    out_name = PERMANENT_ANTHRO_FEATURES
    Permanent_Anthro_Features = ccslib.SelectPermanent(
        Current_Anthro_Features, ELIGIBLE_PROPOSED_FEATURES, mod_field,
        returned_field, subtype_mod_field, duration_field, permanent_codes,
        reclass_code, reclass_subtype_field, out_name)

    # Simplify fields
    allowable_fields = [
        "Type", "Subtype", "SubtypeID", "Overlap_Status", "Returned",
        "Subtype_As_Modified"
        "Surface_Disturbance", "Reclassified_Subtype"
    ]
    ccslib.SimplifyFields(Permanent_Anthro_Features, allowable_fields)

    # Calculate Permanent Anthro Disturbance
    extent_fc = Analysis_Area
    anthro_features = Permanent_Anthro_Features
    term = ccsStandard.DebitTerms[2]
    Permanent_Anthro_Disturbance = ccslib.CalcAnthroDist(
        extent_fc, anthro_features, emptyRaster, AnthroAttributeTable, term)
    Permanent_Anthro_Disturbance.save(PERMANENT_ANTHRO_DISTURBANCE)

    # Update message
    arcpy.AddMessage("Permanent_Anthro_Disturbance Calculated")

    # Calculate local scale modifiers for Current, Projected, and
    # Permanent condition
    extent_fc = Analysis_Area
    terms = ccsStandard.DebitTerms
    for term in terms:
        anthro_disturbance = term + "_Anthro_Disturbance"
        ccslib.CalcModifiers(extent_fc, inputDataPath, Dist_Lek,
                             anthro_disturbance, term)

    # Calculate impact intensity for debit project
    try:
        ccslib.calcDebitImpact(inputDataPath)

        # Add debit project impact to map
        layerFile = ccsStandard.getLayerFile("Debit_Project_Impact.lyr")
        ccslib.AddToMap("Debit_Project_Impact", layerFile, zoom_to=True)
    except:
        pass

    # Update message
    arcpy.AddMessage("Creating Map Units layer")

    # Create Map_Units layer
    Project_Area = DEBIT_PROJECT_AREA
    out_name = MAP_UNITS
    Map_Units = ccslib.CreateMapUnits(Project_Area, out_name)

    # Update message
    arcpy.AddMessage("Creating pre-defined map units of Wet Meadows")

    # Intersect the Map_Units layer with the NV Wet Meadows layer
    in_feature = ccsStandard.Wet_Meadows
    field_name = "Meadow"
    na_value = "No Meadow"
    ccslib.CreatePreDefinedMapUnits(Map_Units, in_feature, field_name,
                                    na_value)

    # Update message
    arcpy.AddMessage("Creating pre-defined map units of PJ")

    # Intersect the Map_Units layer with the Phase III PJ layer
    in_feature = ccsStandard.PJ_Phase_III
    field_name = "Conifer_Phase"
    ccslib.CreatePreDefinedMapUnits(Map_Units, in_feature, field_name)

    # Update message
    arcpy.AddMessage("Creating pre-defined map units of proposed surface "
                     "disturbance")

    # Intersect the Map_Units layer with the proposed surface disturbance
    in_features = ELIGIBLE_PROPOSED_FEATURES
    ccslib.CreatePreDefinedMapUnits(Map_Units, in_features, field_name)

    # Remove unwanted fields from Map Units feature class
    allowable_fields = [
        "Disturbance_Type", "BROTEC", "Conifer_Phase", "Meadow"
    ]
    ccslib.SimplifyFields(Map_Units, allowable_fields)

    # Populate empty attributes with Indirect
    feature = Map_Units
    fieldName = "Disturbance_Type"
    where_clause = "{} = ''".format(
        arcpy.AddFieldDelimiters(feature, fieldName))
    with arcpy.da.UpdateCursor(feature, fieldName, where_clause) as cursor:
        for row in cursor:
            row[0] = "Indirect"
            cursor.updateRow(row)

    # Add Map_Units to map
    layerFile = ccsStandard.getLayerFile("Map_Units.lyr")
    ccslib.AddToMap(Map_Units, layerFile)

    # Add fields Map_Unit_ID, Map_Unit_Name, and Precip to map unit
    input_feature = Map_Units
    fields = ["Map_Unit_ID", "Map_Unit_Name", "Notes"]
    fieldTypes = ["SHORT", "TEXT", "TEXT"]
    ccslib.AddFields(input_feature, fields, fieldTypes, copy_existing=True)

    # Add Domains to Map_Units layer
    # Create Domain for Map_Unit_ID attributes
    input_feature = Map_Units
    domainName = "Map_Unit_ID"
    range_low = 0
    range_high = 10000
    ccslib.AddRangeDomain(input_feature, workspace, domainName, range_low,
                          range_high)

    # Create Domain for Meadow attributes
    featureList = [Map_Units]
    domainName = "Meadow"
    codeList = ["Altered", "Unaltered", "No Meadow"]
    ccslib.AddCodedTextDomain(featureList, workspace, domainName, codeList)

    # Clean up
    arcpy.Delete_management("in_memory")

    # Save map document and exit
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #15
0
def main():
    # GET PARAMETER VALUES
    Map_Units_Provided = arcpy.GetParameterAsText(0)  # optional
    Proposed_Modified_Features_Provided = arcpy.GetParameterAsText(
        1)  # optional
    Project_Name = arcpy.GetParameterAsText(2)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Construct pathname to workspace
    if Map_Units_Provided:
        projectGDB = arcpy.Describe(Map_Units_Provided).path
    elif Proposed_Modified_Features_Provided:
        projectGDB = arcpy.Describe(Proposed_Modified_Features_Provided).path
    else:
        arcpy.AddMessage("Please provide either a Map_Units or " +
                         "Proposed_Modified_Features layer.")
        sys.exit(0)
    arcpy.AddMessage("Project geodatabase: " + projectGDB)
    Project_Folder = arcpy.Describe(projectGDB).path
    arcpy.AddMessage("Project folder:" + Project_Folder)

    # Instantiate a cheStandard object
    cheStandard = cohqt.cheStandard(projectGDB, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = projectGDB
    scratch_folder = os.path.join(arcpy.Describe(projectGDB).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(
            arcpy.Describe(projectGDB).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    Parameter_Values = cheStandard.ParameterValues
    ConiferModifier = cheStandard.ConiferModifier
    GrSG_LDI = cheStandard.GrSG_LDI
    LekPresenceRaster = cheStandard.LekPresenceRaster
    Lek_Distance_Modifier = cheStandard.LekDistanceModifier
    SageModifier = cheStandard.SageModifier
    GrSG_Habitat = cheStandard.GrSGHabitatRaster
    MigrationModifier = cheStandard.MuleDeerMigrationMod
    WinterModifier = cheStandard.MuleDeerWinterMod
    SummerModifier = cheStandard.MuleDeerSummerMod
    MuleDeer_LDI = cheStandard.MuleDeerLDI
    emptyRaster = cheStandard.EmptyRaster
    BWMD_Open = cheStandard.BWMD_Open
    GrSG_Range = cheStandard.GrSGHabitat
    Mule_Range = cheStandard.MuleDeerHabitat
    cellSize = arcpy.GetRasterProperties_management(emptyRaster,
                                                    "CELLSIZEX").getOutput(0)

    # Filenames for feature classes or rasters used by this script
    MAP_UNITS = "Map_Units"
    PROPOSED_MODIFIED_FEATURES = "Proposed_Modified_Features"
    CREDIT_PROJECT_AREA = "Credit_Project_Area"
    CONIFER_TREATMENT_AREA = "Conifer_Treatment_Area"

    # Filenames for feature class and rasters created by this script
    INDIRECT_IMPACT_AREA = "Indirect_Impact_Area"
    ANALYSIS_AREA = "Analysis_Area"
    MAP_UNITS_DISSOLVE = "Map_Units_Dissolve"
    # GrSG Filenames
    CURRENT_ANTHRO_DISTURBANCE = "GRSG_Pre_Anthro_Disturbance"
    PROJECTED_ANTHRO_DISTURBANCE = "GRSG_Post_Anthro_Disturbance"
    GRSG_PRE_BREEDING = "GRSG_Pre_Breeding"
    GRSG_PRE_SUMMER = "GRSG_Pre_Summer"
    GRSG_PRE_WINTER = "GRSG_Pre_Winter"
    GRSG_POST_BREEDING = "GRSG_Post_Breeding"
    GRSG_POST_SUMMER = "GRSG_Post_Summer"
    GRSG_POST_WINTER = "GRSG_Post_Winter"
    POST_CONIFER_MODIFIER = "Post_Conifer_Modifier"
    # Mule Deer Filenames
    CURRENT_ANTHRO_DISTURBANCE_MD = "MuleDeer_Pre_Anthro_Disturbance"
    PROJECTED_ANTHRO_DISTURBANCE_MD = "MuleDeer_Post_Anthro_Disturbance"
    MULE_PRE_SUMMER = "MuleDeer_Pre_Summer"
    MULE_PRE_MIGRATION = "MuleDeer_Pre_Migration"
    MULE_PRE_WINTER = "MuleDeer_Pre_Winter"
    MULE_POST_SUMMER = "MuleDeer_Post_Summer"
    MULE_POST_MIGRATION = "MuleDeer_Post_Migration"
    MULE_POST_WINTER = "MuleDeer_Post_Winter"

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

    # FUNCTION CALLS
    # Check out Spatial Analyst extension
    hqtlib.CheckOutSpatialAnalyst()

    # Check provided layers
    if not Map_Units_Provided and not Proposed_Modified_Features_Provided:
        arcpy.AddError("ERROR:: Please provide a 'Map_Units' and/or "
                       "'Proposed_Modified_Features' feature.")
        sys.exit(0)

    if not Proposed_Modified_Features_Provided:
        # Ensure Proposed_Modified_Features does not exist
        if arcpy.Exists("Proposed_Modified_Features"):
            arcpy.AddError("ERROR:: A 'Proposed_Modified_Features' layer "
                           "was detected in the project's geodatabase. "
                           "Provide the 'Proposed_Modified_Features' layer "
                           "and re-run Credit Tool 2.")
            sys.exit(0)

    if Map_Units_Provided:
        # Clear selection, if present
        util.ClearSelectedFeatures(Map_Units_Provided)

        # Check provided layer
        feature = Map_Units_Provided
        required_fields = ["Map_Unit_ID", "Map_Unit_Name"]
        no_null_fields = ["Map_Unit_ID"]
        expected_fcs = [CREDIT_PROJECT_AREA]
        hqtlib.CheckPolygonInput(feature, required_fields, expected_fcs,
                                 no_null_fields)

        # Update Map Units layer with provided layer
        provided_input = Map_Units_Provided
        parameter_name = MAP_UNITS
        preserve_existing = False
        Map_Units = util.AdoptParameter(provided_input, parameter_name,
                                        preserve_existing)

        # Add Map Units layer to map
        layerFile = cheStandard.getLayerFile("MapUnits.lyr")
        util.AddToMap(Map_Units, layerFile)

        # Provide location of Credit Project Area
        Credit_Project_Area = CREDIT_PROJECT_AREA

    if Proposed_Modified_Features_Provided:
        # Clear selection, if present
        util.ClearSelectedFeatures(Proposed_Modified_Features_Provided)

        # Check provided layer
        required_fields = ["Type", "Subtype"]
        no_null_fields = required_fields
        expected_fcs = None
        hqtlib.CheckPolygonInput(Proposed_Modified_Features_Provided,
                                 required_fields, expected_fcs, no_null_fields)

        # Update Proposed_Modified_Features with provided layer
        provided_input = Proposed_Modified_Features_Provided
        parameterName = PROPOSED_MODIFIED_FEATURES
        preserve_existing = False
        Proposed_Modified_Features = util.AdoptParameter(
            provided_input, parameterName, preserve_existing)

        # Add Proposed Modified Features layer to map
        layerFile = cheStandard.getLayerFile("DebitProjectArea.lyr")
        util.AddToMap(Proposed_Modified_Features, layerFile)

        # Update message
        arcpy.AddMessage("Creating the area of indirect benefit")

        # Create Credit_Project_Area for projects that propose to modify
        # anthropogenic features
        # Create the Indirect_Impact_Area
        in_data = Proposed_Modified_Features
        out_name = INDIRECT_IMPACT_AREA
        Indirect_Impact_Area = hqtlib.CreateIndirectImpactArea(
            in_data, Parameter_Values, out_name)

        # Add field "Indirect"
        input_feature = Indirect_Impact_Area
        fieldsToAdd = ["Indirect"]
        fieldTypes = ["TEXT"]
        util.AddFields(input_feature, fieldsToAdd, fieldTypes)

        # Update field 'Indirect' to equal 'True'
        with arcpy.da.UpdateCursor(Indirect_Impact_Area,
                                   fieldsToAdd) as cursor:
            for row in cursor:
                row[0] = "True"
                cursor.updateRow(row)

        if Map_Units_Provided:
            # Merge with Credit_Project_Boundary
            fileList = [Map_Units_Provided, Indirect_Impact_Area]
            out_name = "in_memory/Credit_Project_Boundary"
            Project_Area = arcpy.Union_analysis(fileList, out_name)
        else:
            Project_Area = Indirect_Impact_Area

        # Eliminate areas of non-habitat to create Credit_Project_Area
        out_name = CREDIT_PROJECT_AREA
        habitat_bounds = cheStandard.HabitatMgmtArea
        Credit_Project_Area = hqtlib.EliminateNonHabitat(
            Project_Area, out_name, habitat_bounds)

    # Detect habitat types impacted directly or indirectly
    is_grsg = cohqt.DetectHabitat(Credit_Project_Area, GrSG_Range)
    is_mule = cohqt.DetectHabitat(Credit_Project_Area, Mule_Range)

    # Update message
    arcpy.AddMessage("Dissolving all multi-part map units to create "
                     "Map_Units_Dissolve")

    # Dissolve Map Units
    in_features = MAP_UNITS
    allowable_fields = ["Map_Unit_ID", "Map_Unit_Name", "Indirect"]
    out_name = MAP_UNITS_DISSOLVE
    anthro_features = None
    Map_Units_Dissolve = hqtlib.DissolveMapUnits(in_features, allowable_fields,
                                                 out_name, anthro_features)

    # Update message
    arcpy.AddMessage("Adding Map_Units_Dissolve to map")

    # Add layer to map document
    feature = Map_Units_Dissolve
    layerFile = cheStandard.getLayerFile("MapUnits.lyr")
    util.AddToMap(feature, layerFile, zoom_to=True)

    # Update message
    arcpy.AddMessage("Calculating area in acres for each map unit")

    # Calculate Area
    hqtlib.CalcAcres(Map_Units_Dissolve)

    # Update message
    arcpy.AddMessage("Adding transect field to Map Units Dissolve")

    # Add transects field to map units table
    fields = ["Transects"]
    fieldTypes = ["SHORT"]
    util.AddFields(Map_Units_Dissolve, fields, fieldTypes)

    # Update message
    arcpy.AddMessage("Creating Analysis Area")

    # Create Analysis Area
    out_name = ANALYSIS_AREA
    Analysis_Area = hqtlib.CreateAnalysisArea(Credit_Project_Area,
                                              Parameter_Values, out_name)

    # Add Analysis_Area to map
    layerFile = cheStandard.getLayerFile("AnalysisArea.lyr")
    util.AddToMap(Analysis_Area, layerFile, zoom_to=True)

    # Set processing extent to Analysis_Area
    arcpy.env.extent = ANALYSIS_AREA

    ### GREATER SAGE-GROUSE ANTHRO DIST & MODIFIERS ###
    if is_grsg:

        # Update message
        arcpy.AddMessage("Calculating proportion of each map unit within 1 km "
                         "of a lek")

        # Calculate proportion of map unit within 1 km of a lek
        inZoneData = Map_Units_Dissolve
        inValueRaster = cheStandard.LekPresenceRaster
        zoneField = "Map_Unit_ID"
        outTable = "Proportion_Lek"
        hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

        # Join the zonal statistic to the Map Units Dissolve table
        field_name = "PropLek"
        hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, field_name)

        # Update message
        arcpy.AddMessage(
            "Calculating proportion of each map unit in the mesic "
            "precip zone")

        # Calculate Proportion of each map unit in the mesic precip zone
        inZoneData = Map_Units_Dissolve
        inValueRaster = cheStandard.Precip
        zoneField = "Map_Unit_ID"
        outTable = "Proportion_Mesic"
        hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

        # Join the zonal statistic to the Map Units Dissolve table
        field_name = "PropMesic"
        hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, field_name)

        # Update message
        arcpy.AddMessage("Calculating pre-project anthropogenic "
                         "disturbance modifier for greater sage-grouse")

        # Calculate Current_Anthro_Disturbance
        dist_field = "GrSG_Dist"
        weight_field = "GrSG_Weight"
        term = cheStandard.CreditTerms[0]
        unique_proposed_subtypes = []
        anthro_disturbance_type = "Pre"

        Current_Anthro_Disturbance = cohqt.CalcAnthroDisturbance(
            Parameter_Values, term, unique_proposed_subtypes,
            anthro_disturbance_type, cheStandard, dist_field, weight_field,
            cellSize, emptyRaster)
        Current_Anthro_Disturbance.save(CURRENT_ANTHRO_DISTURBANCE)

        # Update message
        arcpy.AddMessage("Current_Anthro_Disturbance Calculated")
        arcpy.AddMessage("Calculating Pre-Project Habitat Modifiers for"
                         "Greater Sage-Grouse")

        # Calculate pre-project cumulative habitat modifiers
        winterHabitatPre = cohqt.calcWinterHabitatGRSG(
            Current_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
            GrSG_Habitat)
        LSDMWinterPre = cohqt.applyLekUpliftModifierPre(
            winterHabitatPre, LekPresenceRaster)
        breedingHabitatPre = cohqt.calcBreedingHabitatGRSG(
            Current_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
            Lek_Distance_Modifier, GrSG_Habitat)
        LSDMBreedingPre = cohqt.applyLekUpliftModifierPre(
            breedingHabitatPre, LekPresenceRaster)
        summerHabitatPre = cohqt.calcSummerHabitatGRSG(
            Current_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
            SageModifier, GrSG_Habitat)
        LSDMSummerPre = cohqt.applyLekUpliftModifierPre(
            summerHabitatPre, LekPresenceRaster)
        seasonalHabitatRasters = [
            LSDMWinterPre, LSDMBreedingPre, LSDMSummerPre
        ]

        # Save outputs
        # winterHabitatPre.save(GRSG_PRE_WINTER)
        LSDMWinterPre.save(GRSG_PRE_WINTER)
        # breedingHabitatPre.save(GRSG_PRE_BREEDING)
        LSDMBreedingPre.save(GRSG_PRE_BREEDING)
        # summerHabitatPre.save(GRSG_PRE_SUMMER)
        LSDMSummerPre.save(GRSG_PRE_SUMMER)

        # Initialize list of uplift rasters to combine for LekUpliftModifier
        upliftRasters = []
        if arcpy.Exists(CONIFER_TREATMENT_AREA):
            # Calculate post-project conifer modifier
            Conifer_Cover = cheStandard.ConiferCover
            coniferModifierPost = cohqt.calcConiferPost(
                CONIFER_TREATMENT_AREA, Conifer_Cover)
            coniferModifierPost.save(POST_CONIFER_MODIFIER)

            # Calculate uplift from conifer removal
            coniferUplift = cohqt.calcUplift(ConiferModifier,
                                             coniferModifierPost)
            upliftRasters.append(coniferUplift)

        else:
            coniferModifierPost = ConiferModifier

        if arcpy.Exists(PROPOSED_MODIFIED_FEATURES):
            # Prepare proposed anthropogenic features
            unique_proposed_subtypes = cohqt.convertProposedToRasterCredit(
                PROPOSED_MODIFIED_FEATURES, cellSize)

            anthroPath = cheStandard.AnthroFeaturePath
            cohqt.combineProposedWithCurrentCredit(anthroPath,
                                                   unique_proposed_subtypes)

            # Update message
            arcpy.AddMessage("Calculating post-project anthropogenic "
                             "disturbance modifier for greater sage-grouse")

            # Calculate post-project anthropogenic disturbance
            term = cheStandard.CreditTerms[1]
            anthro_disturbance_type = "Post"

            Projected_Anthro_Disturbance = cohqt.CalcAnthroDisturbance(
                Parameter_Values, term, unique_proposed_subtypes,
                anthro_disturbance_type, cheStandard, dist_field, weight_field,
                cellSize, emptyRaster)

            Projected_Anthro_Disturbance.save(PROJECTED_ANTHRO_DISTURBANCE)

            # Update message
            arcpy.AddMessage("Projected_Anthro_Disturbance Calculated")

            # Calculate uplift from anthro feature removal
            anthroUplift = cohqt.calcUplift(Current_Anthro_Disturbance,
                                            Projected_Anthro_Disturbance)
            upliftRasters.append(anthroUplift)

            # Update message
            arcpy.AddMessage(
                "Merging indirect benefits area and map units layer")

            # Combine the Map Units layer and Indirect Impact Layer
            indirect_benefit_area = CREDIT_PROJECT_AREA
            mgmt_map_units = Map_Units_Dissolve
            Map_Units_Dissolve = hqtlib.AddIndirectBenefitArea(
                indirect_benefit_area, mgmt_map_units)

        else:
            Projected_Anthro_Disturbance = Current_Anthro_Disturbance

            # Add Indirect field to Map Units layer and populate with False
            # Add field "Indirect"
            feature = Map_Units_Dissolve
            fieldsToAdd = ["Indirect"]
            fieldTypes = ["TEXT"]
            util.AddFields(feature, fieldsToAdd, fieldTypes)

            # Update field to equal "False"
            with arcpy.da.UpdateCursor(feature, fieldsToAdd) as cursor:
                for row in cursor:
                    row[0] = "False"
                    cursor.updateRow(row)

        # Calc zonal stats for pre-project modifiers (three seasons)
        term = cheStandard.CreditTerms[0]
        for season, raster in zip(cheStandard.GrSGSeasons,
                                  seasonalHabitatRasters):
            # Update message
            arcpy.AddMessage("Summarizing GrSG " + term + " " + season)

            # Calculate zonal statistics for each map unit
            inZoneData = Map_Units_Dissolve
            inValueRaster = raster
            zoneField = "Map_Unit_ID"
            outTable = "GrSG_Stats_" + term + "_" + season
            hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                  outTable)

            # Join the zonal statistic to the Map Units Dissolve table
            field_name = "GrSG_" + term + "_" + season
            hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, field_name)

        if arcpy.Exists("Conifer_Treatment_Area") or \
                arcpy.Exists("Anthro_Features_Removed"):

            # Update message
            arcpy.AddMessage("Calculating Lek Uplift Modifier")

            # Calculate Lek Uplift Modifier
            lekUpliftModifier = cohqt.calcLekUpliftModifier(
                LekPresenceRaster, upliftRasters)
            lekUpliftModifier.save("Lek_Uplift_Modifier")

            # Update message
            arcpy.AddMessage("Calculating Post-Project Habitat Modifiers")

            # Calculate post-project cumulative habtiat modifiers
            winterHabitatPost = cohqt.calcWinterHabitatGRSG(
                Projected_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
                GrSG_Habitat)
            LSDMWinterPost = cohqt.applyLekUpliftModifierPost(
                winterHabitatPost, LekPresenceRaster, lekUpliftModifier)
            breedingHabitatPost = cohqt.calcBreedingHabitatGRSG(
                Projected_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
                Lek_Distance_Modifier, GrSG_Habitat)
            LSDMBreedingPost = cohqt.applyLekUpliftModifierPost(
                breedingHabitatPost, LekPresenceRaster, lekUpliftModifier)
            summerHabitatPost = cohqt.calcSummerHabitatGRSG(
                Projected_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
                SageModifier, GrSG_Habitat)
            LSDMSummerPost = cohqt.applyLekUpliftModifierPost(
                summerHabitatPost, LekPresenceRaster, lekUpliftModifier)

            seasonalHabitatRasters = [
                LSDMWinterPost, LSDMBreedingPost, LSDMSummerPost
            ]

            # Save outputs
            # winterHabitatPost.save("Post_Seasonal_Winter")
            LSDMWinterPost.save(GRSG_POST_WINTER)
            # breedingHabitatPost.save("Post_Seasonal_Breeding")
            LSDMBreedingPost.save(GRSG_POST_BREEDING)
            # summerHabitatPost.save("Post_Seasonal_Summer")
            LSDMSummerPost.save(GRSG_POST_SUMMER)

            # Calc zonal stats for post-project modifiers
            term = cheStandard.CreditTerms[1]
            for season, raster in zip(cheStandard.GrSGSeasons,
                                      seasonalHabitatRasters):
                # Update message
                arcpy.AddMessage("Summarizing GrSG " + term + " " + season)

                # Calculate zonal statistics for each map unit
                inZoneData = Map_Units_Dissolve
                inValueRaster = raster
                zoneField = "Map_Unit_ID"
                outTable = "GrSG_Stats_" + term + "_" + season
                hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                      outTable)

                # Join the zonal statistic to the Map Units Dissolve table
                field_name = "GrSG_" + term + "_" + season
                hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField,
                                       field_name)

        # Calculate Credit Intensity

    ### END GREATER SAGE-GROUSE ###

    ### MULE DEER ANTHRO DIST & MODIFIERS ###
    if is_mule:
        # Update message
        arcpy.AddMessage("Calculating pre-project anthropogenic disturbance "
                         "modifier for mule deer - process may repeat for "
                         "habitats in mixed PJ and open habitat")

        # # Calculat pre-project anthropogenic disturbance
        # dist_field = "MDO_Dist"
        # weight_field = "MDO_Weight"
        # term = cheStandard.CreditTerms[0]
        # unique_proposed_subtypes = []
        # anthro_disturbance_type = "Pre"
        #
        # Current_Anthro_Disturbance = hqtlib.cheCalcAnthroDisturbance(
        #     Parameter_Values, term, unique_proposed_subtypes,
        #     anthro_disturbance_type, cheStandard, dist_field, weight_field,
        #     cellSize, emptyRaster
        # )
        # Current_Anthro_Disturbance.save(CURRENT_ANTHRO_DISTURBANCE_MD)

        # Calculate pre-project anthropogenic disturbance
        # Calculate pre-project in PJ
        dist_field = "MDP_Dist"
        weight_field = "MDP_Weight"
        term = cheStandard.CreditTerms[0]
        unique_proposed_subtypes = []
        anthro_disturbance_type = "Pre"

        anthro_pj = cohqt.CalcAnthroDisturbance(Parameter_Values, term,
                                                unique_proposed_subtypes,
                                                anthro_disturbance_type,
                                                cheStandard, dist_field,
                                                weight_field, cellSize,
                                                emptyRaster)
        anthro_pj.save(CURRENT_ANTHRO_DISTURBANCE_MD + "_P")

        # Calculate pre-project in Open
        dist_field = "MDO_Dist"
        weight_field = "MDO_Weight"
        term = cheStandard.CreditTerms[0]
        unique_proposed_subtypes = []
        anthro_disturbance_type = "Pre"

        anthro_open = cohqt.CalcAnthroDisturbance(Parameter_Values,
                                                  term,
                                                  unique_proposed_subtypes,
                                                  anthro_disturbance_type,
                                                  cheStandard,
                                                  dist_field,
                                                  weight_field,
                                                  cellSize,
                                                  emptyRaster,
                                                  mask=BWMD_Open)
        anthro_open.save(CURRENT_ANTHRO_DISTURBANCE_MD + "_O")

        # Combine PJ and Open
        # If outside open, make 1
        anthro_open_only = Con(BWMD_Open == 1, anthro_open, 1)
        anthro_open_only.save(CURRENT_ANTHRO_DISTURBANCE_MD + "_OO")

        # Select minimum of pj and open rasters
        Current_Anthro_Disturbance = Con(anthro_open_only < anthro_pj,
                                         anthro_open_only, anthro_pj)
        Current_Anthro_Disturbance.save(CURRENT_ANTHRO_DISTURBANCE_MD)

        # Clean up
        arcpy.Delete_management("temp_masked_raster")
        # arcpy.Delete_management(CURRENT_ANTHRO_DISTURBANCE_MD + "_P")
        # arcpy.Delete_management(CURRENT_ANTHRO_DISTURBANCE_MD + "_O")
        # arcpy.Delete_management(CURRENT_ANTHRO_DISTURBANCE_MD + "_OO")

        # Update message
        arcpy.AddMessage("Calculating Pre-Project Habitat Modifiers")

        # Calculate pre-project cumulative habitat modifiers
        summerHabitatPre = cohqt.calcSummerHabitatMD(
            Current_Anthro_Disturbance,
            MuleDeer_LDI,
            SummerModifier,
            SuitableHabitat=None)
        # LSDMWinterPre = cohqt.applyLekUpliftModifierPre(summerHabitatPre,
        #                                                  LekPresenceRaster)
        migratoryHabitatPre = cohqt.calcMigratoryHabitatMD(
            Current_Anthro_Disturbance,
            MuleDeer_LDI,
            MigrationModifier,
            SuitableHabitat=None)
        # LSDMBreedingPre = cohqt.applyLekUpliftModifierPre(migratoryHabitatPre,
        #                                                    LekPresenceRaster)
        winterHabitatPre = cohqt.calcWinterHabitatMD(
            Current_Anthro_Disturbance,
            MuleDeer_LDI,
            WinterModifier,
            SuitableHabitat=None)
        # LSDMSummerPre = cohqt.applyLekUpliftModifierPre(winterHabitatPre,
        #                                                  LekPresenceRaster)
        seasonalHabitatRasters = [
            summerHabitatPre, migratoryHabitatPre, winterHabitatPre
        ]

        # Save outputs
        summerHabitatPre.save(MULE_PRE_SUMMER)
        # LSDMWinterPre.save("Pre_LSDM_Winter")
        migratoryHabitatPre.save(MULE_PRE_MIGRATION)
        # LSDMBreedingPre.save("Pre_LSDM_Breeding")
        winterHabitatPre.save(MULE_PRE_WINTER)
        # LSDMSummerPre.save("Pre_LSDM_Summer")

        # Update message
        arcpy.AddMessage("Current_Anthro_Disturbance Calculated")

        # Calc zonal stats for pre-project modifiers (three seasons)
        term = cheStandard.DebitTerms[0]
        for season, raster in zip(cheStandard.MuleDeerSeasons,
                                  seasonalHabitatRasters):
            # Update message
            arcpy.AddMessage("Summarizing Mule Deer " + term + " " + season)

            # Calculate zonal statistics for each map unit
            inZoneData = Map_Units_Dissolve
            inValueRaster = raster
            zoneField = "Map_Unit_ID"
            outTable = "Mule_Stats_" + term + "_" + season
            hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                  outTable)

            # Join the zonal statistic to the Map Units Dissolve table
            field_name = "Mule_" + term + "_" + season
            hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, field_name)

        # # Calculate average of three seasonal habitat rasters pre-project
        # finalPreCumulative = hqtlib.calcAverageHabitatQuality(
        #     seasonalHabitatRasters
        # )
        # finalPreCumulative.save(CUMULATIVE_MODIFIER_PRE)

        if arcpy.Exists(PROPOSED_MODIFIED_FEATURES):
            # Update message
            arcpy.AddMessage("Calculating post-project anthropogenic "
                             "disturbance modifier")

            # Calculate post-project anthropogenic disturbance
            term = cheStandard.CreditTerms[1]
            anthro_disturbance_type = "Post"

            Projected_Anthro_Disturbance = cohqt.CalcAnthroDisturbance(
                Parameter_Values, term, unique_proposed_subtypes,
                anthro_disturbance_type, cheStandard, dist_field, weight_field,
                cellSize, emptyRaster)

            Projected_Anthro_Disturbance.save(PROJECTED_ANTHRO_DISTURBANCE_MD)

            # Update message
            arcpy.AddMessage("Projected_Anthro_Disturbance Calculated")

            # Calculate post-project cumulative habitat modifiers
            summerHabitatPost = cohqt.calcSummerHabitatMD(
                Projected_Anthro_Disturbance,
                MuleDeer_LDI,
                SummerModifier,
                SuitableHabitat=None)
            # LSDMWinterPost = cohqt.applyLekUpliftModifierPost(summerHabitatPost,
            #                                                  LekPresenceRaster)
            migratoryHabitatPost = cohqt.calcMigratoryHabitatMD(
                Projected_Anthro_Disturbance,
                MuleDeer_LDI,
                MigrationModifier,
                SuitableHabitat=None)
            # LSDMBreedingPost = cohqt.applyLekUpliftModifierPost(migratoryHabitatPost,
            #                                                    LekPresenceRaster)
            winterHabitatPost = cohqt.calcWinterHabitatMD(
                Projected_Anthro_Disturbance,
                MuleDeer_LDI,
                WinterModifier,
                SuitableHabitat=None)
            # LSDMSummerPost = cohqt.applyLekUpliftModifierPost(winterHabitatPost,
            #                                                  LekPresenceRaster)
            seasonalHabitatRasters = [
                summerHabitatPost, migratoryHabitatPost, winterHabitatPost
            ]

            # Save outputs
            summerHabitatPost.save(MULE_POST_SUMMER)
            # LSDMWinterPre.save("Pre_LSDM_Winter")
            migratoryHabitatPost.save(MULE_POST_MIGRATION)
            # LSDMBreedingPre.save("Pre_LSDM_Breeding")
            winterHabitatPost.save(MULE_POST_WINTER)
            # LSDMSummerPre.save("Pre_LSDM_Summer")

            # Calc zonal stats for pre-project modifiers (three seasons)
            term = cheStandard.DebitTerms[1]
            for season, raster in zip(cheStandard.MuleDeerSeasons,
                                      seasonalHabitatRasters):
                # Update message
                arcpy.AddMessage("Summarizing Mule Deer " + term + season)

                # Calculate zonal statistics for each map unit
                inZoneData = Map_Units_Dissolve
                inValueRaster = raster
                zoneField = "Map_Unit_ID"
                outTable = "Mule_Stats_" + term + season
                hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                      outTable)

                # Join the zonal statistic to the Map Units Dissolve table
                field_name = "Mule_" + term + "_" + season
                hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField,
                                       field_name)

            # # Calculate average of three seasonal habitat rasters post-project
            # finalPostCumulative = hqtlib.calcAverageHabitatQuality(
            #     seasonalHabitatRasters
            # )
            # finalPostCumulative.save(CUMULATIVE_MODIFIER_POST)

            # Calculate permanent cumulative habtiat modifiers

            # Update message
            arcpy.AddMessage("Calculating Mule Deer Benefit")

            # Calculate impact
            pre_fields = [
                "Mule_Pre_Summer", "Mule_Pre_Migration", "Mule_Pre_Winter"
            ]
            post_fields = [
                "Mule_Post_Summer", "Mule_Post_Migration", "Mule_Post_Winter"
            ]
            out_fields = [
                "Mule_Summer_Benefit", "Mule_Migration_Benefit",
                "Mule_Winter_Benefit"
            ]
            for i in range(len(pre_fields)):
                pre_field = pre_fields[i]
                post_field = post_fields[i]
                out_field = out_fields[i]
                cohqt.calcDebits(Map_Units_Dissolve, pre_field, post_field,
                                 out_field)

        # # Export data to Excel
        input_Tables = [MAP_UNITS_DISSOLVE]
        for table in input_Tables:
            hqtlib.ExportToExcel(table, Project_Folder, Project_Name)

    ### END MULE DEER ###
    if not is_grsg and not is_mule:
        arcpy.AddMessage("Impacts were not detected in any habitat type. "
                         "Please check credit project boundary and try "
                         "again")
    # Clean up
    for raster in arcpy.ListRasters("*_Subtype_Disturbance"):
        arcpy.Delete_management(raster)

    for raster in arcpy.ListRasters("*_Type_Disturbance"):
        arcpy.Delete_management(raster)

    arcpy.Delete_management("in_memory")

    # Save map document
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #16
0
def main():
    # GET PARAMETER VALUES
    Map_Units_Provided = arcpy.GetParameterAsText(0)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Construct pathname to workspace
    projectGDB = arcpy.Describe(Map_Units_Provided).path
    arcpy.AddMessage("Project geodatabase: " + projectGDB)

    # Instantiate a idStandard object
    cheStandard = cohqt.cheStandard(projectGDB, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = projectGDB
    scratch_folder = os.path.join(arcpy.Describe(projectGDB).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(scratch_folder)
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    cell_size = 30
    inputDataPath = cheStandard.InputDataPath
    GrSG_Habitat = cheStandard.GrSGHabitatRaster
    ConiferModifier = cheStandard.ConiferModifier
    GrSG_LDI = cheStandard.GrSG_LDI
    LekPresenceRaster = cheStandard.LekPresenceRaster
    Lek_Distance_Modifier = cheStandard.LekDistanceModifier
    SageModifier = cheStandard.SageModifier
    GrSG_Habitat = cheStandard.BWSGHab

    # Filenames of feature classes and rasters used by this script
    MAP_UNITS = "Map_Units"
    PROPOSED_SURFACE_DISTURBANCE_DEBITS = "Proposed_Surface_Disturbance_Debits"
    DISTURBED_FOOTPRINT = "Disturbed_Footprint"
    CURRENT_ANTHRO_FEATURES = "Current_Anthro_Features"
    CURRENT_ANTHRO_DISTURBANCE = "GrSG_Pre_Anthro_Disturbance"
    PROJECTED_ANTHRO_DISTURBANCE = "GRSG_Post_Anthro_Disturbance"
    LEK_DISTURBANCE_MODIFIER = "Lek_Disturbance_Modifier"
    DEBIT_PROJECT_AREA = "Debit_Project_Area"
    DEBIT_PROJECT_IMPACT_A = "Debit_Project_Impact_Adjusted"

    # Filenames of feature classes and rasters created by this script
    # GrSG Filenames
    GRSG_PRE_BREEDING_A = "GRSG_Pre_Breeding_adjusted"
    GRSG_PRE_SUMMER_A = "GRSG_Pre_Summer_adjusted"
    GRSG_PRE_WINTER_A = "GRSG_Pre_Winter_adjusted"
    GRSG_POST_BREEDING_A = "GRSG_Post_Breeding_adjusted"
    GRSG_POST_SUMMER_A = "GRSG_Post_Summer_adjusted"
    GRSG_POST_WINTER_A = "GRSG_Post_Winter_adjusted"
    CUMULATIVE_MODIFIER_PRE_A = "GRSG_Pre_Cumulative_Modifier_adjusted"
    CUMULATIVE_MODIFIER_POST_A = "GRSG_Post_Cumulative_Modifier_adjusted"

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

    # FUNCTION CALLS
    # Check out Spatial Analyst extension
    hqtlib.CheckOutSpatialAnalyst()

    # Clear selection, if present
    util.ClearSelectedFeatures(Map_Units_Provided)

    # Check Map_Units layer
    feature = Map_Units_Provided
    required_fields = ["Map_Unit_ID", "Map_Unit_Name"]
    no_null_fields = ["Map_Unit_ID"]
    expected_fcs = None
    hqtlib.CheckPolygonInput(feature, required_fields, expected_fcs,
                             no_null_fields)

    # Update Map Units layer with provided layer and add to map
    Map_Units = util.AdoptParameter(Map_Units_Provided,
                                    MAP_UNITS,
                                    preserve_existing=False)
    layerFile = cheStandard.getLayerFile("MapUnits.lyr")
    util.AddToMap(Map_Units, layerFile)

    # # Udpate message
    # arcpy.AddMessage("Dissolving all multi-part map units to create "
    #                  "Map_Units_Dissolve")

    # # Dissolve Map Units
    # allowable_fields = ["Map_Unit_ID", "Map_Unit_Name", "Notes",
    #                     "Disturbance_Type", "Precip", ]
    # out_name = MAP_UNITS_DISSOLVE
    # anthro_features = CURRENT_ANTHRO_FEATURES
    # Map_Units_Dissolve = hqtlib.DissolveMapUnits(MUs, allowable_fields,
    #                                             out_name, anthro_features)

    # # Update message
    # arcpy.AddMessage("Adding Map_Units_Dissolve to map")

    # # Add layer to map document
    # feature = Map_Units_Dissolve
    # layerFile = cheStandard.getLayerFile("Map_Units.lyr")
    # util.AddToMap(feature, layerFile)

    # # Update message
    # arcpy.AddMessage("Calculating area in acres for each map unit")

    # # Calculate Area
    # hqtlib.CalcAcres(Map_Units_Dissolve)

    # Update message
    arcpy.AddMessage("Creating site-scale habitat quality rasters")

    # # ADD Join from Excel Doc
    # out_table = os.path.join(projectGDB, "Site_Scale_Scores")
    # summary_table = arcpy.ExcelToTable_conversion(Debit_Calculator,
    #                                               out_table,
    #                                               "Summary")

    # arcpy.AddJoin_management(Map_Units, "Map_Unit_ID",
    #                          summary_table, "MapUnitID")

    # Convert Map Units to raster of Habitat Quality (0 - 1 scale) and  mask
    # out BWSG habitat
    seasonsList = cheStandard.GrSGSeasons
    for season in seasonsList:
        mu_raster_path = cohqt.convertMapUnitsToRaster(projectGDB, Map_Units,
                                                       season, cell_size)
        mu_raster = Raster(mu_raster_path)
        # Mask out BWSG habitat
        SuitableHabitat_adjusted = Con(IsNull(Float(mu_raster)), GrSG_Habitat,
                                       Float(mu_raster))
        SuitableHabitat_adjusted.save(
            os.path.join(projectGDB, season + "_Habitat_adjusted"))

    # Update message
    arcpy.AddMessage("Calculating Pre-Project Habitat Modifiers")

    # Re-run fron calcWinterHabitat down with updated BWSG layer (append
    # "_adjusted")

    WinterSuitableHabitat = os.path.join(projectGDB, "Winter_Habitat_adjusted")
    winterHabitatPre = cohqt.calcWinterHabitatGRSG(CURRENT_ANTHRO_DISTURBANCE,
                                                   ConiferModifier, GrSG_LDI,
                                                   WinterSuitableHabitat)
    LSDMWinterPre = cohqt.applyLekUpliftModifierPre(winterHabitatPre,
                                                    LekPresenceRaster)

    BreedingSuitableHabitat = os.path.join(projectGDB,
                                           "Breed_Habitat_adjusted")
    breedingHabitatPre = cohqt.calcBreedingHabitatGRSG(
        CURRENT_ANTHRO_DISTURBANCE, ConiferModifier, GrSG_LDI,
        Lek_Distance_Modifier, BreedingSuitableHabitat)
    LSDMBreedingPre = cohqt.applyLekUpliftModifierPre(breedingHabitatPre,
                                                      LekPresenceRaster)

    SummerSuitableHabitat = os.path.join(projectGDB, "Summer_Habitat_adjusted")
    summerHabitatPre = cohqt.calcSummerHabitatGRSG(CURRENT_ANTHRO_DISTURBANCE,
                                                   ConiferModifier, GrSG_LDI,
                                                   SageModifier,
                                                   SummerSuitableHabitat)
    LSDMSummerPre = cohqt.applyLekUpliftModifierPre(summerHabitatPre,
                                                    LekPresenceRaster)

    seasonalHabitatRasters = [LSDMWinterPre, LSDMBreedingPre, LSDMSummerPre]

    # Save outputs
    # winterHabitatPre.save("Pre_Seasonal_Winter_adjusted")
    LSDMWinterPre.save(GRSG_PRE_WINTER_A)
    # breedingHabitatPre.save("Pre_Seasonal_Breeding_adjusted")
    LSDMBreedingPre.save(GRSG_PRE_BREEDING_A)
    # summerHabitatPre.save("Pre_Seasonal_Summer_adjusted")
    LSDMSummerPre.save(GRSG_PRE_SUMMER_A)

    # Calculate average of three seasonal habitat rasters pre-project
    finalPreCumulative = cohqt.calcAverageHabitatQuality(
        seasonalHabitatRasters)
    finalPreCumulative.save(CUMULATIVE_MODIFIER_PRE_A)

    # Calculate post-project cumulative habtiat modifiers
    winterHabitatPost = cohqt.calcWinterHabitatGRSG(
        PROJECTED_ANTHRO_DISTURBANCE, ConiferModifier, GrSG_LDI,
        WinterSuitableHabitat)
    LSDMWinterPost = cohqt.applyLekUpliftModifierPost(
        winterHabitatPost, LekPresenceRaster, LEK_DISTURBANCE_MODIFIER)
    breedingHabitatPost = cohqt.calcBreedingHabitatGRSG(
        PROJECTED_ANTHRO_DISTURBANCE, ConiferModifier, GrSG_LDI,
        Lek_Distance_Modifier, BreedingSuitableHabitat)
    LSDMBreedingPost = cohqt.applyLekUpliftModifierPost(
        breedingHabitatPost, LekPresenceRaster, LEK_DISTURBANCE_MODIFIER)
    summerHabitatPost = cohqt.calcSummerHabitatGRSG(
        PROJECTED_ANTHRO_DISTURBANCE, ConiferModifier, GrSG_LDI, SageModifier,
        SummerSuitableHabitat)
    LSDMSummerPost = cohqt.applyLekUpliftModifierPost(
        summerHabitatPost, LekPresenceRaster, LEK_DISTURBANCE_MODIFIER)

    seasonalHabitatRasters = [LSDMWinterPost, LSDMBreedingPost, LSDMSummerPost]

    # Save outputs
    # winterHabitatPost.save("Post_Seasonal_Winter")
    LSDMWinterPost.save(GRSG_POST_WINTER_A)
    # breedingHabitatPost.save("Post_Seasonal_Breeding")
    LSDMBreedingPost.save(GRSG_POST_BREEDING_A)
    # summerHabitatPost.save("Post_Seasonal_Summer")
    LSDMSummerPost.save(GRSG_POST_SUMMER_A)

    # Calculate average of three seasonal habitat rasters post-project
    finalPostCumulative = cohqt.calcAverageHabitatQuality(
        seasonalHabitatRasters)
    finalPostCumulative.save(CUMULATIVE_MODIFIER_POST_A)

    # Calculate Zonal Statistics for cumulative modifier rasters
    # Calculate zonal statistics for pre-project
    inZoneData = DEBIT_PROJECT_AREA
    inValueRaster = finalPreCumulative
    zoneField = "ZONAL"
    outTable = "GRSG_Stats_Pre_adjusted"
    hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

    # Join the zonal statistic to the Debit Project Area table
    fieldName = "GRSG_Pre_Project_A"
    hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

    # Calculate zonal statistics for post-project
    inZoneData = DEBIT_PROJECT_AREA
    inValueRaster = finalPostCumulative
    zoneField = "ZONAL"
    outTable = "GRSG_Stats_Post_adjusted"
    hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

    # Join the zonal statistic to the Debit Project Area table
    fieldName = "GrSG_Post_Project_A"
    hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

    # Calculate debits using field data
    cohqt.calcDebits(DEBIT_PROJECT_AREA, "GRSG_Pre_Project_A",
                     "GrSG_Post_Project_A", "Debits_adj")

    # Update message
    arcpy.AddMessage("Creating visualization of impact from debit project")

    # Calculate impact intensity for debit project
    debit_impact = cohqt.calcImpact(finalPreCumulative, finalPostCumulative)
    debit_impact.save(DEBIT_PROJECT_IMPACT_A)

    # Add Debit Impact raster to map and save map document
    feature = debit_impact
    layerFile = cheStandard.getLayerFile("DebitProjectImpact.lyr")
    util.AddToMap(feature, layerFile, zoom_to=True)

    # Clean up
    arcpy.Delete_management("in_memory")

    # Save map document
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #17
0
def main():
    # GET PARAMETER VALUES
    Analysis_Area = arcpy.GetParameterAsText(0)
    Dist_Lek = arcpy.GetParameterAsText(1)
    Current_Anthro_Features_Provided = arcpy.GetParameterAsText(2)  # optional
    Project_Folder = arcpy.GetParameterAsText(3)
    Project_Name = arcpy.GetParameterAsText(4)  # optional

    # DEFINE DIRECTORIES & PATH NAMES FOR FOLDERS & GBDs
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    # Construct pathname to workspace
    workspace = arcpy.Describe(Analysis_Area).path
    arcpy.AddMessage("Project geodatabase: " + workspace)
    # Instantiate a ccsStandard object
    ccsStandard = ccslib.ccsStandard(workspace, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    scratch_folder = os.path.join(arcpy.Describe(workspace).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(
            arcpy.Describe(workspace).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    AnthroAttributeTable = ccsStandard.AnthroAttributeTable
    emptyRaster = ccsStandard.EmptyRaster
    inputDataPath = ccsStandard.InputDataPath
    # Filenames for feature classes or rasters used by this script
    MAP_UNITS = "Map_Units"
    ANALYSIS_AREA = "Analysis_Area"  # provided
    CURRENT_ANTHRO_FEATURES = "Current_Anthro_Features"
    CREDIT_PROJECT_AREA = "Credit_Project_Area"
    PROPOSED_MODIFIED_FEATURES = "Proposed_Modified_Features"
    # Filenames for feature classes or rasters created by this script
    CURRENT_ANTHRO_DISTURBANCE = "Current_Anthro_Disturbance"
    PROJECTED_ANTHRO_DISTURBANCE = "Projected_Anthro_Disturbance"
    MAP_UNITS_DISSOLVE = "Map_Units_Dissolve"
    CURRENT_MGMT_CAT = "Current_Mgmt_Cat"
    CURRENT_WMZ = "Current_WMZ"
    CURRENT_PMU = "Current_PMU"
    CURRENT_PRECIP = "Current_Precip"

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

    # FUNCTION CALLS
    # Check out Spatial Analyst extension
    ccslib.CheckOutSpatialAnalyst()

    # Check Analysis_Area
    feature = Analysis_Area
    expected_fcs = [MAP_UNITS, ANALYSIS_AREA, CREDIT_PROJECT_AREA]
    ccslib.CheckPolygonInput(feature, expected_fcs=expected_fcs)

    # Set up flag for projects that propose to modify anthro features
    includes_anthro_mod = False

    # Check for existence of 'Proposed_Modified_Features'
    if arcpy.Exists(PROPOSED_MODIFIED_FEATURES):
        # Update flag
        includes_anthro_mod = True

    # Copy Dist_Lek to geodatabase

    # Create Current_Anthro_Features layer, or copy provided into geodatabase
    if Current_Anthro_Features_Provided:
        # Clear selection, if present
        ccslib.ClearSelectedFeatures(Current_Anthro_Features_Provided)

        # Check Current_Anthro_Features
        feature = Current_Anthro_Features_Provided
        required_fields = ["Type", "Subtype"]
        no_null_fields = None
        expected_fcs = None
        ccslib.CheckPolygonInput(feature, required_fields, expected_fcs,
                                 no_null_fields)

        # Update message
        arcpy.AddMessage("Copying Current_Anthro_Features to project "
                         "geodatabase")

        # Copy Current_Anthro_Features to geodatabase
        provided_input = Current_Anthro_Features_Provided
        parameter_name = CURRENT_ANTHRO_FEATURES
        preserve_existing = True
        Current_Anthro_Features = ccslib.AdoptParameter(
            provided_input, parameter_name, preserve_existing)

    else:
        # Update message
        arcpy.AddMessage("Merging all clipped anthropogenic features to "
                         "create the Current_Anthro_Features layer")

        # Merge features (selecting only polygon features)
        fileList = arcpy.ListFeatureClasses("Anthro*Clip",
                                            feature_type="Polygon")
        out_name = CURRENT_ANTHRO_FEATURES
        Current_Anthro_Features = ccslib.MergeFeatures(fileList, out_name)

    # Simplify fields
    allowable_fields = ["Type", "Subtype", "SubtypeID", "Subtype_As_Modified"]
    ccslib.SimplifyFields(Current_Anthro_Features, allowable_fields)

    # Remove subtypes from Current_Anthro_Features
    feature = Current_Anthro_Features
    try:
        subtypes = arcpy.da.ListSubtypes(feature)
        for subtype in subtypes:
            arcpy.RemoveSubtype_management(feature, subtype)
            arcpy.AddMessage("Subtype removed")
    except arcpy.ExecuteError:
        arcpy.AddMessage("Could not remove subtypes from "
                         "Current_Anthro_Features")

    # Add Domains for Type and Subtype
    arcpy.RemoveDomainFromField_management(feature, "Type")
    try:
        domainName = "Type"
        arcpy.CreateDomain_management(workspace, domainName,
                                      "Valid " + domainName + "s", "TEXT",
                                      "CODED")
        typeList = [
            row[0]
            for row in arcpy.da.SearchCursor(AnthroAttributeTable, "Type")
        ]
        for code in typeList:
            arcpy.AddCodedValueToDomain_management(workspace, domainName, code,
                                                   code)
    except arcpy.ExecuteError:
        arcpy.AddMessage("Could not add domains for "
                         "Current_Anthro_Features")

    arcpy.AssignDomainToField_management(feature, "Type", "Type")

    arcpy.RemoveDomainFromField_management(feature, "Subtype")
    arcpy.TableToDomain_management(AnthroAttributeTable, "Subtype", "Subtype",
                                   workspace, "Subtype",
                                   "Valid anthropogenic subtypes", "REPLACE")
    arcpy.AssignDomainToField_management(feature, "Subtype", "Subtype")

    # Update Message
    arcpy.AddMessage("Calculating Current Anthropogenic Disturbance")

    # Calculate Current_Anthro_Disturbance
    extent_fc = Analysis_Area
    anthro_features = Current_Anthro_Features
    term = ccsStandard.CreditTerms[0]
    Current_Anthro_Disturbance = ccslib.CalcAnthroDist(extent_fc,
                                                       anthro_features,
                                                       emptyRaster,
                                                       AnthroAttributeTable,
                                                       term)
    Current_Anthro_Disturbance.save(CURRENT_ANTHRO_DISTURBANCE)

    # Update message
    arcpy.AddMessage("Current_Anthro_Disturbance Calculated")

    # If the project proposes to modify existing anthropogenic features,
    # calculate post-project anthropogenic disturbance (uplift)
    if includes_anthro_mod:
        # Calculate uplift
        extent_fc = Analysis_Area
        anthro_features = Current_Anthro_Features
        term = ccsStandard.CreditTerms[1]
        field = "Subtype_As_Modified"
        Projected_Anthro_Disturbance = ccslib.CalcAnthroDist(
            extent_fc, anthro_features, emptyRaster, AnthroAttributeTable,
            term, field)
        Projected_Anthro_Disturbance.save(PROJECTED_ANTHRO_DISTURBANCE)

        # Update message
        arcpy.AddMessage("Projected_Anthro_Disturbance Calculated")
        arcpy.AddMessage("Creating pre-defined map units of PJ")

        Map_Units = MAP_UNITS

        if len(arcpy.ListFields(Map_Units, "Conifer_Phase")) == 0:
            # Create pre-defined map units for PJ
            # Intersect the Map_Units layer with the PJ layer
            in_feature = ccsStandard.PJ_Phases
            field_name = "Conifer_Phase"
            ccslib.CreatePreDefinedMapUnits(Map_Units, in_feature, field_name)

            # Remove unwanted fields from Map Units feature class
            allowable_fields = [
                "Conifer_Phase", "Map_Unit_ID", "Map_Unit_Name", "Meadow",
                "Notes", "Indirect"
            ]
            ccslib.SimplifyFields(Map_Units, allowable_fields)

        # Update message
        arcpy.AddMessage("Merging indirect benefits area and map units layer")

        # Combine the Map Units layer and Indirect Impact Layer
        indirect_benefit_area = CREDIT_PROJECT_AREA
        mgmt_map_units = Map_Units
        Map_Units = ccslib.AddIndirectBenefitArea(indirect_benefit_area,
                                                  mgmt_map_units)

        # Add Map Units layer to map document
        layerFile = ccsStandard.getLayerFile("Map_Units.lyr")
        ccslib.AddToMap(Map_Units, layerFile)

    else:
        # Add Indirect field to Map Units layer and populate with False
        # Add field "Indirect"
        feature = MAP_UNITS
        fieldsToAdd = ["Indirect"]
        fieldTypes = ["TEXT"]
        ccslib.AddFields(feature, fieldsToAdd, fieldTypes)

        # Update field to equal "False"
        with arcpy.da.UpdateCursor(feature, fieldsToAdd) as cursor:
            for row in cursor:
                row[0] = "False"
                cursor.updateRow(row)

    # Calculate local scale modifiers for Current condition
    extent_fc = Analysis_Area
    anthro_disturbance = CURRENT_ANTHRO_DISTURBANCE
    term = ccsStandard.CreditTerms[0]
    ccslib.CalcModifiers(extent_fc, inputDataPath, Dist_Lek,
                         anthro_disturbance, term)

    # Calculate local scale modifiers for Projected condition
    # Determine which anthropogenic disturbance raster to use
    extent_fc = Analysis_Area
    if arcpy.Exists(PROJECTED_ANTHRO_DISTURBANCE):
        anthro_disturbance = PROJECTED_ANTHRO_DISTURBANCE
    else:
        anthro_disturbance = CURRENT_ANTHRO_DISTURBANCE
    term = ccsStandard.CreditTerms[1]
    ccslib.CalcModifiers(extent_fc,
                         inputDataPath,
                         Dist_Lek,
                         anthro_disturbance,
                         term,
                         PJ_removal=True)

    # Update message
    arcpy.AddMessage("Dissolving all multi-part map units to create "
                     "Map_Units_Dissolve")

    # Dissolve Map Units
    allowable_fields = [
        "Map_Unit_ID", "Map_Unit_Name", "Meadow", "Conifer_Phase", "BROTEC",
        "Indirect"
    ]
    out_name = MAP_UNITS_DISSOLVE
    anthro_features = Current_Anthro_Features
    Map_Units_Dissolve = ccslib.DissolveMapUnits(MAP_UNITS, allowable_fields,
                                                 out_name, anthro_features)

    # Update message
    arcpy.AddMessage("Adding Map_Units_Dissolve to map")

    # Add layer to map document
    feature = Map_Units_Dissolve
    layerFile = ccsStandard.getLayerFile("Map_Units.lyr")
    ccslib.AddToMap(feature, layerFile, zoom_to=True)

    # Update message
    arcpy.AddMessage("Calculating area in acres for each map unit")

    # Calculate Area
    ccslib.CalcAcres(Map_Units_Dissolve)

    # Initialize a list to track proportion feature classes
    prop_fcs = []

    # Update message
    arcpy.AddMessage("Calculating Proportion within each precipitation zone")

    # Calculate Proportion of each map unit in each Precip Zone
    in_feature = os.path.join(inputDataPath, "Precip")
    out_feature_class = CURRENT_PRECIP
    field_name = "Precip_Proportion"
    ccslib.CalcProportion(Map_Units_Dissolve, in_feature, out_feature_class,
                          field_name)
    prop_fcs.append(out_feature_class)

    # Update message
    arcpy.AddMessage("Calculating Management Importance Factor")

    # Calculate Proportion of each map unit in each Management Category
    in_feature = os.path.join(inputDataPath, "Mgmt_Cat")
    out_feature_class = CURRENT_MGMT_CAT
    field_name = "Mgmt_Proportion"
    ccslib.CalcProportion(Map_Units_Dissolve, in_feature, out_feature_class,
                          field_name)
    prop_fcs.append(out_feature_class)

    # Update message
    arcpy.AddMessage("Evaluating WAFWA Management Zone")

    # Calculate Proportion in each map unit in each WAFWA Zone
    in_feature = os.path.join(inputDataPath, "NV_WAFWA")
    out_feature_class = CURRENT_WMZ
    field_name = "WMZ_Proportion"
    ccslib.CalcProportion(Map_Units_Dissolve, in_feature, out_feature_class,
                          field_name)
    prop_fcs.append(out_feature_class)

    # Update message
    arcpy.AddMessage("Evaluating Priority Management Unit")

    # Calculate Proportion in each map unit in each PMU
    in_feature = os.path.join(inputDataPath, "NV_PMU")
    out_feature_class = CURRENT_PMU
    field_name = "PMU_Proportion"
    ccslib.CalcProportion(Map_Units_Dissolve, in_feature, out_feature_class,
                          field_name)
    prop_fcs.append(out_feature_class)

    # Delete unnecessary fields in proportion feature classes
    allowable_fields = [
        "Map_Unit_ID", "Management", "Mgmt_zone", "PMU_NAME", "Precip",
        "Mgmt_Proportion", "WMZ_Proportion", "PMU_Proportion",
        "Precip_Proportion"
    ]
    for feature in prop_fcs:
        ccslib.SimplifyFields(feature, allowable_fields)

    # Set processing extent to Map_Units layer
    arcpy.env.extent = arcpy.Describe(Map_Units_Dissolve).extent

    # Calculate the average HSI values per map unit for each map unit
    HSIseasons = ccsStandard.HSISeasons
    for season in HSIseasons:
        # Update message
        arcpy.AddMessage("Summarizing " + season + " HSI")

        # Calculate zonal statistics for each map unit
        inZoneData = Map_Units_Dissolve
        inValueRaster = os.path.join(inputDataPath, season + "_HSI")
        zoneField = "Map_Unit_ID"
        outTable = "ZonalStats_" + season + "_HSI"
        ccslib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

        # Join the zonal statistic to the Map Units Dissolve table
        fieldName = season + "_HSI"
        ccslib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

    # Update message
    arcpy.AddMessage("Calculating PJ cover per map unit")

    # Calculate the average pinon-juniper cover per map unit
    inZoneData = Map_Units_Dissolve
    inValueRaster = os.path.join(inputDataPath, "PJ_Cover")
    zoneField = "Map_Unit_ID"
    outTable = "ZonalStats_PJCover"
    ccslib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

    # Join the zonal statistic to the Map Units Dissolve table
    fieldName = "PJ_Cover"
    ccslib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

    # Calculate the average seasonal modifier values per map unit and
    # join to Map_Unit_Dissolve table
    terms = ccsStandard.CreditTerms
    seasons = ccsStandard.Seasons
    for term in terms:
        for season in seasons:
            # Update message
            arcpy.AddMessage("Summarizing " + term + "_Local_" + season)

            # Calculate zonal statistics for each map unit
            inZoneData = Map_Units_Dissolve
            inValueRaster = term + "_Local_" + season
            zoneField = "Map_Unit_ID"
            outTable = "ZonalStats_" + term + season
            ccslib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                  outTable)

            # Join the zonal statistic to the Map Units Dissolve table
            fieldName = term + "_" + season
            ccslib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

    # Calculate impact intensity for credit project
    try:
        ccslib.calcCreditBenefit(inputDataPath, includes_anthro_mod)

        # Add credit project quality to map
        layerFile = ccsStandard.getLayerFile("Credit_Project_Benefit.lyr")
        ccslib.AddToMap("Credit_Quality", layerFile, zoom_to=True)
    except:
        pass

    # Remove uplift modifier for map units that do not qualify
    # Select map units of Indirect if project involves anthro
    # feature modification
    if includes_anthro_mod:
        feature = MAP_UNITS_DISSOLVE
        arcpy.MakeFeatureLayer_management(feature, "lyr")
        where_clause = """({} = '{}') AND ({} <> {} OR {} <> {} OR {} <> {})""".format(
            arcpy.AddFieldDelimiters(feature, "Indirect"), "True",
            arcpy.AddFieldDelimiters(feature, "Projected_Breed"),
            arcpy.AddFieldDelimiters(feature, "Current_Breed"),
            arcpy.AddFieldDelimiters(feature, "Projected_LBR"),
            arcpy.AddFieldDelimiters(feature, "Current_LBR"),
            arcpy.AddFieldDelimiters(feature, "Projected_Winter"),
            arcpy.AddFieldDelimiters(feature, "Current_Winter"))
        arcpy.SelectLayerByAttribute_management(feature, "NEW_SELECTION",
                                                where_clause)
        test = arcpy.GetCount_management(feature)
        count = int(test.getOutput(0))
        if count > 0:
            # Update message
            arcpy.AddMessage("Confirming removal of PJ cover credits meet "
                             "eligibility criteria (if applicable)")

            # Substitute Projected_Anthro_Disturbance if it exists
            extent_fc = Analysis_Area
            if arcpy.Exists(PROJECTED_ANTHRO_DISTURBANCE):
                anthroDisturbance = PROJECTED_ANTHRO_DISTURBANCE
            else:
                anthroDisturbance = CURRENT_ANTHRO_DISTURBANCE

            # Repeat calculation of modifiers w/o PJ_uplift
            term = ccsStandard.CreditTerms[1]
            ccslib.CalcModifiers(extent_fc,
                                 inputDataPath,
                                 Dist_Lek,
                                 anthroDisturbance,
                                 term,
                                 PJ_removal=False,
                                 suffix="noPJ")

            # Repeat joins to table
            for season in seasons:
                # Calculate zonal statistics for each map unit
                inZoneData = Map_Units_Dissolve
                inValueRaster = term + "_Local_" + season + "_noPJ"
                zoneField = "Map_Unit_ID"
                outTable = "ZonalStats_" + term + season
                ccslib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                      outTable)

                # Join the zonal statistic to the Map Units Dissolve table
                fieldName = term + "_" + season + "_noPJ"
                ccslib.JoinMeanToTable(inZoneData, outTable, zoneField,
                                       fieldName)

                # Overwrite Projected seasonal local scale scores
                overwrite_field = ccsStandard.CreditTerms[1] + "_" + season
                with arcpy.da.UpdateCursor(
                        feature, [fieldName, overwrite_field]) as cursor:
                    for row in cursor:
                        row[1] = row[0]
                        cursor.updateRow(row)

                # Clean up
                arcpy.DeleteField_management(feature, fieldName)

        # Clean up
        arcpy.SelectLayerByAttribute_management(feature, "CLEAR_SELECTION")
        arcpy.Delete_management("lyr")

    # Add transect field to Map_Units_Dissolve
    fields = ["Transects"]
    fieldTypes = ["SHORT"]
    ccslib.AddFields(Map_Units_Dissolve, fields, fieldTypes)

    # Export data to Excel
    input_Tables = [
        MAP_UNITS_DISSOLVE, CURRENT_MGMT_CAT, CURRENT_WMZ, CURRENT_PMU,
        CURRENT_PRECIP
    ]
    for table in input_Tables:
        ccslib.ExportToExcel(table, Project_Folder, Project_Name)

    # Clean up
    arcpy.Delete_management("in_memory")

    # Save map document
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #18
0
def main():
    # GET PARAMETER VALUES
    Proposed_Surface_Disturbance_Provided = arcpy.GetParameterAsText(0)
    Proposed_Modified_Features_Provided = arcpy.GetParameterAsText(
        1)  # optional

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Construct pathname to workspace
    projectGDB = arcpy.Describe(Proposed_Surface_Disturbance_Provided).path
    arcpy.AddMessage("Project geodatabase: " + projectGDB)

    # Instantiate a cheStandard object
    cheStandard = cohqt.cheStandard(projectGDB, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = projectGDB
    scratch_folder = os.path.join(arcpy.Describe(projectGDB).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(
            arcpy.Describe(projectGDB).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    Parameter_Values = cheStandard.ParameterValues
    habitat_bounds = cheStandard.HabitatMgmtArea
    ConiferModifier = cheStandard.ConiferModifier
    GrSG_LDI = cheStandard.GrSG_LDI
    LekPresenceRaster = cheStandard.LekPresenceRaster
    Lek_Distance_Modifier = cheStandard.LekDistanceModifier
    SageModifier = cheStandard.SageModifier
    GrSGHabitat = cheStandard.BWSGHab
    MuleDeerHabitat = cheStandard.BWMDHab
    emptyRaster = cheStandard.EmptyRaster
    MigrationModifier = cheStandard.MuleDeerMigrationMod
    WinterModifier = cheStandard.MuleDeerWinterMod
    SummerModifier = cheStandard.MuleDeerSummerMod
    MuleDeer_LDI = cheStandard.MuleDeerLDI
    BWMD_Open = cheStandard.BWMD_Open
    GrSG_Range = cheStandard.GrSGHabitat
    Mule_Range = cheStandard.MuleDeerHabitat
    cellSize = arcpy.GetRasterProperties_management(emptyRaster,
                                                    "CELLSIZEX").getOutput(0)

    # Filenames for feature classes or rasters used by this script
    PROPOSED_SURFACE_DISTURBANCE_DEBITS = "Proposed_Surface_Disturbance_Debits"

    # Filenames for feature classes or rasters created by this script
    ANALYSIS_AREA = "Analysis_Area"
    DEBIT_PROJECT_AREA = "Debit_Project_Area"
    INDIRECT_IMPACT_AREA = "Indirect_Impact_Area"
    INDIRECT_BENEFIT_AREA = "Indirect_Benefit_Area"
    PROPOSED_MODIFIED_FEATURES = "Proposed_Modified_Features"
    DEBIT_PROJECT_IMPACT = "GrSG_Impact"
    MAP_UNITS = "Map_Units"
    # GrSG Filenames
    LEK_DISTURBANCE_MODIFIER = "Lek_Disturbance_Modifier"
    CUMULATIVE_MODIFIER_PRE = "GRSG_Pre_Cumulative_Modifier"
    CUMULATIVE_MODIFIER_POST = "GRSG_Post_Cumulative_Modifier"
    CURRENT_ANTHRO_DISTURBANCE = "GRSG_Pre_Anthro_Disturbance"
    PROJECTED_ANTHRO_DISTURBANCE = "GRSG_Post_Anthro_Disturbance"
    GRSG_PRE_BREEDING = "GRSG_Pre_Breeding"
    GRSG_PRE_SUMMER = "GRSG_Pre_Summer"
    GRSG_PRE_WINTER = "GRSG_Pre_Winter"
    GRSG_POST_BREEDING = "GRSG_Post_Breeding"
    GRSG_POST_SUMMER = "GRSG_Post_Summer"
    GRSG_POST_WINTER = "GRSG_Post_Winter"
    # Mule Deer Filenames
    CURRENT_ANTHRO_DISTURBANCE_MD = "MuleDeer_Pre_Anthro_Disturbance"
    PROJECTED_ANTHRO_DISTURBANCE_MD = "MuleDeer_Post_Anthro_Disturbance"
    MULE_PRE_SUMMER = "MuleDeer_Pre_Summer"
    MULE_PRE_MIGRATION = "MuleDeer_Pre_Migration"
    MULE_PRE_WINTER = "MuleDeer_Pre_Winter"
    MULE_POST_SUMMER = "MuleDeer_Post_Summer"
    MULE_POST_MIGRATION = "MuleDeer_Post_Migration"
    MULE_POST_WINTER = "MuleDeer_Post_Winter"

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

    # FUNCTION CALLS
    # Check out Spatial Analyst extension
    hqtlib.CheckOutSpatialAnalyst()

    if not Proposed_Modified_Features_Provided:
        # Ensure Proposed_Modified_Features does not exist
        if arcpy.Exists("Proposed_Modified_Features"):
            arcpy.AddError("ERROR:: A 'Proposed_Modified_Features' layer "
                           "was detected in the project's geodatabase. "
                           "Provide the 'Proposed_Modified_Features' layer "
                           "and re-run Debit Tool 2.")
            sys.exit(0)

    # Clear selection, if present
    util.ClearSelectedFeatures(Proposed_Surface_Disturbance_Provided)

    # Check Proposed_Surface_Disturbance
    feature = Proposed_Surface_Disturbance_Provided
    required_fields = ["Type", "Subtype", "Surface_Disturbance"]
    no_null_fields = required_fields
    expected_fcs = None
    hqtlib.CheckPolygonInput(feature, required_fields, expected_fcs,
                             no_null_fields)

    # Update Proposed_Surface_Disturbance layer with provided layer
    provided_input = Proposed_Surface_Disturbance_Provided
    parameter_name = PROPOSED_SURFACE_DISTURBANCE_DEBITS
    Proposed_Surface_Disturbance = util.AdoptParameter(provided_input,
                                                       parameter_name,
                                                       preserve_existing=False)

    # Replace Proposed_Surface_Disturbance_Debits layer on map
    layerFile = cheStandard.getLayerFile("ProposedSurfaceDisturbance.lyr")
    util.AddToMap(Proposed_Surface_Disturbance, layerFile)

    # Add field for Disturbance_Type and populate. Values will be used in
    # Map_Units_Dissolve to identify map units of direct disturbance
    feature = Proposed_Surface_Disturbance
    fields = ["Disturbance_Type"]
    fieldTypes = ["TEXT"]
    util.AddFields(feature, fields, fieldTypes)

    with arcpy.da.UpdateCursor(feature,
                               ["Surface_Disturbance"] + fields) as cursor:
        for row in cursor:
            row[1] = "Direct_" + row[0]
            cursor.updateRow(row)

    # Update message
    arcpy.AddMessage("Creating the area of indirect impact")

    # Buffer proposed surface disturbance to create Indirect_Impact_Area
    in_data = Proposed_Surface_Disturbance
    out_name = INDIRECT_IMPACT_AREA
    Indirect_Impact_Area = hqtlib.CreateIndirectImpactArea(
        in_data, Parameter_Values, out_name)

    # Set up flag for projects that propose to modify anthro features
    includes_anthro_mod = False

    if Proposed_Modified_Features_Provided:
        # Update flag
        includes_anthro_mod = True

        # Clear selection, if present
        util.ClearSelectedFeatures(Proposed_Modified_Features_Provided)

        # Check provided layer
        required_fields = ["Type", "Subtype"]
        no_null_fields = required_fields
        expected_fcs = None
        hqtlib.CheckPolygonInput(Proposed_Modified_Features_Provided,
                                 required_fields, expected_fcs, no_null_fields)

        # Update Proposed_Modified_Features with provided layer and add to map
        provided_input = Proposed_Modified_Features_Provided
        parameterName = PROPOSED_MODIFIED_FEATURES
        preserve_existing = False
        Proposed_Modified_Features = util.AdoptParameter(
            provided_input, parameterName, preserve_existing)

        # Add Proposed Modified Features layer to map
        layerFile = cheStandard.getLayerFile("ProposedSurfaceDisturbance.lyr")
        util.AddToMap(Proposed_Modified_Features, layerFile)

        # Update message
        arcpy.AddMessage("Creating the area of indirect benefit")

        # Create the Indirect_Impact_Area
        in_data = Proposed_Modified_Features
        out_name = INDIRECT_BENEFIT_AREA
        Indirect_Benefit_Area = hqtlib.CreateIndirectImpactArea(
            in_data, Parameter_Values, out_name)

        # Union the indirect benefit area and the indirect impact area
        in_features = [Indirect_Impact_Area, Indirect_Benefit_Area]
        out_name = "in_memory/Impact_Union"
        Impact_Union = arcpy.Union_analysis(in_features, out_name)

        # Dissolve the unioned indirect impact and benefit areas as
        # Indirect Impact Area
        in_features = Impact_Union
        out_feature_class = INDIRECT_IMPACT_AREA
        Indirect_Impact_Area = arcpy.Dissolve_management(
            in_features, out_feature_class)

    # Detect habitat types impacted directly or indirectly
    is_grsg = cohqt.DetectHabitat(Indirect_Impact_Area, GrSG_Range)
    is_mule = cohqt.DetectHabitat(Indirect_Impact_Area, Mule_Range)

    # Update message
    arcpy.AddMessage("Determining project area - eliminating areas of non-"
                     "habitat from the Project Area")

    # Eliminate non-habitat
    project_area = Indirect_Impact_Area
    out_name = DEBIT_PROJECT_AREA
    Debit_Project_Area = hqtlib.EliminateNonHabitat(project_area, out_name,
                                                    habitat_bounds)

    # Calculate Area
    hqtlib.CalcAcres(Debit_Project_Area)

    # Add Debit Project Area to map
    feature = Debit_Project_Area
    layerFile = cheStandard.getLayerFile("DebitProjectArea.lyr")
    util.AddToMap(feature, layerFile, zoom_to=True)

    # Update message
    arcpy.AddMessage("Creating Analysis Area")

    # Create Analysis_Area
    out_name = ANALYSIS_AREA
    Analysis_Area = hqtlib.CreateAnalysisArea(Debit_Project_Area,
                                              Parameter_Values, out_name)

    # Add Analysis_Area to map
    layerFile = cheStandard.getLayerFile("AnalysisArea.lyr")
    util.AddToMap(Analysis_Area, layerFile, zoom_to=True)

    # Set processing extent to Analysis_Area
    arcpy.env.extent = ANALYSIS_AREA

    # Prepare proposed anthropogenic features
    unique_proposed_subtypes = cohqt.convertProposedToRasterDebit(
        Proposed_Surface_Disturbance, cellSize)

    anthroPath = cheStandard.AnthroFeaturePath
    cohqt.combineProposedWithCurrentDebit(anthroPath, unique_proposed_subtypes)

    # # Do something about anthropogenic mod features
    # if includes_anthro_mod:
    #     unique_proposed_subtypes_removed = hqtlib.convertProposedToRaster(
    #         Proposed_Modified_Features, cellSize
    #       )
    #
    #     anthroPath = cheStandard.AnthroFeaturePath
    #     hqtlib.combineProposedWithCurrent(anthroPath, unique_proposed_subtypes)

    ### GREATER SAGE-GROUSE ANTHRO DIST & MODIFIERS ###
    if is_grsg:
        # Update message
        arcpy.AddMessage("Calculating pre-project anthropogenic disturbance "
                         "modifier for greater sage-grouse")

        # Calculate pre-project anthropogenic disturbance
        dist_field = "GrSG_Dist"
        weight_field = "GrSG_Weight"
        term = cheStandard.DebitTerms[0]
        anthro_disturbance_type = "Pre"

        Current_Anthro_Disturbance = cohqt.CalcAnthroDisturbance(
            Parameter_Values, term, unique_proposed_subtypes,
            anthro_disturbance_type, cheStandard, dist_field, weight_field,
            cellSize, emptyRaster)
        Current_Anthro_Disturbance.save(CURRENT_ANTHRO_DISTURBANCE)

        # Update message
        arcpy.AddMessage("Current_Anthro_Disturbance Calculated")
        arcpy.AddMessage("Calculating post-project anthropogenic "
                         "disturbance modifier for greater sage-grouse")

        # Calculate post-project anthropogenic disturbance
        term = cheStandard.DebitTerms[1]
        anthro_disturbance_type = "Post"

        Projected_Anthro_Disturbance = cohqt.CalcAnthroDisturbance(
            Parameter_Values, term, unique_proposed_subtypes,
            anthro_disturbance_type, cheStandard, dist_field, weight_field,
            cellSize, emptyRaster)

        Projected_Anthro_Disturbance.save(PROJECTED_ANTHRO_DISTURBANCE)

        # Update message
        arcpy.AddMessage("Projected_Anthro_Disturbance Calculated")
        arcpy.AddMessage("Calculating lek disturbance modifier")

        # Calculate permanent anthropogenic disturbance

        # Calculate Lek Disturbance Modifier
        term = cheStandard.DebitTerms[1]
        anthro_disturbance_type = "LekDisturbanceModifier"

        Lek_Disturbance_Modifier = cohqt.CalcAnthroDisturbance(
            Parameter_Values, term, unique_proposed_subtypes,
            anthro_disturbance_type, cheStandard, dist_field, weight_field,
            cellSize, emptyRaster)

        Lek_Disturbance_Modifier.save(LEK_DISTURBANCE_MODIFIER)

        # Update message
        arcpy.AddMessage("Calculating Pre-Project Habitat Modifiers")

        # Calculate pre-project cumulative habitat modifiers
        winterHabitatPre = cohqt.calcWinterHabitatGRSG(
            Current_Anthro_Disturbance, ConiferModifier, GrSG_LDI, GrSGHabitat)
        LSDMWinterPre = cohqt.applyLekUpliftModifierPre(
            winterHabitatPre, LekPresenceRaster)
        breedingHabitatPre = cohqt.calcBreedingHabitatGRSG(
            Current_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
            Lek_Distance_Modifier, GrSGHabitat)
        LSDMBreedingPre = cohqt.applyLekUpliftModifierPre(
            breedingHabitatPre, LekPresenceRaster)
        summerHabitatPre = cohqt.calcSummerHabitatGRSG(
            Current_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
            SageModifier, GrSGHabitat)
        LSDMSummerPre = cohqt.applyLekUpliftModifierPre(
            summerHabitatPre, LekPresenceRaster)
        seasonalHabitatRasters = [
            LSDMWinterPre, LSDMBreedingPre, LSDMSummerPre
        ]

        # Save outputs
        # winterHabitatPre.save(GRSG_PRE_WINTER)
        LSDMWinterPre.save(GRSG_PRE_WINTER)
        # breedingHabitatPre.save(GRSG_PRE_BREEDING)
        LSDMBreedingPre.save(GRSG_PRE_BREEDING)
        # summerHabitatPre.save(GRSG_PRE_SUMMER)
        LSDMSummerPre.save(GRSG_PRE_SUMMER)

        # Calculate average of three seasonal habitat rasters pre-project
        finalPreCumulative = cohqt.calcAverageHabitatQuality(
            seasonalHabitatRasters)
        finalPreCumulative.save(CUMULATIVE_MODIFIER_PRE)

        # Calculate post-project cumulative habtiat modifiers
        winterHabitatPost = cohqt.calcWinterHabitatGRSG(
            Projected_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
            GrSGHabitat)
        LSDMWinterPost = cohqt.applyLekUpliftModifierPost(
            winterHabitatPost, LekPresenceRaster, Lek_Disturbance_Modifier)
        breedingHabitatPost = cohqt.calcBreedingHabitatGRSG(
            Projected_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
            Lek_Distance_Modifier, GrSGHabitat)
        LSDMBreedingPost = cohqt.applyLekUpliftModifierPost(
            breedingHabitatPost, LekPresenceRaster, Lek_Disturbance_Modifier)
        summerHabitatPost = cohqt.calcSummerHabitatGRSG(
            Projected_Anthro_Disturbance, ConiferModifier, GrSG_LDI,
            SageModifier, GrSGHabitat)
        LSDMSummerPost = cohqt.applyLekUpliftModifierPost(
            summerHabitatPost, LekPresenceRaster, Lek_Disturbance_Modifier)

        seasonalHabitatRasters = [
            LSDMWinterPost, LSDMBreedingPost, LSDMSummerPost
        ]

        # Save outputs
        # winterHabitatPost.save("Post_Seasonal_Winter")
        LSDMWinterPost.save(GRSG_POST_WINTER)
        # breedingHabitatPost.save("Post_Seasonal_Breeding")
        LSDMBreedingPost.save(GRSG_POST_BREEDING)
        # summerHabitatPost.save("Post_Seasonal_Summer")
        LSDMSummerPost.save(GRSG_POST_SUMMER)

        # Calculate average of three seasonal habitat rasters post-project
        finalPostCumulative = cohqt.calcAverageHabitatQuality(
            seasonalHabitatRasters)
        finalPostCumulative.save(CUMULATIVE_MODIFIER_POST)

        # Calculate permanent cumulative habtiat modifiers

        # Calculate Zonal Statistics for cumulative modifier rasters
        # Add field to use for zonal statistics
        inTable = Debit_Project_Area
        fields = ["ZONAL"]
        field_types = ["SHORT"]
        util.AddFields(inTable, fields, field_types)

        # Populate field with value 1
        arcpy.CalculateField_management(inTable, fields[0], 1, "PYTHON_9.3",
                                        "")

        # Update message
        arcpy.AddMessage("Calculating debits for greater sage-grouse")

        # Calculate zonal statistics for pre-project
        inZoneData = Debit_Project_Area
        inValueRaster = finalPreCumulative
        zoneField = fields[0]
        outTable = "GRSG_Stats_Pre"
        hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

        # Join the zonal statistic to the Debit Project Area table
        fieldName = "GRSG_Pre_Project"
        hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

        # Calculate zonal statistics for post-project
        inZoneData = Debit_Project_Area
        inValueRaster = finalPostCumulative
        zoneField = fields[0]
        outTable = "GRSG_Stats_Post"
        hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

        # Join the zonal statistic to the Debit Project Area table
        fieldName = "GrSG_Post_Project"
        hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

        # Calculate debits (if not collecting field data)
        cohqt.calcDebits(Debit_Project_Area, "GRSG_Pre_Project",
                         "GrSG_Post_Project", "Debits")

        # Update message
        arcpy.AddMessage("Creating visualization of impact from debit project")

        # Calculate impact intensity for debit project
        debit_impact = cohqt.calcImpact(finalPreCumulative,
                                        finalPostCumulative)
        debit_impact.save(DEBIT_PROJECT_IMPACT)

        # Add Debit Impact raster to map and save map document
        feature = debit_impact
        layerFile = cheStandard.getLayerFile("DebitProjectImpact.lyr")
        util.AddToMap(feature, layerFile, zoom_to=True)

    ### END GREATER SAGE-GROUSE ###

    ### MULE DEER ANTHRO DIST & MODIFIERS ###
    if not is_grsg:
        # Calculate Zonal Statistics for cumulative modifier rasters
        # Add field to use for zonal statistics
        inTable = Debit_Project_Area
        fields = ["ZONAL"]
        field_types = ["SHORT"]
        util.AddFields(inTable, fields, field_types)

        # Populate field with value 1
        arcpy.CalculateField_management(inTable, fields[0], 1, "PYTHON_9.3",
                                        "")

    # Update message
    if is_mule:
        arcpy.AddMessage("Calculating pre-project anthropogenic disturbance "
                         "modifier for mule deer")

        # Calculate pre-project anthropogenic disturbance
        # Calculate pre-project in PJ
        dist_field = "MDP_Dist"
        weight_field = "MDP_Weight"
        term = cheStandard.DebitTerms[0]
        #unique_proposed_subtypes = []
        anthro_disturbance_type = "Pre"

        anthro_pj = cohqt.CalcAnthroDisturbance(Parameter_Values, term,
                                                unique_proposed_subtypes,
                                                anthro_disturbance_type,
                                                cheStandard, dist_field,
                                                weight_field, cellSize,
                                                emptyRaster)
        anthro_pj.save(CURRENT_ANTHRO_DISTURBANCE_MD + "_P")

        # Calculate pre-project in Open
        dist_field = "MDO_Dist"
        weight_field = "MDO_Weight"
        term = cheStandard.DebitTerms[0]
        #unique_proposed_subtypes = []
        anthro_disturbance_type = "Pre"

        anthro_open = cohqt.CalcAnthroDisturbance(Parameter_Values,
                                                  term,
                                                  unique_proposed_subtypes,
                                                  anthro_disturbance_type,
                                                  cheStandard,
                                                  dist_field,
                                                  weight_field,
                                                  cellSize,
                                                  emptyRaster,
                                                  mask=BWMD_Open)
        anthro_open.save(CURRENT_ANTHRO_DISTURBANCE_MD + "_O")

        # Combine PJ and Open
        # If outside open, make 1
        anthro_open_only = Con(BWMD_Open == 1, anthro_open, 1)
        anthro_open_only.save(CURRENT_ANTHRO_DISTURBANCE_MD + "_OO")

        # Select minimum of pj and open rasters
        Current_Anthro_Disturbance = Con(anthro_open_only < anthro_pj,
                                         anthro_open_only, anthro_pj)
        Current_Anthro_Disturbance.save(CURRENT_ANTHRO_DISTURBANCE_MD)

        # Clean up
        arcpy.Delete_management("temp_masked_raster")
        # arcpy.Delete_management(CURRENT_ANTHRO_DISTURBANCE_MD + "_P")
        # arcpy.Delete_management(CURRENT_ANTHRO_DISTURBANCE_MD + "_O")
        # arcpy.Delete_management(CURRENT_ANTHRO_DISTURBANCE_MD + "_OO")

        # Update message
        arcpy.AddMessage("Current_Anthro_Disturbance Calculated")
        arcpy.AddMessage("Calculating post-project anthropogenic "
                         "disturbance modifier")

        # Calculate post-project anthropogenic disturbance
        # Calculate post-project in PJ
        dist_field = "MDP_Dist"
        weight_field = "MDP_Weight"
        term = cheStandard.DebitTerms[1]
        #unique_proposed_subtypes = []
        anthro_disturbance_type = "Post"

        anthro_pj = cohqt.CalcAnthroDisturbance(Parameter_Values, term,
                                                unique_proposed_subtypes,
                                                anthro_disturbance_type,
                                                cheStandard, dist_field,
                                                weight_field, cellSize,
                                                emptyRaster)
        anthro_pj.save(PROJECTED_ANTHRO_DISTURBANCE_MD + "_P")

        # Calculate pre-project in Open
        dist_field = "MDO_Dist"
        weight_field = "MDO_Weight"
        term = cheStandard.DebitTerms[1]
        #unique_proposed_subtypes = []
        anthro_disturbance_type = "Post"

        anthro_open = cohqt.CalcAnthroDisturbance(Parameter_Values,
                                                  term,
                                                  unique_proposed_subtypes,
                                                  anthro_disturbance_type,
                                                  cheStandard,
                                                  dist_field,
                                                  weight_field,
                                                  cellSize,
                                                  emptyRaster,
                                                  mask=BWMD_Open)
        anthro_open.save(PROJECTED_ANTHRO_DISTURBANCE_MD + "_O")

        # Combine PJ and Open
        # If outside open, make 1
        anthro_open_only = Con(BWMD_Open == 1, anthro_open, 1)
        anthro_open_only.save(PROJECTED_ANTHRO_DISTURBANCE_MD + "_OO")

        # Select minimum of pj and open rasters
        Projected_Anthro_Disturbance = Con(anthro_open_only < anthro_pj,
                                           anthro_open_only, anthro_pj)
        Projected_Anthro_Disturbance.save(PROJECTED_ANTHRO_DISTURBANCE_MD)

        # Update message
        arcpy.AddMessage("Projected_Anthro_Disturbance Calculated")
        # arcpy.AddMessage("Calculating lek disturbance modifier")
        #
        # # Calculate permanent anthropogenic disturbance
        #
        # # Calculate Lek Disturbance Modifier
        # term = cheStandard.CreditTerms[1]
        # anthro_disturbance_type = "LekDisturbanceModifier"
        #
        # Lek_Disturbance_Modifier = hqtlib.cheCalcAnthroDisturbance(
        #     Parameter_Values, term, unique_proposed_subtypes,
        #     anthro_disturbance_type, cheStandard, dist_field, weight_field,
        #     cellSize, emptyRaster
        # )
        #
        # Lek_Disturbance_Modifier.save(LEK_DISTURBANCE_MODIFIER)

        # Update message
        arcpy.AddMessage("Calculating Pre-Project Habitat Modifiers")

        # Calculate pre-project cumulative habitat modifiers
        summerHabitatPre = cohqt.calcSummerHabitatMD(
            Current_Anthro_Disturbance,
            MuleDeer_LDI,
            SummerModifier,
            SuitableHabitat=MuleDeerHabitat)
        # LSDMWinterPre = cohqt.applyLekUpliftModifierPre(summerHabitatPre,
        #                                                  LekPresenceRaster)
        migratoryHabitatPre = cohqt.calcMigratoryHabitatMD(
            Current_Anthro_Disturbance,
            MuleDeer_LDI,
            MigrationModifier,
            SuitableHabitat=MuleDeerHabitat)
        # LSDMBreedingPre = cohqt.applyLekUpliftModifierPre(migratoryHabitatPre,
        #                                                    LekPresenceRaster)
        winterHabitatPre = cohqt.calcWinterHabitatMD(
            Current_Anthro_Disturbance,
            MuleDeer_LDI,
            WinterModifier,
            SuitableHabitat=MuleDeerHabitat)
        # LSDMSummerPre = cohqt.applyLekUpliftModifierPre(winterHabitatPre,
        #                                                  LekPresenceRaster)
        seasonalHabitatRasters = [
            summerHabitatPre, migratoryHabitatPre, winterHabitatPre
        ]

        # Save outputs
        summerHabitatPre.save(MULE_PRE_SUMMER)
        # LSDMWinterPre.save("Pre_LSDM_Winter")
        migratoryHabitatPre.save(MULE_PRE_MIGRATION)
        # LSDMBreedingPre.save("Pre_LSDM_Breeding")
        winterHabitatPre.save(MULE_PRE_WINTER)
        # LSDMSummerPre.save("Pre_LSDM_Summer")

        # Calc zonal stats for pre-project modifiers (three seasons)
        term = cheStandard.DebitTerms[0]
        for season, raster in zip(cheStandard.MuleDeerSeasons,
                                  seasonalHabitatRasters):
            # Update message
            arcpy.AddMessage("Summarizing Mule Deer " + term + " " + season)

            # Calculate zonal statistics for each map unit
            inZoneData = Debit_Project_Area
            inValueRaster = raster
            zoneField = fields[0]
            outTable = "Mule_Stats_" + term + "_" + season
            hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                  outTable)

            # Join the zonal statistic to the Map Units Dissolve table
            fieldName = "Mule_" + term + "_" + season
            hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

        # # Calculate average of three seasonal habitat rasters pre-project
        # finalPreCumulative = hqtlib.calcAverageHabitatQuality(
        #     seasonalHabitatRasters
        # )
        # finalPreCumulative.save(CUMULATIVE_MODIFIER_PRE)

        # Calculate post-project cumulative habitat modifiers
        summerHabitatPost = cohqt.calcSummerHabitatMD(
            Projected_Anthro_Disturbance,
            MuleDeer_LDI,
            SummerModifier,
            SuitableHabitat=MuleDeerHabitat)
        # LSDMWinterPost = cohqt.applyLekUpliftModifierPost(summerHabitatPost,
        #                                                  LekPresenceRaster)
        migratoryHabitatPost = cohqt.calcMigratoryHabitatMD(
            Projected_Anthro_Disturbance,
            MuleDeer_LDI,
            MigrationModifier,
            SuitableHabitat=MuleDeerHabitat)
        # LSDMBreedingPost = cohqt.applyLekUpliftModifierPost(migratoryHabitatPost,
        #                                                    LekPresenceRaster)
        winterHabitatPost = cohqt.calcWinterHabitatMD(
            Projected_Anthro_Disturbance,
            MuleDeer_LDI,
            WinterModifier,
            SuitableHabitat=MuleDeerHabitat)
        # LSDMSummerPost = cohqt.applyLekUpliftModifierPost(winterHabitatPost,
        #                                                  LekPresenceRaster)
        seasonalHabitatRasters = [
            summerHabitatPost, migratoryHabitatPost, winterHabitatPost
        ]

        # Save outputs
        summerHabitatPost.save(MULE_POST_SUMMER)
        # LSDMWinterPre.save("Pre_LSDM_Winter")
        migratoryHabitatPost.save(MULE_POST_MIGRATION)
        # LSDMBreedingPre.save("Pre_LSDM_Breeding")
        winterHabitatPost.save(MULE_POST_WINTER)
        # LSDMSummerPre.save("Pre_LSDM_Summer")

        # Calc zonal stats for pre-project modifiers (three seasons)
        term = cheStandard.DebitTerms[1]
        for season, raster in zip(cheStandard.MuleDeerSeasons,
                                  seasonalHabitatRasters):
            # Update message
            arcpy.AddMessage("Summarizing Mule Deer " + term + " " + season)

            # Calculate zonal statistics for each map unit
            inZoneData = Debit_Project_Area
            inValueRaster = raster
            zoneField = fields[0]
            outTable = "Mule_Stats_" + term + "_" + season
            hqtlib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                  outTable)

            # Join the zonal statistic to the Map Units Dissolve table
            fieldName = "Mule_" + term + "_" + season
            hqtlib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

        # # Calculate average of three seasonal habitat rasters post-project
        # finalPostCumulative = hqtlib.calcAverageHabitatQuality(
        #     seasonalHabitatRasters
        # )
        # finalPostCumulative.save(CUMULATIVE_MODIFIER_POST)

        # Calculate permanent cumulative habtiat modifiers

        # Update message
        arcpy.AddMessage("Calculating Mule Deer Impact")

        # Calculate impact
        pre_fields = [
            "Mule_Pre_Summer", "Mule_Pre_Migration", "Mule_Pre_Winter"
        ]
        post_fields = [
            "Mule_Post_Summer", "Mule_Post_Migration", "Mule_Post_Winter"
        ]
        out_fields = [
            "Mule_Summer_Impact", "Mule_Migration_Impact", "Mule_Winter_Impact"
        ]
        for i in range(len(pre_fields)):
            pre_field = pre_fields[i]
            post_field = post_fields[i]
            out_field = out_fields[i]
            cohqt.calcDebits(Debit_Project_Area, pre_field, post_field,
                             out_field)

        # # Update message
        # arcpy.AddMessage("Creating visualization of impact from debit project")
        #
        # # Calculate impact intensity for debit project
        # debit_impact = hqtlib.calcImpact(finalPreCumulative, finalPostCumulative)
        # debit_impact.save(DEBIT_PROJECT_IMPACT)
        #
        # # Add Debit Impact raster to map and save map document
        # feature = debit_impact
        # layerFile = cheStandard.getLayerFile("DebitProjectImpact.lyr")
        # hqtlib.AddToMap(feature, layerFile, zoom_to=True)

        ### END MULE DEER ###

    if not is_grsg and not is_mule:
        arcpy.AddMessage("Impacts were not detected in any habitat type. "
                         "Please check credit project boundary and try "
                         "again")

    # Create Map_Units layer
    in_data = Debit_Project_Area
    out_data = MAP_UNITS
    Map_Units = hqtlib.CreateMapUnits(in_data, out_data)

    # Add Map_Units to map
    layerFile = cheStandard.getLayerFile("MapUnits.lyr")
    util.AddToMap(Map_Units, layerFile)

    # Add fields Map_Unit_ID, Map_Unit_Name, and Meadow to Map_Units
    fields = ["Map_Unit_ID", "Map_Unit_Name", "Notes", "Precip", "Transects"]
    fieldTypes = ["SHORT", "TEXT", "TEXT", "TEXT", "SHORT"]
    util.AddFields(Map_Units, fields, fieldTypes, copy_existing=True)

    # Add Domains to Map_Units layer
    # Create Domain for Map_Unit_ID attributes
    domainName = "Map_Unit_ID"
    range_low = 0
    range_high = 10000
    util.AddRangeDomain(Map_Units, projectGDB, domainName, range_low,
                        range_high)

    # Create Domain for Precip attributes
    feature_list = [Map_Units]
    domain_name = "Precip"
    code_list = ["Arid", "Mesic"]
    util.AddCodedTextDomain(feature_list, projectGDB, domain_name, code_list)

    # Update message
    arcpy.AddMessage("Cleaning up workspace")

    # Clean up
    for raster in arcpy.ListRasters("*_Subtype_Disturbance"):
        arcpy.Delete_management(raster)

    for raster in arcpy.ListRasters("*_Type_Disturbance"):
        arcpy.Delete_management(raster)

    arcpy.Delete_management("in_memory")
    try:
        arcpy.Delete_management(scratch_folder)
    except:
        pass

    # Save map document and exit
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #19
0
def main():
    # GET PARAMETER VALUES
    Map_Units_Dissolve_Provided = arcpy.GetParameterAsText(0)
    Transects_Provided = arcpy.GetParameterAsText(1)
    Project_Folder = arcpy.GetParameterAsText(2)
    Project_Name = arcpy.GetParameterAsText(3)  # optional

    # DEFINE DIRECTORIES & PATH NAMES FOR FOLDERS & GBDs
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Construct pathname to workspace
    workspace = arcpy.Describe(Map_Units_Dissolve_Provided).path
    arcpy.AddMessage("Project geodatabase: " + workspace)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    arcpy.env.scratchWorkspace = workspace
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    # Filenames for feature classes or rasters used by this script

    # Filenames for feature classes or rasters created by this script
    TRANSECTS_SJ = "Transects_SpatialJoin"

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

    # FUNCTION CALLS
    # Check tool version
    ccslib.CheckToolVersion()

    if Transects_Provided:
        # Update message
        arcpy.AddMessage("Executing spatial join of Transects and "
                         "Map_Unit_Dissolve layer")

        # ccslib.AddTransectFields(Transects)
        Map_Units_Dissolve = Map_Units_Dissolve_Provided
        out_name = "in_memory/Transects"
        transects = ccslib.TransectJoin(Map_Units_Dissolve, Transects_Provided,
                                        out_name)

    else:
        arcpy.AddError("ERROR:: Please provide the transects feature"
                       "class or shapefile provided by the SETT")
        sys.exit(0)

    # Update message
    arcpy.AddMessage("Preparing Transects Spatial Join for export")

    # Remove unnecessary fields
    allowable_fields = [
        "Bearing1", "Bearing2", "Bearing3", "UTM_E", "UTM_N", "Map_Unit_ID",
        "Map_Unit_Name", "Meadow", "Indirect", "Acres", "Spring_HSI",
        "Summer_HSI", "Winter_HSI", "PJ_Cover", "Current_Breed", "Current_LBR",
        "Current_Winter", "Projected_Breed", "Projected_LBR",
        "Projected_Winter", "Permanent_Breed", "Permanent_LBR",
        "Permanent_Winter", "Transects", "Transect_Number", "Sample_Type",
        "Notes"
    ]
    allowable_fields_lower = [
        allow_field.lower() for allow_field in allowable_fields
    ]
    for field in arcpy.ListFields(transects):
        if field.name.lower() not in allowable_fields_lower \
                and field.required is False:
            try:
                arcpy.DeleteField_management(transects, field.name)
            except arcpy.ExecuteError:
                pass
    # ccslib.SimplifyFields(TRANSECTS_SJ, allowable_fields)

    # Sort fields by Transect ID
    arcpy.Sort_management(transects, TRANSECTS_SJ,
                          [["Transect_Number", "ASCENDING"]])

    # Add Transects to map
    ccslib.AddToMap(TRANSECTS_SJ)

    # Export data to Excel
    table = TRANSECTS_SJ
    ccslib.ExportToExcel(table, Project_Folder, Project_Name)

    # Save map document
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #20
0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"""

# Import system modules
import arcpy
import os
import sys
import gc
import ccslib

if arcpy.ListInstallations()[0] == 'arcgispro':  # switch
    import importlib
    importlib.reload(ccslib)


def main():
    # GET PARAMETER VALUES
    Analysis_Area = arcpy.GetParameterAsText(0)
    Current_Anthro_Features_Provided = arcpy.GetParameterAsText(1)  # optional
    Dist_Lek = arcpy.GetParameterAsText(2)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    # Construct pathname to workspace
Beispiel #21
0
def main():
    # GET PARAMETER VALUES
    workspace = arcpy.GetParameterAsText(0)
    Credit_Project_Boundary = arcpy.GetParameterAsText(1)
    includes_anthro_mod = arcpy.GetParameterAsText(2)  # optional
    Proposed_Modified_Features_Provided = arcpy.GetParameterAsText(3)  # optional

    # Update boolean parameters
    includes_anthro_mod = ccslib.Str2Bool(includes_anthro_mod)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Instantiate a ccsStandard object
    ccsStandard = ccslib.ccsStandard(workspace, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    arcpy.env.scratchWorkspace = workspace
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE GLOBAL VARIABLES
    AnthroAttributeTable = ccsStandard.AnthroAttributeTable
    coordinate_system = ccsStandard.CoorSystem
    habitat_bounds = ccsStandard.HabitatBounds
    # Filenames for feature classes and rasters created by this script
    CREDIT_PROJECT_AREA = "Credit_Project_Area"
    PROPOSED_MODIFIED_FEATURES = "Proposed_Modified_Features"
    MAP_UNITS = "Map_Units"
    
    # ------------------------------------------------------------------------

    # FUNCTION CALLS
    # Update includes_anthro_mod if Proposed_Modified_Features is
    # provided
    if Proposed_Modified_Features_Provided and not includes_anthro_mod:
        includes_anthro_mod = True

    # Exit with warning if no Credit Project Boundary is provided and project
    # is does not propose to remove or modify anthropogenic disturbance
    if not Credit_Project_Boundary and not includes_anthro_mod:
        arcpy.AddError("ERROR:: A credit project boundary must be provided "
                       "unless the project proposes to remove or modify "
                       "anthropogenic features. Ensure 'Credit Project will "
                       "remove or modify existing anthropogenic features' is "
                       "checked if true. Please see the User's Guide for "
                       "additional instruction.")
        sys.exit(0)

    # Check input features
    if Credit_Project_Boundary:
        # Check provided input for polygon shape type
        ccslib.CheckPolygonInput(Credit_Project_Boundary)

    if Proposed_Modified_Features_Provided:
        # Check provided feature for polygon shape type
        ccslib.CheckPolygonInput(Proposed_Modified_Features_Provided)

    # Set up zoom to for map units variable
    zoom_to_mu = False

    # Check input features for existence of features and feature type;
    # create template if Credit_Project_Boundary is not provided
    if Credit_Project_Boundary:
        # Create a local copy of the credit project boundary in case it is
        # the output of the projected input from re-running Credit Tool 1
        CPB_copy = arcpy.CopyFeatures_management(Credit_Project_Boundary,
                                                 "in_memory/CPB_provided")

        # Update message
        arcpy.AddMessage("Projecting provided feature(s) to "
                         + coordinate_system.name)
        
        # Project input to standard projection
        in_dataset = CPB_copy
        out_dataset = "Credit_Project_Boundary_Projected"
        projectedFeature = ccslib.ProjectInput(in_dataset, out_dataset,
                                               coordinate_system)

        # Update message
        arcpy.AddMessage("Determining project area - eliminating areas of non-"
                         "habitat from the Project Area")

        # Eliminate areas of non-habitat from project boundary
        Project_Area = projectedFeature
        outName = "in_memory/Credit_Project_Boundary_Clipped"
        clippedFeature = ccslib.EliminateNonHabitat(Project_Area, outName,
                                                    habitat_bounds)

        # Create Credit Project Area
        in_features = clippedFeature
        out_feature_class = CREDIT_PROJECT_AREA
        arcpy.Dissolve_management(in_features, out_feature_class)

        # Update message
        arcpy.AddMessage("Creating Map Units layer")

        # Create Map_Units layer
        in_data = clippedFeature
        out_data = MAP_UNITS
        Map_Units = ccslib.CreateMapUnits(in_data, out_data)

        zoom_to_mu = True

    if includes_anthro_mod:
        # Create a template for digitizing anthropogenic features proposed for
        # modification
        out_name = "Proposed_Modified_Features_tmp"
        Template_Features = ccslib.CreateTemplate(
            workspace, out_name, coordinate_system
            )

        # Update message
        arcpy.AddMessage("Adding fields Type and Subtype to "
                         "the Proposed_Modified_Features layer")

        # Add fields Type and Subtype
        inputFeature = Template_Features
        fieldsToAdd = ["Type", "Subtype"]
        fieldTypes = ["TEXT", "TEXT"]
        ccslib.AddFields(inputFeature, fieldsToAdd, fieldTypes,
                         copy_existing=True)

        # Set up zoom to for proposed surface disturbance variable
        zoom_to_psd = False

        if Proposed_Modified_Features_Provided:
            # Merge the template created with the provided layer, if provided
            fileList = [Proposed_Modified_Features_Provided,
                        Template_Features]
            out_name = "in_memory/tmp_Modified"
            merged_features = ccslib.MergeFeatures(fileList, out_name)

            # Rename the provided as merged (cannot merge two files with
            # equivalent filenames) as Proposed_Modified_Features
            in_data = merged_features
            out_data = PROPOSED_MODIFIED_FEATURES
            Proposed_Modified_Features = arcpy.CopyFeatures_management(
                in_data, out_data
                )

            zoom_to_psd = True

        else:
            # Save the template as Proposed_Modified_Features
            in_data = Template_Features
            out_data = PROPOSED_MODIFIED_FEATURES
            Proposed_Modified_Features = ccslib.RenameFeatureClass(
                in_data, out_data
                )

        # Clean up
        arcpy.Delete_management("Proposed_Modified_Features_tmp")

        # Add Domains to Proposed_Modified_Features layer
        featureList = [Proposed_Modified_Features]
        # Create Domain for Subtype attributes and assign to Subtype field
        ccslib.AddSubtypeDomains(featureList, workspace, AnthroAttributeTable)
        
        # Create Domain for Type attributes and assign to Type field
        typeList = [row[0] for row in arcpy.da.SearchCursor(
                    AnthroAttributeTable, "Type")]
        ccslib.AddCodedTextDomain(featureList, workspace, "Type", typeList)

        # Add layer to map for editing
        layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
        ccslib.AddToMap(Proposed_Modified_Features, layerFile, zoom_to_psd)

        if not Credit_Project_Boundary:
            # Create dummy Map Units layer if no Credit Project Boundary provided
            out_name = MAP_UNITS
            Map_Units = ccslib.CreateTemplate(workspace, out_name,
                                              coordinate_system)

            if Proposed_Modified_Features_Provided:
                # Zoom to the Modified Anthro Feature layer
                if arcpy.ListInstallations()[0] == 'arcgispro':
                    p = arcpy.mp.ArcGISProject("CURRENT")
                    m = p.activeMap
                    layer=m.Layer(PROPOSED_MODIFIED_FEATURES)
                    pass
                    # df.extent = layer.getSelectedExtent()
                else:
                    mxd = arcpy.mapping.MapDocument("CURRENT")
                    df = mxd.activeDataFrame
                    layer = arcpy.mapping.Layer(PROPOSED_MODIFIED_FEATURES)
                    df.extent = layer.getSelectedExtent()

    # Update message
    arcpy.AddMessage("Creating pre-defined map units of Wet Meadows")

    # Intersect the Map_Units layer with the NV Wet Meadows layer
    in_feature = ccsStandard.Wet_Meadows
    field_name = "Meadow"
    na_value = "No Meadow"
    ccslib.CreatePreDefinedMapUnits(Map_Units, in_feature, field_name, 
                                    na_value)
    
    # Add fields Map_Unit_ID, Map_Unit_Name, and Meadow to Map_Units
    fields = ["Map_Unit_ID", "Map_Unit_Name", "Notes"]
    fieldTypes = ["SHORT", "TEXT", "TEXT"]
    ccslib.AddFields(Map_Units, fields, fieldTypes, copy_existing=True)

    # Add Domains to Map_Units layer
    # Create Domain for Map_Unit_ID attributes
    domainName = "Map_Unit_ID"
    range_low = 0
    range_high = 10000
    ccslib.AddRangeDomain(Map_Units, workspace,
                          domainName, range_low, range_high)

    # Create Domain for Meadow attributes
    featureList = [Map_Units]
    domainName = "Meadow"
    codeList = ["No Meadow", "Altered", "Unaltered"]
    ccslib.AddCodedTextDomain(featureList, workspace, domainName, codeList,
                              assign_default=True)

    if Credit_Project_Boundary:
        # Create pre-defined map units for PJ
        # Update message
        arcpy.AddMessage("Creating pre-defined map units of PJ")

        # Intersect the Map_Units layer with the Phase III PJ layer
        in_feature = ccsStandard.PJ_Phases
        field_name = "Conifer_Phase"
        ccslib.CreatePreDefinedMapUnits(Map_Units, in_feature, field_name)

        # Remove unwanted fields from Map Units feature class
        allowable_fields = fields + ["Conifer_Phase"]
        ccslib.SimplifyFields(Map_Units, allowable_fields)

        # Add Map_Units to map
        layerFile = ccsStandard.getLayerFile("Map_Units.lyr")
        ccslib.AddToMap(Map_Units, layerFile, zoom_to_mu)

    # Clean up
    arcpy.Delete_management("in_memory")

    # Save map document
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #22
0
def main():
    # GET PARAMETER VALUES
    Proposed_Surface_Disturbance_Provided = arcpy.GetParameterAsText(0)
    Proposed_Modified_Features_Provided = arcpy.GetParameterAsText(
        1)  # optional
    Project_Folder = arcpy.GetParameterAsText(2)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Construct pathname to workspace
    workspace = arcpy.Describe(Proposed_Surface_Disturbance_Provided).path
    arcpy.AddMessage("Project geodatabase: " + workspace)

    # Instantiate a ccsStandard object
    ccsStandard = ccslib.ccsStandard(workspace, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    scratch_folder = os.path.join(arcpy.Describe(workspace).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(
            arcpy.Describe(workspace).path, 'scratch')
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE VARIABLES FOR INPUT DATA
    AnthroAttributeTable = ccsStandard.AnthroAttributeTable
    habitat_bounds = ccsStandard.HabitatBounds
    public_land = ccsStandard.Public

    # Filenames for feature classes or rasters used by this script
    PROPOSED_SURFACE_DISTURBANCE_DEBITS = "Proposed_Surface_Disturbance_Debits"
    # Filenames for feature classes or rasters created by this script
    ELIGIBLE_PROPOSED_FEATURES = "Proposed_Surface_Disturbance_Eligible"
    ANALYSIS_AREA = "Analysis_Area"
    DEBIT_PROJECT_AREA = "Debit_Project_Area"
    INDIRECT_IMPACT_AREA = "Indirect_Impact_Area"
    INDIRECT_BENEFIT_AREA = "Indirect_Benefit_Area"
    PROPOSED_MODIFIED_FEATURES = "Proposed_Modified_Features"

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

    # FUNCTION CALLS
    # Check tool version
    ccslib.CheckToolVersion()

    # Check for proposed modified features
    if not Proposed_Modified_Features_Provided:
        # Ensure Proposed_Modified_Features does not exist
        if arcpy.Exists("Proposed_Modified_Features"):
            arcpy.AddError("ERROR:: A 'Proposed_Modified_Features' layer "
                           "was detected in the project's geodatabase. "
                           "Provide the 'Proposed_Modified_Features' layer "
                           "and re-run Debit Tool 2.")
            sys.exit(0)

    # Clear selection, if present
    ccslib.ClearSelectedFeatures(Proposed_Surface_Disturbance_Provided)

    # Check Proposed_Surface_Disturbance
    feature = Proposed_Surface_Disturbance_Provided
    required_fields = ["Type", "Subtype", "Surface_Disturbance"]
    no_null_fields = required_fields
    expected_fcs = None
    ccslib.CheckPolygonInput(feature, required_fields, expected_fcs,
                             no_null_fields)

    # Update Proposed_Surface_Disturbance layer with provided layer
    provided_input = Proposed_Surface_Disturbance_Provided
    parameter_name = PROPOSED_SURFACE_DISTURBANCE_DEBITS
    Proposed_Surface_Disturbance_Debits = ccslib.AdoptParameter(
        provided_input, parameter_name, preserve_existing=False)

    # Replace Proposed_Surface_Disturbance_Debits layer on map
    layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
    ccslib.AddToMap(Proposed_Surface_Disturbance_Debits, layerFile)

    # Clip the Proposed Surface Disturbance to Public Lands
    input_features = PROPOSED_SURFACE_DISTURBANCE_DEBITS
    clip_features = public_land
    out_name = ELIGIBLE_PROPOSED_FEATURES
    Proposed_Surface_Disturbance = arcpy.Clip_analysis(input_features,
                                                       clip_features, out_name)

    # Exit if no features on public land exist
    test = arcpy.GetCount_management(Proposed_Surface_Disturbance)
    count = int(test.getOutput(0))

    if count < 1:
        arcpy.AddWarning("""
            There are no proposed features located on public lands.\n
            Therefore, this project does not require mitigation.\n
            Please confirm with the SETT.            
            """)
        sys.exit(0)

    # Add Surface_Disturbance_Eligible layer on map
    layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
    ccslib.AddToMap(Proposed_Surface_Disturbance, layerFile)

    # Add field for Disturbance_Type and populate. Values will be used in
    # Map_Units_Dissolve to identify map units of direct disturbance
    feature = Proposed_Surface_Disturbance
    fields = ["Disturbance_Type"]
    fieldTypes = ["TEXT"]
    ccslib.AddFields(feature, fields, fieldTypes)

    with arcpy.da.UpdateCursor(feature,
                               ["Surface_Disturbance"] + fields) as cursor:
        for row in cursor:
            row[1] = "Direct_" + row[0]
            cursor.updateRow(row)

    # Update message
    arcpy.AddMessage("Creating the area of indirect impact")

    # Buffer proposed surface disturbance to create Indirect_Impact_Area
    in_data = Proposed_Surface_Disturbance
    out_name = INDIRECT_IMPACT_AREA
    Indirect_Impact_Area = ccslib.CreateIndirectImpactArea(
        in_data, AnthroAttributeTable, out_name)

    if Proposed_Modified_Features_Provided:
        # Clear selection, if present
        ccslib.ClearSelectedFeatures(Proposed_Modified_Features_Provided)

        # Check provided layer
        required_fields = ["Type", "Subtype"]
        no_null_fields = required_fields
        expected_fcs = None
        ccslib.CheckPolygonInput(Proposed_Modified_Features_Provided,
                                 required_fields, expected_fcs, no_null_fields)

        # Update Proposed_Modified_Features with provided layer and add to map
        provided_input = Proposed_Modified_Features_Provided
        parameterName = PROPOSED_MODIFIED_FEATURES
        preserve_existing = False
        Proposed_Modified_Features = ccslib.AdoptParameter(
            provided_input, parameterName, preserve_existing)

        # Add Proposed Modified Features layer to map
        layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
        ccslib.AddToMap(Proposed_Modified_Features, layerFile)

        # Update message
        arcpy.AddMessage("Creating the area of indirect benefit")

        # Create the Indirect_Impact_Area
        in_data = Proposed_Modified_Features
        out_name = INDIRECT_BENEFIT_AREA
        Indirect_Benefit_Area = ccslib.CreateIndirectImpactArea(
            in_data, AnthroAttributeTable, out_name)

        # Union the indirect benefit area and the indirect impact area
        in_features = [Indirect_Impact_Area, Indirect_Benefit_Area]
        out_name = "in_memory/Impact_Union"
        Impact_Union = arcpy.Union_analysis(in_features, out_name)

        # Dissolve the unioned indirect impact and benefit areas as
        # Indirect Impact Area
        in_features = Impact_Union
        out_feature_class = INDIRECT_IMPACT_AREA
        Indirect_Impact_Area = arcpy.Dissolve_management(
            in_features, out_feature_class)

    # Update message
    arcpy.AddMessage("Determining project area - eliminating areas of non-"
                     "habitat from the Project Area")

    # Eliminate non-habitat
    project_area = Indirect_Impact_Area
    out_name = DEBIT_PROJECT_AREA
    Debit_Project_Area = ccslib.EliminateNonHabitat(project_area, out_name,
                                                    habitat_bounds)

    # Update message
    arcpy.AddMessage("Copying Debit_Project_Area as shapefile into project "
                     "folder")

    # Export feature class to shapefile in project folder so it can be sent to
    # NDOW for Dist_Lek layer
    arcpy.FeatureClassToShapefile_conversion(Debit_Project_Area,
                                             Project_Folder)

    # Update message
    arcpy.AddMessage("Creating Analysis Area")

    # Create Analysis_Area
    out_name = ANALYSIS_AREA
    Analysis_Area = ccslib.CreateAnalysisArea(Debit_Project_Area,
                                              AnthroAttributeTable, out_name)

    # Add Analysis_Area to map
    layerFile = ccsStandard.getLayerFile("Analysis_Area.lyr")
    ccslib.AddToMap(Analysis_Area, layerFile, zoom_to=True)

    # Save map document and exit
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()
Beispiel #23
0
def main():
    # GET PARAMETER VALUES
    Map_Units_Provided = arcpy.GetParameterAsText(0)
    Project_Folder = arcpy.GetParameterAsText(1)
    Project_Name = arcpy.GetParameterAsText(2)  # optional

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    arcpy.AddMessage("Python version: " + sys.version)
    # Construct pathname to workspace
    workspace = arcpy.Describe(Map_Units_Provided).path
    arcpy.AddMessage("Project geodatabase: " + workspace)

    # Instantiate a ccsStandard object
    ccsStandard = ccslib.ccsStandard(workspace, scriptPath)

    # ENVIRONMENT SETTINGS
    # Set workspaces
    arcpy.env.workspace = workspace
    scratch_folder = os.path.join(arcpy.Describe(workspace).path, 'scratch')
    if arcpy.Exists(scratch_folder):
        pass
    else:
        arcpy.CreateFolder_management(scratch_folder)
    arcpy.env.scratchWorkspace = scratch_folder
    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # DEFINE VARIABLES FOR INPUT DATA
    inputDataPath = ccsStandard.InputDataPath
    # Filenames of feature classes and rasters used by this script
    MAP_UNITS = "Map_Units"
    CURRENT_ANTHRO_FEATURES = "Current_Anthro_Features"
    # Filenames of feature classes and rasters created by this script
    MAP_UNITS_DISSOLVE = "Map_Units_Dissolve"
    CURRENT_MGMT_CAT = "Current_Mgmt_Cat"
    CURRENT_WMZ = "Current_WMZ"
    CURRENT_PMU = "Current_PMU"
    CURRENT_PRECIP = "Current_Precip"

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

    # FUNCTION CALLS
    # Check tool version
    ccslib.CheckToolVersion()

    # Check out Spatial Analyst extension
    ccslib.CheckOutSpatialAnalyst()

    # Clear selection, if present
    ccslib.ClearSelectedFeatures(Map_Units_Provided)

    # Check Map_Units layer
    feature = Map_Units_Provided
    required_fields = ["Map_Unit_ID", "Map_Unit_Name", "Meadow"]
    no_null_fields = ["Map_Unit_ID"]
    expected_fcs = [CURRENT_ANTHRO_FEATURES]
    ccslib.CheckPolygonInput(feature, required_fields, expected_fcs,
                             no_null_fields)

    # Update Map Units layer with provided layer and add to map
    Map_Units = ccslib.AdoptParameter(Map_Units_Provided,
                                      MAP_UNITS,
                                      preserve_existing=False)
    layerFile = ccsStandard.getLayerFile("Map_Units.lyr")
    ccslib.AddToMap(Map_Units, layerFile)

    # Update message
    arcpy.AddMessage("Dissolving all multi-part map units to create "
                     "Map_Units_Dissolve")

    # Dissolve Map Units
    allowable_fields = [
        "Map_Unit_ID", "Map_Unit_Name", "Meadow", "Disturbance_Type", "PJ",
        "BROTEC", "Conifer_Phase"
    ]
    out_name = MAP_UNITS_DISSOLVE
    anthro_features = CURRENT_ANTHRO_FEATURES
    Map_Units_Dissolve = ccslib.DissolveMapUnits(Map_Units, allowable_fields,
                                                 out_name, anthro_features)

    # Update message
    arcpy.AddMessage("Adding Map_Units_Dissolve to map")

    # Add layer to map document
    feature = Map_Units_Dissolve
    layerFile = ccsStandard.getLayerFile("Map_Units.lyr")
    ccslib.AddToMap(feature, layerFile)

    # Update message
    arcpy.AddMessage("Calculating area in acres for each map unit")

    # Calculate Area
    ccslib.CalcAcres(Map_Units_Dissolve)

    # Initialize a list to track proportion feature classes
    prop_fcs = []

    # Update message
    arcpy.AddMessage("Calculating Proportion within each precipitation zone")

    # Calculate Proportion of each map unit in each Precip Zone
    in_feature = os.path.join(inputDataPath, "Precip")
    out_feature_class = CURRENT_PRECIP
    field_name = "Precip_Proportion"
    ccslib.CalcProportion(Map_Units_Dissolve, in_feature, out_feature_class,
                          field_name)
    prop_fcs.append(out_feature_class)

    # Update message
    arcpy.AddMessage("Calculating Management Importance Factor")

    # Calculate Proportion of each map unit in each Management Category
    in_feature = os.path.join(inputDataPath, "Mgmt_Cat")
    out_feature_class = CURRENT_MGMT_CAT
    field_name = "Mgmt_Proportion"
    ccslib.CalcProportion(Map_Units_Dissolve, in_feature, out_feature_class,
                          field_name)
    prop_fcs.append(out_feature_class)

    # Update message
    arcpy.AddMessage("Calculating Proportion within each WAFWA Management "
                     "Zone")

    # Calculate Proportion in each map unit in each WAFWA Zone
    in_feature = os.path.join(inputDataPath, "NV_WAFWA")
    out_feature_class = CURRENT_WMZ
    field_name = "WMZ_Proportion"
    ccslib.CalcProportion(Map_Units_Dissolve, in_feature, out_feature_class,
                          field_name)
    prop_fcs.append(out_feature_class)

    # Update message
    arcpy.AddMessage("Calculating Proportion within each Priority Management "
                     "Unit")

    # Calculate Proportion in each map unit in each PMU
    in_feature = os.path.join(inputDataPath, "NV_PMU")
    out_feature_class = CURRENT_PMU
    field_name = "PMU_Proportion"
    ccslib.CalcProportion(Map_Units_Dissolve, in_feature, out_feature_class,
                          field_name)
    prop_fcs.append(out_feature_class)

    # Delete unnecessary fields in proportion feature classes
    allowable_fields = [
        "Map_Unit_ID", "Management", "Mgmt_zone", "PMU_NAME", "Precip",
        "Mgmt_Proportion", "WMZ_Proportion", "PMU_Proportion",
        "Precip_Proportion"
    ]
    for feature in prop_fcs:
        ccslib.SimplifyFields(feature, allowable_fields)

    # Set processing extent to Map_Units layer
    arcpy.env.extent = arcpy.Describe(Map_Units_Dissolve).extent

    # Calculate the average HSI values per map unit for each map unit
    HSIseasons = ccsStandard.HSISeasons
    for season in HSIseasons:
        # Update message
        arcpy.AddMessage("Summarizing " + season + " HSI")

        # Calculate zonal statistics for each map unit
        inZoneData = Map_Units_Dissolve
        inValueRaster = os.path.join(inputDataPath, season + "_HSI")
        zoneField = "Map_Unit_ID"
        outTable = "ZonalStats_" + season + "_HSI"
        ccslib.CalcZonalStats(inZoneData, zoneField, inValueRaster, outTable)

        # Join the zonal statistic to the Map Units Dissolve table
        fieldName = season + "_HSI"
        ccslib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

    # Calculate the average seasonal modifier values per map unit and join to
    # Map_Units_Dissolve layer
    terms = ccsStandard.DebitTerms
    seasons = ccsStandard.Seasons
    for term in terms:
        for season in seasons:
            # Update message
            arcpy.AddMessage("Summarizing " + term + "_Local_" + season)

            # Calculate zonal statistics for each map unit
            inZoneData = Map_Units_Dissolve
            inValueRaster = term + "_Local_" + season
            zoneField = "Map_Unit_ID"
            outTable = "ZonalStats_" + term + season
            ccslib.CalcZonalStats(inZoneData, zoneField, inValueRaster,
                                  outTable)

            # Join the zonal statistic to the Map Units Dissolve table
            fieldName = term + "_" + season
            ccslib.JoinMeanToTable(inZoneData, outTable, zoneField, fieldName)

    # Add transect field to Map_Units_Dissolve
    input_feature = Map_Units_Dissolve
    fields = ["Transects"]
    fieldTypes = ["SHORT"]
    ccslib.AddFields(input_feature, fields, fieldTypes)

    # Export data to Excel
    input_Tables = [
        MAP_UNITS_DISSOLVE, CURRENT_MGMT_CAT, CURRENT_WMZ, CURRENT_PMU,
        CURRENT_PRECIP
    ]
    for table in input_Tables:
        ccslib.ExportToExcel(table, Project_Folder, Project_Name)

    # Save map document
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        p.save()
    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        mxd.save()