TitlePages

Showing posts with label arcpy. Show all posts
Showing posts with label arcpy. Show all posts

Wednesday, 24 December 2014

ArcGIS Python Mapping Module


Arc Python to interact with Arc-map

What is ArcPy Mapping and Why is it actually used for :

Arcpy.mapping was built for the professional GIS analyst (as well as for developers). Traditionally, the scenarios listed above had to be done using ArcObjects and it often proved to be a very difficult programming environment to learn for the average GIS professional. Arcpy.mapping is a courser-grained object model, meaning that the functions are designed in a way that a single arcpy.mapping function can replace many lines of ArcObjects code. The following is a very simple example of how arcpy.mapping can be used to reference an existing map document and export it to a PDF document with only two lines of code.

To explore the Overall Arcpy mapping Module use the following PDF:

Arcpy Python Mapping Module


Code for Getting the reference to the MXD :

YourMXD= arcpy.mapping.MapDocument("path to the MXD")

To export the above MXD to PDF using arcpy:

arcpy.mapping.ExportToPdf(YourMXD,"your pdf file")



Get Reference to the Current Arcmap
Pointer to a MXD present on the Disk


Map Layout Document in the Arc map
Layout View of the Map Document

Arcpy.mapping is not a replacement for ArcObjects but rather an alternative for the different scenarios it supports. ArcObjects is still necessary for finer-grain development and application customization, whereas arcpy.mapping is intended for automating the contents of existing map documents and layer files.



Exporting the feature class to CSV Format


Exporting Geodatabase toComma Separated Value Format

Let start creating an python addin for converting the feature class in your geodatabase to CSV format.So that everyone can understand your feature class and its values.
  • If you are very new to python addin then go through- How to start with python addin 
  • The input feature class and output csv file path are hard coded in the sample program
  • For dynamic conversion get the path of the files through a variable and pass it as a parameter to the defined functions
Comma Seperated values
CSV Fromat



def ex_fc_to_csv(fc, out_csv):
    """
    Export all vertex in a line or poly feature class to a csv with OID
   
    example

        import geom_snippets
        geom_snippets.ex_fc_to_csv(r"c:\proj\fc1.shp", r"c:\proj\fc1.csv")

    output csv looks like this

        1,56019.99998067904,69118.00001450378
        1,56159.99998080942,69026.0000144181
        1,56359.999980995686,68913.00001431286
        2,34985.00002508866,68936.00001433428
        2,35178.000025268404,68805.00001421227

    """
    import csv
    import json

    with open(out_csv, 'w') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',', lineterminator='\n')

        with arcpy.da.SearchCursor(fc,
                                   field_names=("OID@","SHAPE@JSON")) as cursor:
            for row in cursor:
                geom = json.loads(row[1])
                for path in geom['paths']:
                    for pt in path:
                        csvwriter.writerow([row[0]] + pt)

Friday, 12 December 2014

How to create a simple python add-in tool for ArcGIS Desktop

How to create a simple python add-in for ArcGIS Desktop


TOOL USED:  Python Add-in Assistant

WORKING OF THE TOOL:
Creating a Simple python add-in assistant for ArcGIS Desktop to add a Fishnet table to the ArcMap using the python
Type of Python Add-in: Tool Type
Function: At the end of drawing a rectangle on the ArcMap a fishnet with specified rows and columns should appear on the Screen
A python add-in tool is very similar to a button. But, a tool requires user to interact with the map application based on that interaction some business logic will get executed. The Zoom In tool Description: Zoom In in ArcMap will be a great example, when the user draws a rectangle on the ArcMap ,then the map will be redrawn with that rectangle as an extent.
Below steps will help you to create both Toolbox as well as a Tool on it

PROCEDURE:
Steps to Create a Toolbar for your Tool:
1.     To create your own toolbar. Open the Add-n assistant and Go to Add-in Contents tab and give the information about the add-in which you are going to create.
Note: A tool can reside on a Toolbar but cannot sits on a Menu
2.     Click the Add-In Contents tab and begin declaring your add-in customizations. A tool can reside on a toolbar but not on a menu. See creating an add-in toolbar for more detailed procedure.
3.     To Create the tool on your new Toolbar
Right-click the new toolbar and choose New Tool on the right click Menu.
Python addin assistant window

At once you have finished giving out the information and details about the add-in. Click on Save button at the bottom of the wizard. All the necessary files and folders will get created within the working folder of your add-in assistant.
Now it is the time to work on the main code. Go to the python script located on the install folder and open it using your Python idle. Code will appear as shown below with the class name same as your button name.
Note: Do not change the button name as it is directly linked with the button and registered in the your Config.xml file

 
Onclick() methof of the addin button class
The Onclick () method shown on idle will get executed on when the user click on the tool . But I our case the fishnet should get created whenever the user draw the tool is selected and draw an rectangle on the Map. So to do that OnRectangle () method of the python add-in will comes in to Picture. Replace on click method with OnRectangle () method as shown below:


Fishnet content added to On Rectangle method


·         The code will check for any preexistence of fishnet on the memory using the Exist() Method and deletes if anyone is already there using the Delete_Management() function.
·         CreateFishnet_management is the core function which is going to do the actual work after supply all the necessary parameters to it
·         Refresh the active view to redraw the Map and return the path of the fishnet to the calling function.







How to check for condition in Geoprocessing Service or Model Builder

How to check for if/else conditions in Geoprocessing Service


TOOL USED:  
Arc python and Script tool
Python script will be deployed in the ARC Toolbox to create the Conversion Tool 

WORKING OF THE TOOL:
Script tool is created in the ArcMap and the required input & Output Parameter are set. The script tool source is set to the custom python code present in an Python file(.py)
Out motive is to use check for the count of a features in an feature class and performing an conditional Execution

PROCEDURE:
  • Open ArcMap 10.0+ 
  • Create your own Geometric Network or Open your Existing Geometric Network
  • Add your Geometric network to the Table of contents in the ArcMap as Shown Below


·         Create a new Model in your myToolBox .Right Click on MyToolBox > New > Model.Following window will appear on the Screen 







  •    Add your desired feature class to the Model. (Right Click on any empty space and select ADD DATA  and select your feature class in the object browser)
  • ·         Add Get Count and Calculate value Model from the System Toolbox Connect the model as shown below 






  • ·         Now open calculate value Model and in the Expression Textbox call the function Calculate(%RowCount%)
  • ·         Here %RowCount% will act as an Inline Variable and Compiler automatically replace the %RowCount% with the value of the rowcount field
  • ·         At the Code block defined the function Calculate as

def calculate(row):
if row>0:
return true
else:
return false
  • ·         Make the return Data type as Boolean
  • ·         The output Boolean can be set as a precondition for any model. So that the Model  get executes only when the output of calculate value is true






How to create Graphical User Interface in Arcpy

To Show GUI in your Script tool of your ArcMap



Python consist of  huge number of GUI frameworks (or toolkits) available for it, from TkInter to a number of other cross-platform solutions.

In your case we going to use the default TkInter Module to access the windows form from the python script tool.
TkInter is being proposed as the most interactive and easy to program module in Python GUI framework

1. Create a new Script tool in the Arcmap's ArcCatalog window in your desired location
2. Copy the below codes in to a notepad file and save it as python .py extension
3.Go to the script tool and Right Click > Properties > Parameter
4.Browse to your newly created python code as the source file to execute
5.All is well.Start GUI python from TkInter. Happy Programming




from Tkinter import *
import datetime
from array import *



root = Tk()
logo = PhotoImage(file="Image.Gif")
w2 = Label(root,
           image=logo).grid(row=0,column=1)
explanation = """Team Geo Zoner"""
w2 = Label(root, 
          compound = CENTER,
           fg="Red",
           bg="black",
           font="Times 55 bold",
          text=explanation)
w2.grid(row=0,column=0)

p=str(datetime.datetime.now().isoformat())
texter="Your Heading Goes Here"+str(p);
w3 = Label(root, 
          compound = CENTER,
           fg="Green",
           font="Times 20 bold",
          text=texter)
w3.grid(row=1,column=0)

Parameters = ['Number of Inputs','Number of Ouputs','Number of Processing Parameters','Number of Intermediate data']

r = 2
i=1
for c in Parameters:
    Label(text=c, relief=RIDGE,width=25).grid(row=r,column=0)
    Entry(text="Value", relief=SUNKEN,width=10).grid(row=r,column=1)
    r = r + 1
    i = i + 1

root.title("GISSTUDY")
root.mainloop()

Thursday, 11 December 2014

Performance issues on ArcGIS Geoprocessing Service

How to improve Geo-processing Execution Speed

Geoprocessing services hosted in the ArcGIS server needs to be pretty fast and accurate. User will always want the service to be the fastest. Since ArcGIS Server will be able to service multiple users at one instant of time, inefficient services can overload your server and increase the processing time. The more efficient and intelligent your services, the more users can be serviced with the same computing resources at a smaller amount of time.

Below are some of the tips and techniques that helps in increasing the performance of your Geo-processing Services.

Use local paths to data and resources

The more faster the data requires to be processed is accessible by the server the more faster your service will be.It is good to copy your data to the server rather than placing it on the shared location and asking the server to access it.(Copying the server will be effective only if the Geo processing input data is very small in size and also when the input data is not dynamic)
Reading data from the local area network will be slow compared to accessing the data from the local disk.. 


Reading and Writing the Intermediate data IN_Memory


The service execution speed will get increased by multiple times when the intermediate data is allowed to stored in the machine memory(RAM).Input and output operation is the slowest of all the computing operations.In Geoprocessing storing the intermediate data in a file geodatabase or personnel Geodatabase will take maximum of the execution time.
Please be sure the data which your are storing in the memory as an intermediate data need not be necessary after the execution is complete.Because once the execution is complete the data in the memory will get cleared.Don't write large amount of data to the in_memory as it may affect the performance of the processing service.
To write to your computer's memory, use the pathname in_memory, as follows:
          in_memory\your featureclassname




Use layers from a source map document

If a service uses a source map document instead of feature classes and datasets, it will tremendously increase the performance of the service.Your models and scripts can use map layers from the source map document so that it will impose less load on the processor and significantly decrease the execution time. A layer references a dataset on disk or feature class on a geodatabase, and some layers cache properties about the dataset. Therefore by using dataset layer instead of the direct dsataset or feature class,there is a performance advantage because ArcMap opens the dataset once, caches basic properties of the dataset, and keeps the dataset open. When the Service executes, the dataset need not to be  reopened because the source map document already it is opened and it will gives us a performance boost.


Write data to shapefiles

Storing the data to shapefiles is a bit faster than writing to other formats but writing data to memory, described above, is the fastest of all. Even then there is further more limitations on the shapefiles such field names should be  as 10 character , no null values, and limited support for date/time, to name a few. This become more helpful if the you are running your model locally on your Desktop

Friday, 21 November 2014

Working with Group layers through Python


Working with Group layers through Python


 This tool will be helpful in accessing the Trace Managaement Results
TOOL USED:  arcpy.mapping
Python script will be deployed in the ARC Toolbox to create the Conversion Tool
WORKING OF THE TOOL:
This tool will iterate through each layer in the group layer and perform operation on each layer for every iterations
PROCEDURE:
·         Create a New Script tool in your toolbox of your ArcCatalog
·         Set any empty python code file as source file in which you are going to write your script
·         Set Output layer as input parameter and group layers as the data Type
·         Copy the following code into your python code file


import arcpy
from arcpy import env
arcpy.env.overwriteOutput=1
outputgrouplayer=arcpy.GetParameter(0)

#Assign the output group layer to a variable, to be used later
lyrs =outputgrouplayer

print lyrs
#Create a Mapping Layer out of the Group Layer
groupLayer = arcpy.mapping.Layer(lyrs)

#Get a list of all the mappping layers, the first return will be the Group Layer itself
newLyrs = arcpy.mapping.ListLayers(groupLayer)

#Iterate through all of the Layers (mapping layers)
for lyr in newLyrs:
    #Because the first return is the group layer itself, we check for this, and move on
    if not lyr.isGroupLayer:
        print "Layer name is: {0}. Count is: {1}.".format(lyr.name, str(arcpy.GetCount_management(lyr)))
  • This will print the layer name and count of feature for every layer in the Group layer inputted
  •  Run the script tool and target your group layer as the input in the parameter box. Click on Ok
  • Now it is Party time. Happy Coding

Thursday, 20 November 2014

Feature Count using Model Builder

Software Required:
  1. ArcMap 10.2 or more


Procedure:
  • Open ArcMap 10.2+ 
  • Goto Window > Show ArcCatalog
  • ArcCatalog Right Click on the Default GeoDatabase and Create New Feature Class.Give a name for the new feature class and Click Finish
  • Add a New Model to the Database New > Model Tool after creating a New ToolBox
  • Add Get Count and Calculate Value to the New Model
  • Set GetCount Ouput Value as  the Precondition for Calculate Value
  • Add the following procedure for the Calculate value Model






Expression

CountMe(%RowCount%)

Code Block
def CountMe(n):
  if n > 0: 
     return "true" 
  else: 
     return "false"



The Output of the Calculate Value Model is Boolean(True or False).Setting the output value of Calculate Value as the Precondition for the desired Model will make it model to run only when the output is True