Showing posts with label Scripting. Show all posts
Showing posts with label Scripting. Show all posts

Wednesday, June 18, 2014

Finding the Location of Your Python File

Another issue I have run into depending on the OS, is the ability to find where the python file is located that is being run.  I like the use the __file__ property, but it's not always present.  Thanks to google, I found this:

__file__ is the path name of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the path name of the shared library file.
 This means you can't always rely on os.path.dirname(__file__) to find the folder of where your python file is located.  Here is a function that has four potential checks to get the python file's folder location:


import os
def getPythonFileLocation():
    """  returns the location of where the python file is located """
    if os.path.dirname(__file__) != "":
        return os.path.dirname(__file__)
    elif os.path.dirname(os.path.abspath(__file__)) != "":
        return os.path.dirname(os.path.abspath(__file__))
    elif os.path.dirname(os.getcwd()) != "":
        return os.path.dirname(os.getcwd())
    else:
        from inspect import getsourcefile
        return os.path.dirname(os.path.abspath(getsourcefile(lambda _:None)))

The function first tries the __file__ property using the os.path.dirname() then it tries another flavor of __file__ that I found from good old stack exchange. The 3rd check uses the os.getcwd() and finally it falls back on the inspect library.

Hopefully this will help prevent 'NoneType' issues when trying to join string paths.

Enjoy

Friday, December 20, 2013

Support Python GUI Support in ArcGIS

Please support my idea on having Python GUI support in ArcGIS.

http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU

I want to get this idea to over 1000 points before the beginning of 2014, and I need your help!

Thank you

Tuesday, December 17, 2013

GPX to Feature Class

A handy tool created at 10.1, but refined at 10.2 is the GPX to Feature Class tool, which allows users to convert GPX files from GPS units to feature classes.  Waypoints and Tracks can then be extracted from the converted GPX file, and rendered as desired.

The ArcGIS online help for the GPX to Feature Class can be found here.


import arcpy
import os
if __name__ == "__main__":
    input_gpx = r"C:\data.gpx"
    convert_fc = arcpy.env.scratchGDB + os.sep + "gpxfc"
    gpx_fc = arcpy.GPXtoFeatures_conversion(Input_GPX_File=input_gpx, 
                                            Output_Feature_class=convert_fc
                                           )[0]
    track_points_lyr = arcpy.MakeFeatureLayer_management(in_features=convert_fc, 
                                                        out_layer="TRKLYR", 
                                                        where_clause="Type = 'TRKPT'", 
                                                        )[0]
    way_point_lyr = arcpy.MakeFeatureLayer_management(in_features=convert_fc, 
                                                      out_layer="WPT", 
                                                        where_clause="Type = 'WPT'", 
                                                        )[0]    

    if int(arcpy.GetCount_management(track_points_lyr)[0]) > 0:
        trkpt = arcpy.CopyFeatures_management(way_point_lyr,
                                              env.scratchGDB + os.sep + "trkpt")[0]
        trkLine = arcpy.PointsToLine_management(trkpt,
                                                env.scratchGDB + os.sep + "lines",
                                                "Name")[0]
    if int(arcpy.GetCount_management(way_point_lyr)[0]) > 0:
        waypts = arcpy.CopyFeatures_management(way_point_lyr,
                                               env.scratchGDB + os.sep + "WAYPTS")[0]
        
Here the code converted the GPX file to a feature class, then further refined the results from just a set of points to tracks and waypoints as mentioned earlier in this post.

There is a difference between 10.1 and 10.2 that should be noted.  In 10.2, more of the GPX properties will be converted where as in 10.1, I have noticed that only a small set of the data is actually pulled in from the GPX files.  So if you need all the GPX properties, ArcGIS 10.2 is probably what you need.  You can always parse the XML in the GPX manually using the minidom library in python if this doesn't suit you needs.


Enjoy


Monday, April 8, 2013

Great Learning Python Resource

Hey Everyone,

The Internet is filled with great resources for learning programming, almost too much, but here is a great resource: http://learnpythonthehardway.org/book/

This site hosts a e-book called 'Learn Python The Hard Way' and I highly recommend if you are starting out programming, or want to just a refresher course on python that you take a look.

There are also courses on C, CLI, SQL, Ruby, and Regex.

You might learn something new, so give it a try.

As always, I encourage my reader to please support my idea on the ArcGIS Ideas Site to allow GUI integration with ArcPy.  Please vote it up here: http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU

Enjoy


Thursday, February 21, 2013

Query Feature Service By Object IDs (Python)

To query a feature service using object ids, you need to perform a POST.  For those who don't know the difference between a "GET" and "POST" here is a quick blurb based on the HTML specifications:
"POST" means that former means that form data is to be encoded (by a browser) into a URL while the "GET" means that the form data is to appear within a message body. 

Even simpler, "GET" is basically for just getting data where a "POST" may involve anything, like updating data, sending, or creating data.

Using python, you can perform both "GET" and "POST" methods, but since we need a "POST" to query by IDs, here is a simple example.  Please note that most feature services limit 1000 features being returned, so if you want to grab all of the features from a feature service, you'll have to perform multiple queries to get all the features back in JSON format.

Example:


import urllib2
import urllib
import urlparse
import httplib

def query_by_objectid(url, objectIDStart=0, objectIDEnd=1001):
    """ performs a POST operation where the query is called using
        the object id method.  If a feature service has more than
        1000 records, use this method to get a range of features
        from the feature service.

        Inputs:
           :url:  - string of feature service URL
           :objectIDStart: - integer of the start whole number
           :objectIDEnd: - end range whole number
        Returns:
           returns string JSON of query
    """
    url = url + '/query'
    start = int(objectIDStart)
    end = int(objectIDEnd)

    objectIDs = ",".join([str(x) for x in range(start, end)])
    headers = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "text/plain"}
    parameters = {'objectIds' : objectIDs,
                  'f' : 'json'}
    urlparams = urllib.urlencode(parameters)
    parts = urlparse.urlparse(url)
    h = httplib.HTTPConnection(parts.netloc)
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    h.request('POST', parts.path, urlparams, headers)
    r = h.getresponse()
    return r.read()

if __name__ == "__main__":
    url = 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/TaxParcel/AssessorsLiveLayers/MapServer/1'
    print query_by_objectid(url=url,
                            objectIDStart=0,
                            objectIDEnd=5)

So we have a simple "POST" example. This sample should work with both ArcGIS Server 10.1 and ArcGIS Online feature services.

Please support my idea of having a python GUI by voting it up here.

Enjoy

Wednesday, February 13, 2013

wx GUI Article for ArcGIS

Here is an interesting article on how to create an interactive GUI for ArcGIS 10.1.

Basically what it does is it creates the form before ArcMap/Catalog finishes loading therefore the core software doesn't prevent the mainloop() to fail.  At least that's my take on it. 

If you think custom GUIs should be part of the next major release, I suggest you go to the Esri Idea site and vote up this idea.  It will need YOUR support to get into the next release.

Happy GUI designing!


Thursday, January 3, 2013

ArcPy 10.1 - Multiple Data Frames and Data Driven Pages

Data driven pages is a great way to automate map production over a given area, and it works right out of the box with a single data frame.  If you have 2 or more data frames though, you will need to control the movement of each data frame object by performing some sort of coding (ArcObjects or ArcPy).

A simple way to move multiple data frames is to:

  1. Get a list of all data frames
  2. Identify the parent data frame
  3. Move the extents of the other data frame
Sounds simple?  Well it is.

To get started, get a reference to the map document

mxd = arcpy.mapping.MapDocument("CURRENT")

Change "CURRENT"  to a path if not run in ArcMap.  Then list all the data frames

dfs = arcpy.mapping.ListDataFrames(mxd)

Now how do you know what data frame is the parent data frame or what data frame is a child data frame? Luckily at 10.1, the data driven page object provides a property called dataFrame, which returns the DataFrame object.  At 10.0, you would either use names or indexing values to determine which is the parent or not, but this example is for 10.1.

ddp = mxd.dataDrivePages
parentDF = ddp.dataFrame

Next step is to pan the other data frames to the extent of the parent data frame's extent.


for pageNum in range(1, ddp.pageCount + 1):

   for df in dfs:
      ddp.currentPageID = pageNum
      row = ddp.pageRow
      extent = row.Shape.extent
      if (df.name == parentDF.name) and (df.scale == parentDF.scale):
         print 'I found the parent frame'
      else:
         df.panToExtent(extent)
   arcpy.mapping.ExportToPNG(mxd, r"C:\Project\OutPut\ParcelAtlas_" + str(pageNum) + ".png")

Here we have a bunch of code that loops through each data driven page area and then modifies each underlying data frame that isn't the parent.  After the data frames are changes, the code then exports the maps to PNG to the '...\output' folder with reference to the page number.

Enjoy

Monday, December 17, 2012

Finding Distance Along A Line

The arcpy polyline geometry object has a very helpful method called positionAlongLine (value, {use_percentage}).  This function finds either a distance (in the feature's coordinate system) or the percentage from the line's starting location.  It then returns a PointGeometry object that can be used for further analysis, or that can be saved out as a feature class using the CopyFeatures tool.  If you use the optional use_percentages, false means it's a distance, true means it is a percentage with values between 1-100.  If a value is great than the length or over 100 % then the last point is used.  If values are less than 0 or less than 0% then the first point is used as well.

Assuming you have a line feature class, just create a search cursor and begin accessing your locations.  

fc = r"c:\temp\lines.shp" 
with da.SearchCursor(fc, ["SHAPE@"] as cursor:
    for row in cursor:
       print row[0].positionAlongLine(10, True)    
       print row[0].positionAlongLine(10, False)
Enjoy

Thursday, December 6, 2012

ArcPy Sample: Zipping a Shapefile

I've decided to post full code samples on github.  Here is my first sample to zip shapefiles.

Enjoy

Monday, December 3, 2012

Truncate Table, A New Way To Erase Rows

Truncate table is the 10.1 way to erase ALL the rows in a table or feature class.  It will ignore any sql query, so use this tool carefully.

Some Notes:

  • Supported data types are simple, meaning no terrains, topologies, etc..
  • Data must be unversioned to execute
  • After rows are removed, the data is unrecoverable, so make sure you know what you are doing before you go and use this.

This is a good tool for workflows where you need to clear out rows on some regular basis.

Usage Example:
import arcpy
from arcpy import env
wrksp = r"c:\temp\data.gdb"
env.workspace = wrksp
fcs = arcpy.ListFeatureClasses()
for fc in fcs:
   arcpy.TruncateTable_management(fc)
del fcs


Enjoy

Thursday, November 29, 2012

Walk, new arcpy.da function as 10.1 SP1

Walk is a useful function that walks directories.  Though this is an easy function to create using recursion, it is now including as a core function at 10.1 SP1 for arcpy.

The help describes the function as such:
Generate data names in a catalog tree by walking the tree top-down or bottom-up. Each directory/workspace in the tree yields a tuple of three: dirpath, dirnames, and filenames. Python's os module includes an os.walk function that can be used to walk through a directory tree and find data. os.walk is file based and does not recognize database contents such as geodatabase feature classes, tables, or rasters. arcpy.da.Walk can be used to catalog data.
 Example:

import arcpy
import os
workspace = "c:/data"
feature_classes = []
for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
                                                  datatype="FeatureClass",
                                                  type="Polygon"):
    for filename in filenames:
        feature_classes.append(os.path.join(dirpath, filename))


Enjoy

Wednesday, November 21, 2012

Shift Those Polygons at 10.1

The arcpy team at Esri has a great blog post that shows how to shift polygons using the SHAPE@XY tag.
Here is the sample:

with arcpy.da.UpdateCursor(in_features, ['SHAPE@XY']) as cursor:
        for row in cursor:
            cursor.updateRow([[row[0][0] + (x_shift or 0),
                               row[0][1] + (y_shift or 0)]])


Here we have the shape column (column 0) and to access the X and Y property, you just edit the first and second objects in the X,Y pair.  The x_shift and y_shift are float values that will move the code in one direction or another.  

It's very simple sample, but it shows how you can easily move polygons.  In the past you had to adjust each vertex, but now this is done internally thanks to the new arcpy.da module at 10.1.


Tuesday, November 20, 2012

New Geometry Tags for Cursors

At 10.1 SP1, there are 3 new tags that can be used to represent geometry objects.  Those tags are:
  • SHAPE@WKB
  • SHAPE@WKT 
  • SHAPE@JSON
The well-known binary (WKB) representation for OGC geometry. It provides a portable representation of a geometry value as a contiguous stream of bytes.  The well-known text (WKT) representation for OGC geometry. It provides a portable representation of a geometry value as a text string.  The esri JSON string representing the geometry.

Here is a simple usage example from the python window:

from arcpy import da
with da.SearchCursor("Counties", ["SHAPE@JSON", "SHAPE@WKT", "SHAPE@WKB"]) as rows:
     for r in rows:
         print r[0]
         print r[1]
         print r[2]
         break
You'll see all three types print out.  The print out doesn't really mean anything except to show the various string formats that a coder can now export the geometry object into. It will also make exporting geometries to something like a TAB or Excel table a bit more practical.  I would stay away from csv, since many of these formats use the ',' (comma) to separate the points.

Enjoy

Thursday, October 25, 2012

Using pythonaddins Messagebox

New 10.1, there is a module created for python add-ins.  It's called the pythonaddins module, and you can create a messagebox.  The messagebox object allows you to display messages to an end user.

The arcpy help can be found here.

So the messagebox can be defined as such:

MessageBox(message, title, {mb_type})

To use you just pass in a message and title as text.  The mb_type is the type of messagebox type value.  It supports the following types:

mb_type value
0
OK Only
1
OK/Cancel
2
Abort/Retry/Cancel
3
Yes/No/Cancel
4
Yes/No
5
Retry/Cancel
6
Cancel/Try Again/Continue


Complete Example:
>>> import pythonaddins
>>> result = pythonaddins.MessageBox("Press Cancel", "TITLE", 1)
>>> print result
Cancel


Simple Right!

Tuesday, October 23, 2012

Easy C++ Project for Python Use

For this tutorial, I will be using Visual Studios 2010 (C++) and Python 2.7 with ctypes.

Let's assume your boss wants a program that performs addition, there are many ways to write this code, but for the sake of this this tutorial, you want to use the python and C++.
  • Open Visual Studios
  • Follow the steps in creating a project here.
  • Give the project a name called additioncpp
  • Create a header file called 'additioncpp.h' and enter in the following code:
      int sum(int, int);
  •  In the dllmain.cpp file, comment out everything but the '#include "stdafx.h" line
  • Now we are ready to write the sum() we defined in the additioncpp.h header file.  Since python like 'C', and not 'C++' we need to use exten "C" around the functions
      #include "stdafx.h"
      #define DLLEXPORT extern "C" __declspec(dllexport)

      DLLEXPORT int sum(int a, int b) {
          return a + b;
       }

  • Compile the code and copy the .dll to a new folder
  • Create a new .py file and type in the following:
  • print 'start' 
    from ctypes import cdll
    mydll = cdll.LoadLibrary(r'PATHTODLL\additioncpp.dll')
    print mydll
    print mydll.sum
    print mydll.sum(1,2)
    print 'end'
  • You should see an output like this:
>>> 
>>> <_funcptr 0x10ca47b0="0x10ca47b0" at="at" object="object">
>>> 3
>>> end

Enjoy

Monday, September 24, 2012

Delete Rows Using the UpdateCursor - arcpy.da

The arcpy.da.UpdateCursor() provides the method to alter and update field values.  This quick post will show you how to delete a row.

All you need to do is specify the fields, here I take the default of * and the feature class.  You can reduce the number of rows by passing a query as well.

Code Sample Run From Python Window:

with da.UpdateCursor(r'C:\temp\scratch.gdb\floodsub', "*") as urows:
...     for row in urows:
...         urows.deleteRow()
...         break


This little sample just erases the first row in the feature class.  The 'with' statement automatically closes the cursor object, so it does not have to be manually deleted.  This ensures the locks are removed on success or on failure.

Enjoy

Friday, September 7, 2012

Article on 3rd Party Modules

The Esri python team wrote another good article on 3rd party modules, which is a good read for anyone who is new to python.

The article can be found here.

Enjoy

Friday, July 20, 2012

The Tile Package

What is it?
New at 10.1, tile packages are compressed files that contain a map document's cached data.  The tile package or .tpk is ideal for disconnected use and for sharing information to ArcGIS Online.
Why Should I Care?
It makes sharing cache easy, and you can create custom caches on the fly.  From a geoprocessing/application view of things, this means you can get your data out to mobile users without needing an air card.  It also produces an easy way to share cache from server to server or AGOL.

Other reasons include:
  • Improved rendering performance
  • Improved quality
  • Follows industry standards (AGOL, Google, Bing, etc..)

You can create a package using geoprocessing as follows:
import os
import arcpy
from arcpy import env
# Set environment settings
env.overwriteOutput = True
env.workspace = "C:/Tilepackages/"
# Loop through the workspace, find all the mxds and create a tile package using the same name as the mxd
for mxd in arcpy.ListFiles("*.mxd"):
    print "Packaging " + mxd
    arcpy.CreateMapTilePackage_management(mxd, "ONLINE",
                                       os.path.splitext(mxd)[0] + '.tpk',   "PNG8", "10")
Pretty easy to create.  It should be noted that your ArcMap Document's extent determines the area to be processed.  You can embed web service layers as well as local data.  The cached is fused together and it means you cannot query the base data as well.

Have packaging


Friday, June 15, 2012

Introducing the Data Access Module (arcpy.da) at 10.1

The data access module also known as arcpy.da is used to manipulate and search data.  It allows control of an edit session, faster and better cursor support, function to convert to and from numpy arrays, and supports versioning, replicas, domains, and subtypes work flows.

The data access module has the following functions:

  • ExtendTable - Joins the content of a numpy array based on a common attribute field.  This is like a table join but more flexible.
  • FeatureClassToNumPyArray - this convert a feature class to a numpy structured array
  • ListDomains - Lists the attribute domains in a geodatabase
  • ListReplicas - Lists replicas in a work space
  • ListSubtypes - returns a dictionary of subtypes for a table or feature class
  • ListVersions - list the versions in the work space
  • NumPyToFeatureClass - converts a numpy array to a point feature class
  • NumPyToTable - converts a numpy array to a table
  • TableToNumPyArray - converts a table to numpy array

The data access classes:

  • Domain - the domain object properties that describes an attribute domain
  • Editor - editor class allows use of edit sessions and operations to manage database transactions.  This means rollbacks, and better error handling!
  • InsertCursor - adds new rows to a table or feature class
  • Replica - contains properties of a replica
  • SearchCursor - read only access to a table or feature class
  • UpdateCursor - allows read/write access to a table or feature class.  This is what you use to update or delete a row.
  • Version - contains properties that describe a version.

I plan on detailing these items in future posts.

Thursday, June 14, 2012

Random Number Generator (arcpy.env)

This is a tool that creates a random number based on a seed number and an algorithm selection.
Inputs are as follows:
  1. Seed—The seed is an integer value and is used to initiate the random number generator. The default value is 0.
  2. Random Generator Type—The random generator algorithm.


    • ACM599—ACM collected algorithm 599. This is the default.
    • MERSENNE_TWISTER—Mersenne Twister mt19937.
    • STANDARD_C—Standard C Rand

So to create a random number generation environmental variable you can do it two ways:

Option 1:

from arcpy import env
env.randomGenerator = "4 MERSENNE_TWISTER"


Option 2:

from arcpy import env
env.randomGenerator = arcpy.CreateRandomValueGenerator(4, "MERSENNE_TWISTER")



To produce a random number, the easiest way is to use the arcpy.CalculateValue() and get the results from that tool.
Example:

import arcpy
arcpy.env.randomGenerator = "4 MERSENNE_TWISTER"
result = arcpy.CalculateValue_management("arcgis.rand('normal 0.0 10.0')")
randomValue = float(result.getOutput(0))
print randomValue


The code should print a random number.

It should be noted that this environmental variable will effect any tool that uses random values.

Enjoy