Monday, 24 June 2013

CrossTabulate Statistics...Kappa and Chi-suqre main script

read the header to create your own tool

'''
  CrossTabulateStatistics.py

  Author:
    Dan Patterson
    Dept of Geography and Environmental Studies
    Carleton University, Ottawa, Canada
   
Dan_Patterson@carleton.ca
  Date created:  Jan 2010
  Last modified: June 2013
  Properties (right-click on the tool and specify the following
              if you are producing your own tool)
    General
    Name   Cross Tabulate Statistics
    Label  Cross Tabulate Statistics
    Desc   Allows you to cross-tabulate data within a layer or table view
           The scripts can also be extracted and used in standalone mode

  Source script CrossTabulateStatistics.py
  Parameter list
                            Parameter Properties
           Display Name          Data type        Type      Direction  MultiValue  Dependency
  argv[1]  Input table           Table view       Required  Input      No
  argv[2]  ID field              Field            Required
  argv[3]  Primary class field   Field            Required  Input      No
  argv[4]  Secondary class field Field            Required  Input      No
  argv[5]  Area field            Field            Required  Input      No

''' 
def printMessages(messages):
  '''provide a list of messages to this method'''
  for i in messages:
    print i
    arcpy.AddMessage(i)

#--------------------------------------------------------------------
#Import the basic modules
import os, sys, string 

import arcpy
import crosstab as CT


input_table  = sys.argv[1]
field_0 = sys.argv[2]
field_1 = sys.argv[3]
field_2 = sys.argv[4]
field_3 = sys.argv[5]
output_table = sys.argv[6]
if field_3 == "#":
  field_3 = "None"
 
desc = arcpy.Describe

messages = []
#Read the data and sort it since the features should be sorted on
#the point buffer ID
data = []
rows = arcpy.SearchCursor(input_table)
for row in rows:
  FID  = row.getValue(field_0)
  class_1 = row.getValue(field_1)
  class_2 = row.getValue(field_2)
  if field_3 != "None":
    area = row.getValue(field_3)
    data.append( [FID, class_1, class_2, area ] )
  else:
    data.append( [ class_1, class_2 ] )
data.sort()

#If there is an area field perform the analysis by parts
if field_3 != "None":
  N = len(data)
  unique_list = []          #records that only occur once
  dup_list = []             #records that occur more than once
  parts_list = []           #dup_list repartitioned into list of lists
  temp_list = []            #temporary handling list

  '''
  Check for recurring FID values that result from the intersection operation
  Separate into two lists for processing
  If two consecutive FIDs are not equal, add them to the unique_list
  If two consecutive FIDs are equal, begin collecting them in the dup_list
    and the temp_list.  When they are not equal again, add temp_list into
    parts_list.
  '''
  for i in range(1,len(data)):
    first = data[i-1][0]
    second = data[i][0]
    if first == second:
      if data[i-1] not in dup_list:
        dup_list.append(data[i-1])
        temp_list.append(data[i-1])
      dup_list.append(data[i])
      temp_list.append(data[i])
      if temp_list not in parts_list:
        parts_list.append(temp_list)
    else:
      temp_list = []
      if data[i-1] not in dup_list:
        unique_list.append(data[i-1])
  #check the last record
  if data[-1] not in dup_list:
    unique_list.append(data[-1])

  #Parse parts_list based upon the maximum area.  We could add the areas
  #  but this is probably not necessary unless individual buffers overlapped
  #Finally, extend unique_list using the results

  to_keep =[]
  for a_set in parts_list:   #attempts to do sums for parts.
    max_area = 0.0
    if len(a_set) == 2:
      area_0 = a_set[0][3]
      area_1 = a_set[1][3]
      if a_set[0][0:3] == a_set[1][0:3]:
        current_area = area_0 + area_1
        max_piece = a_set[0]
        max_piece[3] = current_area
      elif area_0 >= area_1:
        max_piece = a_set[0]
      else:
        max_piece = a_set[1]
    else:
      for i in range(1, len(a_set)):
        area_0 = a_set[i-1][3]
        area_1 = a_set[i][3]
        if a_set[i-1][0:3] == a_set[i][0:3]:
          current_area = area_0 + area_1
          max_piece = a_set[i-1]
          max_piece[3] = current_area
        else:
          if area_0 >= area_1:
            max_piece = a_set[i-1]
            max_area = max([max_area, area_0])
            max_piece[3] = max_area
          else:
            max_piece = a_set[i]
            max_area = max([max_area, area_1])
            max_piece[3] = max_area
    to_keep.append(max_piece)
   
  unique_list.extend(to_keep)
  unique_list.sort()

  #print the messages
  ##printMessages(messages)

  #Parse the data, determine the crosstabulation and perform the Kappa statistics
  data = []
  for i in range(len(unique_list)):
    data.append(unique_list[i][1:3])

#Perform the calculations using the original data or the area-balanced data
 
result_1 = CT.kappa_results(data)

print result_1
arcpy.AddMessage(result_1)

result_2 = CT.chi_results(data)
print result_2
arcpy.AddMessage(result_2)

messages = result_1 + result_2
if output_table != "#":
  try:
    outFile = open(output_table,'w')
    outFile.write(messages)
    arcpy.AddMessage("\nOutput text file created: " + str(output_table))
  except:
    arcpy.AddMessage("Unable to create text file")
  outFile.flush()
  outFile.close()

del input_table
del arcpy

No comments:

Post a Comment