Monday, September 16, 2013

Table to Excel (10.2 Arcpy)

Table to excel is a great tool for converting your spatial data into an excel spreadsheet.  In the past, before 10.2, you would have to use a 3rd party module like Python Excel in order to convert your data to and from ArcGIS tables to excel spreadsheets.

It should be noted that this only support the MS Excel 5.0/95 format (.xls) file type.

The syntax and use is pretty simple for this tool, it has 4 inputs, the table path (string), out path (string), use field alias (Boolean and optional), and use domain and sub-type description (Boolean and optional).  Let's dive into an example:

import arcpy
import os
if __name__ == '__main__':
    table = r"c:\temp\scratch.gdb\StarbucksAddresses"
    out_excel = r"c:\temp\starbucks.xls"
    if os.path.isfile(out_excel):
        os.remove(out_excel)
    arcpy.TableToExcel_conversion(table, out_excel)

All we have done here is taken the simplest example and convert my list of Starbucks locations and converted to an excel spreadsheet so I can now use it in excel.

Enjoy

ArcGIS Tool help link - http://resources.arcgis.com/en/help/main/10.2/index.html#/Table_To_Excel/001200000054000000/


Friday, September 13, 2013

Excel to Table (10.2) Tool

New at ArcGIS 10.2 is the Excel to Table tool.. This tool is found under the conversion toolbox, and it a quick way to easily convert your Excel Workbooks (.xlsx files) and MS Excel 5.0/95 Workbook (.xls files) into geodatabase tables.
  • Supports xlsx and xls file extensions
  • First row is considered the field names, and can be renamed so a valid table is generated
  • It assumes that each field contains uniform data types and the data is not mixed
ExcelToTable() takes the following inputs:
  1. Input_Excel_File - MS Office Excel file path 
  2. Output_table - export table name and path
  3. Sheet (optional) - Name of the sheet to export.  If none is provide the 1st sheet will be exported
Sample:

import arcpy
from arcpy import env
if __name__ == '__main__':
    env.overwriteOutput = True
    xls_file = r"c:\temp\somedata.xls"  # supports xlsx and xls
    dest_gdb = env.scratchGDB
    arcpy.ExcelToTable_conversion(xls_file,
                        os.path.join(dest_gdb, "sheet"))

Pretty easy.  The biggest advantage I see with this tool is if you are in an environment where you cannot install 3rd party modules like xlrd.

Enjoy

Wednesday, September 11, 2013

ArcGIS 10.2 Help Documentation

With the release of 10.2, it is important to know where you can find help.  The product documents can be found here (http://pro.arcgis.com/documentation/).

Enjoy

Thursday, August 22, 2013

Creating a SQlite database via 10.2 ArcPy

At ArcGIS 10.2, there is not support for SQLite database, according to Wikipedia is described as follows:

is a relational database management system contained in a small (~350 KB) C programming library. In contrast to other database management systems, SQLite is not a separate process that is accessed from the client application, but an integral part of it.
To create a SQLite database, use the CreateSQLiteDatabase().
 
import arcpy
# Set local variables
sqlite_database_path = 'C:/Data/Counties.sqlite'
# Execute CreateSQLiteDatabase
arcpy.gp.CreateSQLiteDatabase(sqlite_database_path, "ST_GEOMETRY")

It's not too hard.  All file paths must end in '.sqlite' extension.  The database supports two spatial types: "ST_GEOMETRY" or "SPATIALITE".  ST_GEOMETRY is Esri's storage type, whereas SPATIALITE is the SpatiaLite geometry type.  ST_GEOMETRY is the default geometry storage type.

This database can be fully used with the python sqlite3 module that comes as a default with any python installation.  This means you can create a database using ArcPy, then perform all updates through native SQL instead of update/insert cursors.

Some notes:

  • ":memory:" stored databases are not supported, they must be written to disk
  • SQLite version 3.16.2


Enjoy

Tuesday, August 6, 2013

Hurricane RSS Feeds

The National Hurricane Center has created two very helpful feeds for those who want to know the latest GIS hurricane data:

  • Atlantic Feed: http://www.nhc.noaa.gov/gis-at.xml
  • Pacific Feed: http://www.nhc.noaa.gov/gis-ep.xml
Each feed contains a wealth of information that can be parsed out:

  • Graphical Tropical Weather Outlook [shp]
  • 120h Wind Speed Probabilities (34kt, 50kt, 64kt) [shp] [kml]
  • Advisory Summary Information [xml]
  • Advisory Forecast Track [shp] [kml]
  • Advisory Cone of Uncertainty [shp] [kml]
  • Advisory Watches & Warnings [shp] [kml]
  • Advisory Wind Field [shp]
  • Preliminary Best Track [shp] [kml] & Wind Swath [shp]
  • Storm Surge (Probabilities, Exceedance) [shp] [kml]
shp means shapefile (in zip files) and kml is keyhole markup language (google format). 

This is a great improvement over the old way of trying to automate pulling data from the National Hurricane Center's website.  Hopefully next year they will improve these feeds by offering JSON or GeoJSON formats like the USGS has for new real time Earthquake data.



Friday, July 26, 2013

Always Tip Well Because...

Always tip that pizza driver well, because you never know if they are a GIS major or not.  Besides being funny, this is a very interesting ArcGIS Online map.  It shows concentrations of pizza consumption in the college town of Shippenburg, PA.  It also allows people in that town to see how much your neighbors are tipping.  Better tip well, you do not want to be the cheap guy on the block.

http://www.arcgis.com/home/item.html?id=f86568bc807b49cd86e437194ccd2bca

I wonder if the map creator is the driver and if now he will get more tips!

Enjoy

Wednesday, July 24, 2013

Python Add-Ins and Tkinter

ArcGIS for Desktop does not support any python GUIs out of the box, but let's say we want to have a form pop-up anyway. As shown below


One way to do this is to create a wx python instance at start up, which is create before the desktop python loop is created.  You would then reference the wx loop instead of the ArcGIS python loop.. but it's complicated...  You can also see tons of forum posts like this, that describe how the in process causes python to crash with GUIs: http://gis.stackexchange.com/questions/36848/crashing-arcgis-10-1-add-ins-using-multiprocessing

Let's assume though you want to use Tkinter because it's core, it comes with the python install.  Tkinter is the out of the box GUI that comes with python, and if you want to learn more about it, you can check it out here.  

Since ArcGIS for Desktop runs python add-ins 'in process'.  We cannot use multiprocessing or subprocessing to launch another instance python and display the code.  This is essentially the thing hindering python GUI development in the 10.x framework.  To get around this issue, code must be executed out of process.  Luckily for python people, we can create toolboxes and reference those toolboxes through the ImportToolbox().  Toolboxes allow you to run code 'out of process', which means multiprocessing!  Pretty sweet.

Let's take a look at the code to generate the form:
import Tkinter
from Tkinter import *
import multiprocessing
import sys, os
import arcpy
def show_form():

    root =Tk()
    root.title('Button')
    Label(text='I am a button').pack(pady=15)

    #button are labels that react to mouse and keyboard events.
    #in this case the button is packed to be at the bottom of the root or
    #toplevel widget.

    Button( text='Button') .pack(side=BOTTOM)
    root.mainloop()
    
if __name__ == "__main__":
    pythonExe = os.path.join(sys.exec_prefix, 'python.exe')
    multiprocessing.set_executable(pythonExe)
    multiprocessing.freeze_support = True
    jobs = []
    pool = multiprocessing.Pool(1)
    jobs.append(pool.apply_async(show_form,[]))
    pool.close()
    pool.join()
    del pool
    del jobs
    arcpy.SetParameterAsText(0, True)   


Now that we have the code to create the form, create a new python toolbox. Add this script and make sure you UNCHECK 'Run python script in process'

Next create your python add-in toolbar and add a button.  Copy the python script and toolbox from above into your 'install' folder.  Begin editing the python add-in script as follows:
import arcpy
import pythonaddins
import os
class btnShowForm(object):
    """Implementation for tkinterTester_addin.button (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
    def onClick(self):
        tbx = arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "scripts.tbx"))
        tbx.showform() # name of script in toolbox is showform

Finally all you have to do is create the .esriaddin file. Just double click on the makeaddin.py and install the addin.

When you run the add-in from ArcMap, you should see a pop-up appear.  Pretty cool!  The one down side is that ArcPy needs to reload, so it can cause a slight delay in showing the form.


Enjoy

Also, if you want Python GUI support in ArcGIS for Desktop, please vote up this (http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU).