MGLPhase2p.py

Giovanni Manghi, 2012-08-12 04:11 PM

Download (10.7 KB)

 
1
# MGLPhase2.py
2
# Created on: Wed Oct 7 2009 09:35:35 AM
3
#   by William Perry & Robert Lugo
4
# Usage: MGLPhase2  <Input_folder> <Output_folder> <Extent>
5
# Description: Master python script for second phase of the MGL model
6
# This program does;
7
# 1. Creates a surface with genetic values and values of 0 for areas outside of species range but within total analysis extent for each species
8
# 2. Creates a surface with values of 1 for each cell with a genetic value, 0 for other cells in analysis extent
9
# 3. Sum of all genetic values created in step 1.
10
# 4. Sum of counts created in step 2.
11
# 5. Divide step 3 layer by step 4 layer to get the average of all species
12
# 6. Calculate the variance using this equation: s^2 = (sum of x^2 - ((sum of x)^2/n)/n-1, where
13
#         s^2 = variance
14
#         x = input genetic values (from the individual species genetic grids)
15
#         n= number of input values (from the result of step 4)
16
# 7. Clean up files
17
#
18
# Parameter list
19
#                                Parameter Properties
20
#           Display Name         Data type        Type      Direction  MultiValue
21
#  argv[1]  Input folder         Folder           Required  Input      No
22
#  argv[2]  Output folder        Folder           Required  Input      No
23
#  argv[3]  Extent grid          Grid             Required  Input      No
24

    
25
# Import system modules
26
import sys, string, os, arcgisscripting
27

    
28
# Create the Geoprocessor object
29
gp = arcgisscripting.create(9.3)
30

    
31
# set variables
32
inFolder = sys.argv[1]
33
outFolder = sys.argv[2]
34
outExtent = sys.argv[3]
35

    
36
# Check out any necessary licenses
37
gp.CheckOutExtension("spatial")
38

    
39
############################### future code to implement
40
#try:
41
##       gp.CheckOutExtension("spatial")
42
#    else:
43
#        raise "LicenseError"
44

    
45
    #gp.Workspace = "D:/GrosMorne"
46
    #gp.HillShade_sa("WesternBrook", "westbrook_hill", 300)
47
    #gp.Aspect_sa("WesternBrook", "westbrook_aspect")
48
    #gp.CheckInExtension("spatial")
49

    
50
#except "LicenseError":
51
#    print "Spatial Analyst license is unavailable"  
52
#except:
53
#    print gp.GetMessages(2)
54
###############################
55

    
56
# Load required toolboxes...
57

    
58
ArcGISHome = os.environ["ARCGISHOME"]
59
Toolpath = ArcGISHome + "ArcToolbox\\Toolboxes\\Spatial Analyst Tools.tbx"
60
print Toolpath
61
gp.AddToolbox(Toolpath)
62

    
63
# Set the Geoprocessing environment...
64

    
65
# set the analysis extent 
66
gp.extent = outExtent
67
#gp.extent = 'c:/files/gis/mglmodel/tooldata/ecogridarea'
68

    
69
# select directory to look in 
70
gp.Workspace = inFolder
71

    
72
Outpath = outFolder    # select directory to write to
73

    
74
### Step 1. Reads in the genetic surfaces and changes the null values to 0 for areas 
75
###         outside of species range but within total analysis extent
76

    
77
gp.Addmessage("Changing Null values to zeros...")
78

    
79
# Get a list of grids in the workspace.
80
rasters = gp.ListRasters("", "GRID")
81

    
82
# create a variable to count the number of grids
83
x = 0
84

    
85
for raster in rasters:
86
    # loop through rows and process data....
87
    print "selected grid for calculations is " + raster
88
    
89
    # Local variables...
90
    #out_grid = fc[:13] #only use the first 13 characters
91
    temp05 = Outpath + "/" + raster + "_0"
92
    #temp05 = Outpath + "/" + raster + "_0"          
93
    gp.SingleOutputMapAlgebra_sa("con(isnull(" + raster + " ), 0 , " + raster + ")", temp05, "")
94
    x = x + 1 
95
    
96
### Step 2. Creates a surface with values of 1 for each cell with a genetic value, 
97
###         0 for other cells in analysis extent
98

    
99
gp.Addmessage("Changing Genetic values to ones...")
100

    
101
# Get a list of grids in the workspace.
102
rasters = gp.ListRasters("", "GRID")
103

    
104
for raster in rasters:
105
    # loop through rows and process data....
106
    print "selected grid for calculations is - " + raster
107

    
108
    # Local variables...
109
    temp05 = Outpath +  "/" + raster + "_1"
110
               
111
    #gp.SingleOutputMapAlgebra_sa("con(isnull(" + raster + " ), 0 , " + raster + ")", temp05, "")
112
    gp.SingleOutputMapAlgebra_sa("con(isnull(" + raster + " ), 0 , 1)", temp05, "")
113
    
114
### Step 3. Sum of all genetic values created in step 1
115

    
116
# now need to switch the workspace to the outfolder   
117
gp.Workspace = outFolder 
118

    
119
# Get a list of grids in the workspace.
120
rasters = gp.ListRasters("*_0", "GRID")
121

    
122
# Local variables...
123
theString = ""
124

    
125
#out_grid = fc[:13] #only use the first 13 characters
126

    
127
gp.Addmessage("Adding all the genetic grids...")
128

    
129
for raster in rasters:
130
    # loop through rows and process data....
131
    theString = theString + str(raster) + ", "       
132
     
133
theString = theString.rstrip(", ")
134
print theString
135
    
136
try:
137
    Output = "allsumgv"
138
    InExpression = "Sum(" + theString + ")"
139
    gp.SingleOutputMapAlgebra_sa(InExpression, Output, theString)
140
    
141
except:
142
    print "exception:"
143
    print gp.GetMessages(2)    
144

    
145
# now we need to square the sum of all grids from SumAllGeneticValues.py, AllSumGV.
146
try:
147
    Inraster = 'allsumgv'
148
    temp06 = "allsumgvsq"
149
    #temp06 = Outpath + "/" + "AllSumGVSq"
150
    # Process: Square
151
    gp.Square_sa(Inraster, temp06)   
152

    
153
except:
154
    print "exception:"
155
    print gp.GetMessages(2)  
156
    
157
### Step 4. Sum of counts created in step 2.
158

    
159
# Get a list of grids in the workspace.
160
rasters = gp.ListRasters("*_1", "GRID")
161

    
162
# Local variables...
163
theString = ""
164

    
165
#out_grid = fc[:13] #only use the first 13 characters
166

    
167
gp.Addmessage("Adding all the count grids...")
168

    
169
for raster in rasters:
170
    # loop through rows and process data....
171
    print "selected grid for calculations is " + raster
172
    theString = theString + str(raster) + ", "       
173
    
174
theString = theString.rstrip(", ")
175
print theString
176
    
177
try:
178
    Output = "allcountgv"
179
    InExpression = "Sum(" + theString + ")"
180
    gp.SingleOutputMapAlgebra_sa(InExpression, Output, theString)  
181
    
182
except:
183
    print "exception:"
184
    print gp.GetMessages(2)    
185

    
186
    
187
### Step 5. Divide step 3 layer by step 4 layer to get the average of all species   
188
## 
189
# The first step is to take all the single species genetic divergence surfaces and square them, then sum them.
190

    
191
# Get a list of grids in the workspace. The '_0' grids contain 0 instead of null values.
192
rasters = gp.ListRasters("*_0", "GRID")
193

    
194
theString = ""
195

    
196
gp.Addmessage("Squaring all the genetic values grids, then adding them...")
197

    
198
# loop through rows and process data....
199
for raster in rasters:
200
    
201
    # Local variables...
202
    temp05 = raster[:-2] + "_2"   # here we are stripping off the '_0' and replacing with '_2' to indicated a squared grid.
203
    # Process: Square
204
    gp.Square_sa(raster, temp05)          
205
     
206
# Now get a list of squared grids in the workspace and add them together.
207
rasters2 = gp.ListRasters("*_2", "GRID")
208

    
209
gp.Addmessage("Adding all the squared genetic values grids...")
210

    
211
for raster in rasters2:
212
    # loop through rows and process data....
213
    print "selected grid for calculations is " + raster
214
    theString = theString + str(raster) + ", "    # builds expression of raster names separated by commas.     
215
    
216
theString = theString.rstrip(", ")
217
print theString
218

    
219
try:
220
    Output = "allsqsumgv"
221
    InExpression = "Sum(" + theString + ")"
222
    gp.SingleOutputMapAlgebra_sa(InExpression, Output, theString)
223
    
224
except:
225
    print "exception:"
226
    print gp.GetMessages(2)    
227
      
228
print    
229
print "Finished"
230
print "Number of Grids Processed: " + str(x)
231

    
232
# Next we need to change all the zero values in allcountgv back to null and remove all the grid cells with count < 2.
233

    
234
try:    
235
    # Set local variables
236
    InRaster = "allcountgv"
237
    OutRaster = "allcountgvn"        
238

    
239
    # Process: SetNull
240
    gp.SetNull_sa(InRaster, InRaster, OutRaster, "Value < 2")
241

    
242
except:
243
    # If an error occurred while running a tool, then print the messages.
244
    print gp.GetMessages()
245

    
246
gp.Addmessage("Creating average genetic value grid...")
247
    
248
try:
249
    # Set the input raster dataset
250
    inputRaster1 = "allsumgv"
251
    inputRaster2 = "allcountgvn"
252

    
253
    # Set the output raster name
254
    outputRaster = "average"
255
    
256
    # Process: Divide
257
    gp.Divide_sa(inputRaster1, inputRaster2, outputRaster)
258

    
259
except:
260
    # If an error occurred while running a tool, then print the messages.
261
    gp.AddMessage("Failed to create raster: " + outputRaster)   
262
    
263
### Step 6. Calculate the variance using this equation: s^2 = (sum of x^2 - ((sum of x)^2/n)/n-1, where
264
##         s^2 = variance
265
##         x = input genetic values (from the individual species genetic grids)
266
##         n= number of input values (from the result of step 4)
267
    
268
# Now we need to build a single output Map Algebra expression for the variance equation below;    
269
#Gvariance = ([allsqsumgv] - ([allsumgvsq] / [allcountgvn])) / ([allcountgvn] - 1)    
270
  
271
gp.Addmessage("Creating genetic variance grid...")  
272

    
273
try:
274
# Set the input raster dataset
275
    inputRaster1 = "AllSumGVsq"
276
    inputRaster2 = "AllCountGVn"
277

    
278
    # Set the output raster name
279
    outputRaster = "SumCntDivGV"
280

    
281
    # Process: Divide
282
    gp.Divide_sa(inputRaster1, inputRaster2, outputRaster)    
283
    
284
    inputRaster3 = "Allsqsumgv"
285
    inputRaster4 = outputRaster
286
    
287
    #set the output raster
288
    outputRaster2 = "AminusB"
289
    
290
    # Process: Minus
291
    gp.Minus_sa(inputRaster3, inputRaster4, outputRaster2)
292

    
293
    inputRaster5 = "allcountgvn"
294
    
295
    outputRaster3 = "MinusCount"
296
    
297
    # Process: Minus
298
    gp.Minus_sa(inputRaster5, 1, outputRaster3)
299
    
300
    FinalOutput = "variance"
301
    
302
    # Process: Divide
303
    gp.Divide_sa(outputRaster2, outputRaster3, FinalOutput)
304
    
305
    
306
except:
307
    print "exception:"
308
    print gp.GetMessages(2)    
309

    
310
### Step 7. Clean up and delete all the temporary grids from the Output folder
311

    
312
# first we need to copy the average and variance grids to another directory
313

    
314
gp.workspace = Outpath
315
gp.Addmessage("Cleaning up and removing temporary files....")
316
average_n = Outpath + "\\FinalResults\\average"
317
if gp.Exists(average_n):
318
    gp.delete_management(Outpath + "\\FinalResults\\average")
319

    
320
variance_n = Outpath + "\\FinalResults\\variance"
321
if gp.Exists(variance_n):
322
    gp.delete_management(Outpath + "\\FinalResults\\variance")
323

    
324
Final_n = Outpath + "\\FinalResults"
325
if gp.Exists(Final_n):
326
    gp.delete_management(Outpath + "\\FinalResults")
327

    
328
output_folder = "FinalResults"    
329
gp.CreateFolder_management(Outpath, output_folder)    
330
gp.copy_management("average", Outpath + "\\FinalResults\\average")   
331
gp.copy_management("variance", Outpath + "\\FinalResults\\variance")
332
gp.copy_management("allcountgv", Outpath + "\\FinalResults\\sumcount")
333

    
334
rasters = gp.ListRasters("", "GRID")
335

    
336
for raster in rasters:
337
    # loop through and delete data....
338
    print "deleting raster... " + raster
339
          
340
    gp.delete_management(raster)
341
   
342