Tuesday, July 10, 2012

Insert Cursor (arcpy.da) at 10.1

The insert cursor, just like the old insert cursor object, is used to write a new row to an existing table.  When using the InserCursor object you must tell the cursor object what type of geometry you will be using.  So if your feature class is a point feature class, use "SHAPE@XY" but if it's a polygon or polyline, use "SHAPE@".  It should be noted that "SHAPE@" is valid for point features as well.

The InsertCursor has one function called insertRow(), which is a list object with field values in it.

Table Examples:

from arcpy import da
with da.InsertCursor(fc, ["name"]) as cursor:
   cursor.insertRow(["BOB SMITH"])

Feature Class Example (Point):

from arcpy import da
with da.InsertCursor(fc, ["name", "SHAPE@"]) as cursor:
   cursor.insertRow(["A Point",(-77, 34)])



Feature Class Example (Line):

from arcpy import da

array = arcpy.Array([arcpy.Point(-77, 34),
                     arcpy.Point(-77.1, 34.1),
                     arcpy.Point(-77.2, 34.2)])
polyline = arcpy.Polyline(array)

with da.InsertCursor(fc, ["name", "SHAPE@"]) as cursor:
   cursor.insertRow(["A Line", polyline])
Feature Class Example (Polygon):

from arcpy import da

array = arcpy.Array([arcpy.Point(-77, 34),
                     arcpy.Point(-77, 34.1),
                     arcpy.Point(-77.2, 34.1),
                     arcpy.Point(-77, 34)])
pg = arcpy.Polygon(array)

with da.InsertCursor(fc, ["name", "SHAPE@"]) as cursor:
   cursor.insertRow(["Polygon", pg])

Enjoy

Monday, July 9, 2012

Setup WING IDE for ArcPy 10.1

I've changed python IDE to WING.  It's a very nice IDE, but it took sometime getting use to from pydev's eclipse add on.

Here is the basic setup of WING IDE with PyLint:

1. Download easy_install: http://pypi.python.org/pypi/setuptools/#windows
2. Install easy_install
3. Go to the install location of Python 2.7.x and run 'easy_install pylint'
4. Install WING IDE
5. Start WING IDE
6. Select Tools -> PyLint
7. Right click on the PyLint window and select 'configure'
8. Edit the 'command =' to be 'command = C:\Python27\ArcGIS10.1\Scripts\pylint.bat'
9. Run pylint on a .py file

* if you get an error, try adding the full path to the python.exe in the pylint.bat file.

Enjoy

Tuesday, June 26, 2012

Introduction to the Update Cursor (arcpy.da) at 10.1

The UpdateCursor creates a read-write access to records returned from a feature class or table.
Returns an iterator of lists. The order of values in the list matches the order of fields specified by the field_names argument.  UpdateCursor objects can be iterated using a for loop and it supports with statements. Using a with statement will ensure that the database locks are removed.


You can use both an insert and update cursor at the same time if an edit session is opened.

Example:

from arcpy import da
fc = r"c:\temp\samples.gdb\nests"
fields = ('BirdPop', 'Rank')

with da.UpdateCursor(fc, fields) as cursor:
    for row in cursor:
        if (row[0] >= 0 and row[0] <= 10):
            row[1] = 1
        elif (row[0] > 10 and row[0] <= 20):
            row[1] = 2
        elif (row[0] > 20 and row[0]<= 30):
            row[1] = 3
        elif (row[0] > 20):
            row[1] = 4
        cursor.updateRow(row)

In this simple example, you see that you can use conditional statements to change values within the 'with' statement.

Enjoy

Friday, June 22, 2012

ArcGIS API for Silveright 3.0 Released

I like Silverlight as a programming language, and now the ArcGIS API for Silveright is released.  You can check out the announcement here.

Enjoy

Wednesday, June 20, 2012

Working with BLOB data at 10.1 (arcpy.da)

Reading and writing BLOB data has always been an issue previous to 10.1, but now it's not a problem.  A reader pointed out that fact the other day, so I thought why not point this out to everyone.
From the help (source: resourcebeta.arcgis.com):
A BLOB is data stored as a long sequence of binary numbers. ArcGIS stores annotation and dimensions as BLOBs, and items such as images, multimedia, or bits of code can be stored in this type of field. You can use a cursor to load or view the contents of a BLOB field.
In Python, BLOB fields can accept strings, bytearray, and memoryviews. When reading BLOB fields, a memoryview object is returned.
So what does this mean to you.  We'll it's time to store those documents, pictures from vacation, and videos with geo tags in a spatial database.

Writing Blobs :
from arcpy import da

myFile = open(r"c:\temp\image.jpg",'rb').read()

with da.InsertCursor(r"c:\temp\demo.gdb\table",['blobFieldname','fileName']) as cursor:
   cursor.insertRow([myFile,'image.jpg'])


Reading Blobs:

from arcpy import da
import os
with da.SearchCursor(r"c:\temp\demo.gdb\table",['blobFieldname','fileName']) as cursor:
   for row in cursor:
      binaryRep = row[0]
      fileName = row[1]
      # save to disk
      open(r"c:\saveFolder" + os.sep + fileName, 'wb').write(binaryRep.tobytes())
      del row
      del binaryRep
      del fileName



Writing and reading Blob fields involves using the python built in open().  This function can open up files in various modes, but ensure that the method used are the binary modes 'rb' (read binary) and 'wb' (write binary), or else this process will not work.  You can essentially open up any file as a Blob, so stick whatever you want in there, but realize that this can balloon the size of your database up greatly.  It does however open up a whole new host of ways of transporting file based data.  Off the top of my head, I can image how this could improve data transport for local parallel processing methods of spatial and non-spatial data.

Enjoy

Tuesday, June 19, 2012

SearchCursor (arcpy.da) 10.1 Continued

The new cursor objects contain a very helpful property called fields.  This property returns a tuple of field names defined in the field_names argument.  This means that if you pass "*" for all fields you can then get the associated field to the associated value.

Remember, cursor objects will ignore BLOB and Raster fields.

Example:
import arcpy
from arcpy import da
fc = r"c:\temp\demo_polygon.shp"
with da.SearchCursor(fc,"*") as rows:
   for field in rows.fields:
      print field


So in this example, the cursor will print all the fields being accessed.  It will also show the type of Shape field is being returned.  If all fields is used ("*"), then the SHAPE@XY property returned by default.

Enjoy

Monday, June 18, 2012

10.1 SearchCursor (arcpy.da)

The Search Cursor object creates read-only access to the records in a feature class or table.  It will return an iterator of tuples.  The order of values matches the order of fields mentioned by the field_names argument.

When comparing the old search cursor to the new search cursor, functionally they are basically the same, except the data access module is better, stronger, and faster. It's like the Six Million Dollar Man of upgrades in ArcPy.

Looking at the inputs:
SearchCursor (in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause})


The two biggest differences between arcpy.SearchCursor and arcpy.da.SearchCursor, is the field_names is required, and the optional parameter explode_to_points.


Paramter field_names can be "*", which means all fields, but it does exclude BLOB and raster fields.  This is required because you should only be returning what you need.  The other interesting aspect of the is the way you can obtain geometry and other field information using the @.

  • SHAPE@XY —A tuple of the feature's centroid x,y coordinates
  • SHAPE@TRUECENTROID —A tuple of the feature's true centroid x,y coordinates
  • SHAPE@X —A double of the feature's x-coordinate
  • SHAPE@Y —A double of the feature's y-coordinate
  • SHAPE@Z —A double of the feature's z-coordinate
  • SHAPE@M —A double of the feature's m-value
  • SHAPE@ —A geometry object for the feature
  • SHAPE@AREA —A double of the feature's area
  • SHAPE@LENGTH —A double of the feature's length
  • OID@ —The value of the ObjectID field

The parameter explode_to_points is a boolean value.  If you specify the value to true, it will explode multi-geometry values into there own rows.  This means if you have a 5 multipoint geometry object, it will have 5 rows instead of 1.

Example: Basic Use
import arcpy
fc = r"c:\temp\wells.shp"
fields = ["WELL_ID","TYPE","SHAPE@XY"]
with arcpy.da.SearchCursor(fc,fields) as cursor:
   for row in cursor:
      print "{0}, {1}, {2}".format(row[0],row[1],row[2])

So here we have just a simple read-only example where the user will pass in a feature class and the fields needed to query.  It will print the information out on the screen.  Notice the usage of the with statement.  This is great because it automatically cleans up the cursor object.  This means no more del statements and help reduce the number of cursor locks on data.

Enjoy