3

I got some good help here yesterday. I'm basically trying to set up my script in such a way that once the user just puts in the workspace in the script tool in ArcGIS the script will do the rest. I have been able to create a geodatabase and now I'm trying to run the following code and I'm having trouble. I basically need to be able to change or reset the workspace halfway through to tell it to use the newly created GDB. This is the next piece of code that I'm trying to run:

# Create Raster Dataset
out_path = "Prog.gdb"
out_name = "R_Dataset"
# Run the Create Raster Dataset Script
arcpy.CreateRasterDataset_management (out_path, out_name, "", "8_BIT_UNSIGNED", "", "1", "", "PYRAMIDS -1 NEAREST DEFAULT 75 NO_SKIP", "128 128", "LZ77", "")
# Mosaic Rasters into a the Raster Dataset
inputs = arcpy.ListRasters("", "TIF")
# Set the target to the Raster Dataset that was already created
target = "R_Dataset"
# Run the Mosaic tool
arcpy.Mosaic_management (inputs, target, "LAST", "FIRST", "", "", "NONE", "0", "NONE")

The out_path is basically referencing the GDB that was just created in the workspace folder. It's telling me that this isn't a valid input etc. I was then trying to get it to sort through to Tiffs and automatically mosaic these into the newly created raster dataset.

Any and all help greatly appreciated.

Thanks

Edit: @Aaron

Below is the entire script that I want to use, basically if I can get the user to get the workspace as a parameter the script will then do everything else. Where I'm falling short is that basically the initial (and hopefully only) workspace they define is a folder. I then want the Mosaic to New Raster to select the 4 tiffs in the original workspace folder to create a new raster in the gdb I have already created.

I think then if I could then somehow change the workspace to the gdb (as in the workspace they select + the name of the gdb I have created) it would work as everything from then on in the script happens in the gdb if that makes sense?

    # Create file Geodatabase
# Import ArcGIS modules
import arcpy, os
# Check out the ArcGIS Spatial Analyst Extension
arcpy.CheckOutExtension("spatial")
# Need to be able to OverWrite Outputs
arcpy.env.overwriteOutput = True
#Set the workspace
arcpy.env.workspace = out_folder_path = arcpy.GetParameterAsText(0)
# Set up variables)
out_name = "Prog.gdb"
# Execute CreateFileGDB
arcpy.CreateFileGDB_management(out_folder_path, out_name)
# Set local variables before importing shapefiles to Geodatabase
inFeatures =  arcpy.ListFeatureClasses()
outLocation = "Prog.gdb"
# Execute shapefile to Geodatabase
arcpy.FeatureClassToGeodatabase_conversion(inFeatures, outLocation)
# Remove _shp if it is present in feature class name
arcpy.env.workspace = os.path.join(out_folder_path, outLocation)
newFC = arcpy.ListFeatureClasses()
[arcpy.Rename_management(fc, fc.replace("_shp", "")) for fc in newFC if "_shp" in fc]
#Mosaic rasters to a new raster dataset
inputs = arcpy.ListRasters()
arcpy.env.workspace = Location = os.path.join(arcpy.env.workspace)
#Set Name
mosaic_name = "All_Mosaic.tif"
#Run the Mosaic Tool
arcpy.MosaicToNewRaster_management(inputs, Location, mosaic_name, "", "", "", 1, "", "")
#Inputs for the extract by mask tool
in_raster = "All_Mosaic.tif"
in_mask_data = "Study_area_extent"
#Extract by Mask
outExtractByMask = arcpy.sa.ExtractByMask (in_raster, in_mask_data)
# Save the output
outExtractByMask.save("T_Mask")
# Buffer the Thames feature class to create the Flood Risk Area
in_features = "Thames"
out_feature_class = "Flood_R_A"
# Run the Buffer Tool
arcpy.Buffer_analysis (in_features, out_feature_class, "300 Meters", "FULL", "ROUND", "ALL", "")
#Clip the Flood Risk Area to the Study Area Extent
# Set local variables
in_features = "Flood_R_A"
clip_features = "Study_area_extent"
out_feature_class = "Clipped_Flood_R_A"
xy_tolerance = ""
# Execute Clip
arcpy.Clip_analysis(in_features, clip_features, out_feature_class, xy_tolerance)
#Super Output Areas: Add field (this field will be used to calculate the population density of the each of the SOAs
inFeatures= "Super_Output_Areas"
arcpy.AddField_management(inFeatures, "Pop_Density", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
#Calculate field
#Set variables
inFeatures = "Super_Output_Areas"
fieldName1 = "Pop_Density"
arcpy.CalculateField_management(inFeatures, fieldName1, "!LSOA_POP! / !AreaSQKM!", "PYTHON", "")
# The Flood Risk Area and the SOA are going to be intersected in order try and find the population at risk
in_Features = (["Super_Output_Areas", "Clipped_Flood_R_A"])
intersectOutput = "Intersect"
arcpy.Intersect_analysis(in_Features, intersectOutput, "ALL", "", "INPUT")
#Add field. This will add a field to the Intersect file (intersection of SOAs and Flood Risk Area). This field will be used to calculate the population at risk.
inFeatures= "Intersect"
arcpy.AddField_management(inFeatures, "Pop_Risk", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
# Local variables:
Intersect = "Intersect"
# Process: Calculate Field
arcpy.CalculateField_management(Intersect, "Pop_Risk", "!Shape_Area! * !Pop_Density!", "PYTHON", "")
#Summary Statistics for the Total Population Effected
in_table = "Intersect"
out_table = "Pop_Risk_Sum"
stats = "SUM"
casefield = "Pop_Risk"
arcpy.Statistics_analysis(in_table, out_table, "Pop_Risk SUM", "")
# Process: Make Feature Layer
in_features = "Points_of_interest"
out_layer = "POIs_Layer"
arcpy.MakeFeatureLayer_management(in_features, out_layer, "", "", "OBJECTID OBJECTID VISIBLE NONE;Shape Shape VISIBLE NONE;CATEGORY CATEGORY VISIBLE NONE;NAME NAME VISIBLE NONE")
# Process: Select Layer By Location
in_layer = "POIs_Layer"
select_features = "Clipped_Flood_R_A"
arcpy.SelectLayerByLocation_management(in_layer, "INTERSECT", select_features, "", "NEW_SELECTION")
# Process: Copy Features
in_features = "POIs_Layer"
out_feature_class = "Copy_POI_LAYER"
arcpy.CopyFeatures_management(in_features, out_feature_class, "", "0", "0", "0")
# Process: Summary Statistics (2)
in_table = "Copy_POI_LAYER"
out_table = "POI_SUMMARY"
arcpy.Statistics_analysis(in_table, out_table, "CATEGORY COUNT", "CATEGORY")
  • 1
    Oh dear, it looks like this was converted straight from ModelBuilder. Please have a go at cleaning it up by removing extraneous comments, reducing hardcoded string values, using keyword arguments where practicable and breaking logical sections up into functions. Also a linebreak here and there won't kill you :) See this answer for some tips. – blah238 Jul 21 '13 at 22:17
  • 1
    What I think Aaron was referring to was to set your initial workspace to a variable and use os.path.join() to append the GDB name to the original workspace path and use that as input for the new raster. – Paul Jul 22 '13 at 0:39
  • @Paul What you're saying above was what I'm trying to implement but not really sure where I'm going wrong! – Dunuts Jul 22 '13 at 5:49
  • Before you call ListRasters(), you need to change the workspace back to the original (out_folder_path). Then you can can set it back to arcpy.env.workspace = os.path.join(out_folder_path, outLocation) – Paul Jul 22 '13 at 13:53
1

A couple of ideas for you. First, try and assign your workspace to an object:

env.workspace = r"C:\temp"
Dir = env.workspace

Then you can use the os module such as the os.path.join() function to manipulate your paths:

os.path.join(Dir, ...)

Second, I would consider using Mosaic To New Raster (Data Management) rather than Mosaic (Data Management). In most cases, this function leads to a cleaner script.

For example:

import arcpy, os
from arcpy import env

env.workspace = r"C:\temp"
Dir = env.workspace

# Get raster list
inputs = arcpy.ListRasters()

# Set name
mosaic_name = "mosaic.tif"

# Run the Mosaic tool
arcpy.MosaicToNewRaster_management(inputs, Dir, mosaic_name, "", "", "", 1)
  • Thanks, I am trying this but it's telling me my parameters aren't valid: Location = arcpy.env.workspace = os.path.join(arcpy.env.workspace) #Mosaic rasters to a new raster dataset inputs = arcpy.ListRasters() #Set Name mosaic_name = "Mosaic.tif" #Run the Mosaic Tool arcpy.MosaicToNewRaster_management(inputs, Location, mosaic_name, "", "", "", 1) in_raster = "Mosaic.tif" in_mask_data = "Study_area_extent" #Extract by Mask outExtractByMask = arcpy.sa.ExtractByMask (in_raster, in_mask_data) – Dunuts Jul 21 '13 at 18:03
  • Looks like that is the wrong use of os.path.join(). If you get a chance, I recommend added the entire script you are using, including your implementation of the workspace. – Aaron Jul 21 '13 at 18:46
  • I have added all my code as an edit above in my original post now. Thank you. – Dunuts Jul 21 '13 at 21:03
0

Your out path needs to have the directory path included for you geodatabase workspace.

e.g.

out_path = "C:\\temp\\Prog.gdb"

You will also include the directory path in your arcpy.ListRasters method and than run your mosaic.

  • Okay, but then that's hardcoded? Is there anyway to for the code to set the start of it so that the "c:\\temp\" part comes from the original workspace? If you understand what I mean! Thanks – Dunuts Jul 21 '13 at 13:48
  • Use os.path.dirname() and os.path.join() from the os module. Do something like this: og_ws = r"c:\temp\og.gdb". baseDir = os.path.dirname(og_ws) returns "c:\temp". then set out_path = os.path.join(baseDir, "Prog.gdb") – Nxaunxau Jul 21 '13 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.