[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Batch file / command for ESRI ArcMap 9.1 / 9.2 using Spatial Analyst

Posted on 2007-10-04
5
Medium Priority
?
2,057 Views
Last Modified: 2012-08-14
Hello,
 I am using ArcMap 9.1 and I would like to have a batch file that will perform operations in Spatial Analyst for me.  For example, I would like to take a bunch of rasters/arc grids and perform an spatial analyst operation on them (e.g. Raster calculator operations: (Grid_A) + (Grid_A * 10) = Grid_B, then CON([Grid_B] == 21, [Grid_B], [Grid_C])

In English: I want to take grid A and add it to grid A times 10, then use this new grid B and combine in with Grid C, but use grid B where the value = 21, otherwise use Grid C.

Basically, I don't know much about programming but I'd like to have a code that is easily modified.  I would also appreciate annotation.

 I'd like it to save each new file from the final operation with a sequential  two-digit number appended to the end (e.g. 01, 02, 75, etc)

Esri's help gives scripting examples for the specific procedures, but I still need help.
http://webhelp.esri.com/arcgisdesktop/9.2/index.cfm?TopicName=welcome

I used python to create the following script which performed the following operation and I also don't know why it works exactly, but it does. I forgot what the '.strip' does. (Its work in 9.2, but I'd like it to work in 9.1 if possible, also its using python 2.4):

CON(ISNULL(donut grid), landcovergrid, landcovergrid * -1

# Multi_Output_Map_Algebra_sample.py
# Description:
#   Runs an expression bu
# Import system modules
import sys, arcgisscripting
#import sys

# Create the Geoprocessor object
gp = arcgisscripting.create()
f = open(sys.argv[1],'r')
circlefile = open(sys.argv[2],'r')
count = 1
dir = 'c:\\temp\\'
try:
            for landcover in f.readlines():
                  donut = circlefile.readline()
                  # Set local variables
                  Outfile = dir + 'LC16_H' + `count`
                  InExpression = "CON(ISNULL(" + donut.strip() + ")," + landcover.strip() + "," + landcover.strip() + " * -1)"
                  print InExpression
                  # Check out Spatial Analyst extension license
                  gp.CheckOutExtension("Spatial")

                  # Process: MapAlgebra
                  gp.SingleOutputMapAlgebra_sa(InExpression, Outfile)

                  count = count + 1
            f.close
            circlefile.close
except:
    # If an error occurred while running a tool, then print the messages.
    print gp.GetMessages()

Thanks,
0
Comment
Question by:mgjust
  • 3
  • 2
5 Comments
 

Author Comment

by:mgjust
ID: 20017470
I ran the mentioned python file like this from the command line in windows XP:

C:\Python24\python "C:\Documents and Settings\user\Desktop\test.py" "C:\ LANDCOVERFILE.txt" "C:\DONUTFILE.txt"

Where landcover and donutfile were just lists of locations of said files.
0
 
LVL 29

Accepted Solution

by:
pepr earned 2000 total points
ID: 20019846
I know nothing about arcgisscripting module. You will probably get the answer from the GIS... zone for that.

For Python, the strip() method of the standard string removes leading and trailing whitespaces from the string. If you run Python in the interactive mode (just type Python on command line), you can try:

>>> s = '   \n\t   abc efg  \t\t\t\n'
>>> s
'   \n\t   abc efg  \t\t\t\n'
>>> s.strip()
'abc efg'

When Python reads from a text file, the line contains the \n sequence (end of line mark). It is likely that the strip() is used at least for removing that  newline sequence.

You should remove the .readlines() from the following line...
    for landcover in f.readlines():
It should look like that...
    for landcover in f:

The visible effect is the same if the read file is short. However, the former reads all the lines into the memory (as a list of lines data structure) and after all was read it loops through the list. The latter reads line by line from the file only when needed. From another point of view, the latter would process the first line of the file "immediately" even when the file is extremely big and have no other disadvantages. It is also more readable. It was not possible in older Python but it definitely works in 2.4.

For constructing the Outfile name: Firstly, I woudl recommend to add the 'name' to the identifier to make it visible that you work with the filename and not with the open file handle. Also, the 'dir' is identifier for the standard function. You should choose other identifier. You can use normal slashes in paths thus you can avoid a potential bug when you forget to double the backspace. It is also better to  get used to os.path.join() and the other companion functios for processing the filenames.

Also, do not use backticks like `count`. I believe it is even deprecated. Use standard str() function instead for conversion of integer value to the string. Or you can use formatting string effectively in some cases.

You did open the files outside the try/except construct. You should also close it outside the structe, i.e. after the except block. Notice also that you forgot to add the () after the close. This would not close the files:

...
import os
...

count = 1
tmpdir = 'c:/temp'
try:
    for landcover in f:
        donut = circlefile.readline()

        # Set local variables
        outfname = os.path.join(tmpdir, 'LC16_H', str(count))
         InExpression = "CON(ISNULL(" + donut.strip() + ")," + landcover.strip() + "," + landcover.strip() + " * -1)"
        print InExpression
        # Check out Spatial Analyst extension license
        gp.CheckOutExtension("Spatial")

        # Process: MapAlgebra
        gp.SingleOutputMapAlgebra_sa(InExpression, outfname)

        count = count + 1
except:
    # If an error occurred while running a tool, then print the messages.
    print gp.GetMessages()

f.close()
circlefile.close()


Feel free to ask.
0
 

Author Comment

by:mgjust
ID: 20024948
Whoops!  I made a mistake - I was little confused, below is what I was hoping to do.

TO clarify I have two grids of the same area for different times:
GRID A1 and A2 have the values:
1 & 2
(Grid_A1) + (Grid_A2 * 10) = Grid_B, then CON([Grid_B] == 21, [Grid_B], [Grid_C])

In English: I want to take grid A and add it to grid A times 10, then use this new grid B and combine in with Grid C, but use grid B where the value = 21, otherwise use Grid C.

I have a binary landscape and I want to 'extract' the change from landcover class 1 (year 1) to landcover class 2 (year 2) and then append this to another landcover grid. The value 21 gives me the areas that changed from 1 to 2 during this time sequence.  

The rest of my inquiry is the same.
0
 

Author Comment

by:mgjust
ID: 20052343
whats does the "in f" mean in the code?
Also what does the circle file mean?

0
 
LVL 29

Expert Comment

by:pepr
ID: 20054593
"whats does the "in f" mean in the code?"
I did not copy all the source code, just a fragment. The f is the open file object that was created by your command
                   f = open(sys.argv[1],'r')

The same holds for circlefile.
                   circlefile = open(sys.argv[2],'r')

The construct
                   for landcover in f:

means "loop over all lines in an open text file f. Each line is extracted to the variable named landcover as a string. I have no experience with your GIS. I only guess that each processed description is stored on a separarate line in the text file. Similar holds for circlefile where each line should describe one donut.

   


0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Not long ago I saw a question in the VB Script forum that I thought would not take much time. You can read that question (Question ID  (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_28455246.html)28455246) Here (http…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Suggested Courses

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question