Spatial treatment

From DreamsteepWiki

Jump to: navigation, search

try:
  #import relevant modules, create geoprocessing dispatch object
  import win32com.client
  gp = win32com.client.Dispatch("esriGeoprocessing.gpDispatch.1")

except:
  print 'WARN NO ESRI SUPPORT FROM CURRENT SHELL '
  
#import relevant modules, create geoprocessing dispatch object
#import win32com.client, sys, traceback
#gp = win32com.client.Dispatch("esriGeoprocessing.gpDispatch.1")

import sys,os
import sys_strings

import sys_arclink_ATTRS
import sys_gm_batcher
import sys_kernel


import sys_file_io

#################





"""
ESRI METHODS

ProjectRaster
Usage: ProjectRaster <in_raster> <out_raster> <out_coor_system> {NEAREST | BILINEAR | CUBIC} {cell_size}

Project
Usage: Project <in_dataset> <out_dataset> <out_coor_system> {transform_method;transform_method...}



"""



def AddPrintMessage(msg, severity):
    print msg
    if severity == 0: gp.AddMessage(msg)
    elif severity == 1: gp.AddWarning(msg)
    elif severity == 2: gp.AddError(msg)


####.......######   ####.......######  ####.......######   ####.......######
####.......######   ####.......######  ####.......######   ####.......######
"""
NOTES

# Set the workspace. List all of the polygon feature classes that
# start with 'G'
GP.Workspace= "D:/St_Johns/data.mdb"
fcs = GP.ListFeatureClasses("G*","polygon")

"""


####.......######   ####.......######  ####.......######   ####.......######
"""
class GETINFO

getSpatRef(file) ----> return the esri spatial refernece object
readPRJ     ---->
getunits
listSpatialReference
listAllDataSets
getRasterResolution
getRasterMeanCellHeight
getRasterBandCount
getCentroid
getLengthXY
getEXTNTS( rasterdataset ): #returns :  float [ MIN_X ,MIN_Y ,MAX_X ,MAX_Y ]
getDataClassType
getDataClassInfo
getRasterInfo


"""





####.......######   ####.......######  ####.......######   ####.......######
####.......######   ####.......######  ####.......######   ####.......######

class GET_INFO :

  def getSpatRef (self,gisdata):
     desc = gp.Describe(gisdata)
     SR   = desc.SpatialReference
     return SR

  def readPRJ (self,prjfile):
     PRJTEXT= sys_file_io.PARSE_GIS_PRJ( prjfile)
     #print PRJTEXT
     return PRJTEXT
     
  def getunits (self,prjfile):
     PRJTEXT= self.readPRJ(prjfile)
     print PRJTEXT[0][17] #?

  def listSpatialReference(self,gisfile):
     SR = self.getSpatRef(gisfile)
     print '############################'
     print 'FILENAME IS '+gisfile
     print 'SPATIAL REFERENCE DATA '
     #
     print SR.Type

     #exclusive to projection ype
     if SR.Type=='Unknown':
        print 'error Unknown Type DEBUG '
        #return None
     
     if SR.Type=='Projected':
        print 'HAS PROJECTED COORDINATES '
        print SR.LinearUnitName
        
     if SR.Type=='Geographic':
        print 'HAS GEOGRAPHIC  COORDINATES '
        print SR.AngularUnitName
     
     #common
     print SR.Domain
     print SR.ZDomain
     print SR.MDomain
     print SR.HasMPrecision
     print SR.HasXYPrecision
     print SR.HasZPrecision
     print SR.FalseOriginAndUnits
     print SR.MFalseOriginAndUnits
     print SR.ZFalseOriginAndUnits

     #print SR.Classification
     print SR.Abbreviation
     print SR.Remarks
     print '############################'

  ##############################
  #ESRI DOES NOT SUPPORT DEM , USE GMBATCHER.INFO  FOR THAT
  ####.......######   ####.......######  ####.......######   ####.......######
  def listAllDataSets(self,folder,datatype):
    #print featurepath
    gp.Workspace =folder

    #gp.ListRasters()
    #p.ListFeatureClasses()
    #gp.ListTables()
    outnodes = []
    ####.......######
    if datatype=='dataset':
      datanodes = gp.ListDatasets()
      datanodes.reset()
      datanode = datanodes.next()
      while datanode:
        outnodes.append(datanode)
        datanode = datanodes.next()
      return outnodes
      
    ####.......######
    if datatype=='raster':
      datanodes = gp.ListRasters()
      datanodes.reset()
      datanode = datanodes.next()
      while datanode: # While the feature class name is not None
        outnodes.append(datanode)
        datanode = datanodes.next()
      return outnodes
    ####.......######
    if datatype=='vector':
      datanodes = gp.ListFeatureClasses()
      datanodes.reset()
      datanode = datanodes.next()
      while datanode: # While the feature class name is not None
        outnodes.append(datanode)
        datanode = datanodes.next()
      return outnodes
      
    ####.......######
     #DEM NOT SUPPORTED USE GMBATCHERS INFO COMMAND FOR THAT

    ####.......######
    
    
  ####.......######   ####.......######  ####.......######   ####.......######
  def getRasterResolution(self,rasterdataset ):
      infomem = self.getRasterInfo(rasterdataset)
      return[infomem[4],infomem[5]]
      ##....##....##....##....##
  def getRasterMeanCellHeight(self,rasterdataset ):
      infomem = self.getRasterInfo(rasterdataset)
      return[infomem[2],infomem[3]]
      ##....##....##....##....##
  def getRasterBandCount(self,rasterdataset ):
      infomem = self.getRasterInfo(rasterdataset)
      return infomem[0]
      ##....##....##....##....##
      
      
  ####.......######   ####.......######  ####.......######   ####.......######
  #returns centroid [X ,Y] of a gis dataset
  def getCentroid(self,dataset ):
      BBOX = self.getEXTNTS(dataset)
      #print 'DEBUG BBEBOX IS '
      #print BBOX
      LENX= (BBOX[2] - BBOX[0])
      LENY= (BBOX[3] - BBOX[1])
      HALFX = LENX/2
      HALFY = LENY/2
      CEX   = BBOX[2]- HALFX #MAX X - .5 LENGTH
      CEY   = BBOX[3]- HALFY #MAX Y - .5 LENGTH
      
      return[CEX,CEY]
  ####.......######   ####.......######  ####.......######   ####.......######
  #returns length [X ,Y] of a gis dataset
  def getLengthXY(self,dataset ):
      BBOX = self.getEXTNTS(dataset)
      LENX= (BBOX[2] - BBOX[0])
      LENY= (BBOX[3] - BBOX[1])
      return[LENX,LENY]

  ####.......######   ####.......######  ####.......######   ####.......######
  
   #returns :  float [ MIN_X ,MIN_Y ,MAX_X ,MAX_Y ]
  def getEXTNTS(self,rasterdataset ):
      desc = gp.describe(rasterdataset)
      XTNT = desc.Extent
      TOKER=  XTNT.split(' ')
      OUTVAR = []
      OUTVAR.append( float(TOKER[0]) )
      OUTVAR.append( float(TOKER[1]) )
      OUTVAR.append( float(TOKER[2]) )
      OUTVAR.append( float(TOKER[3]) )
      return OUTVAR

  ####.......######   ####.......######  ####.......######   ####.......######
  #IS IT A RASTER OR VECTOR? , ETC
  #need to add in arcrasters, dems , etc
  def getDataClassType(self,dataset):
      #if dataset == 'folder':
         #check for w001001.adf
         
      desc = gp.describe(dataset)
      return desc.DataSetType

  ####.......######   ####.......######  ####.......######   ####.......######
  #COMMON ATTRIBUTES FOR ALL GIS DATA
  def getDataClassInfo(self,dataset):
      desc = gp.describe(dataset)
      print '############################'
      print 'FILENAME IS '+dataset
      print 'DATA CLASS INFO  \n'
      ##
      print 'DATASET TYPE       '+ str( desc.DataSetType )
      print 'EXTENTS            '+ str( desc.Extent )
      CENTROID =  self.getCentroid(dataset)
      LENGTHXY =  self.getLengthXY(dataset)
      print 'CENTROID            '+ str( CENTROID )
      print 'LENGTHXY            '+ str( LENGTHXY )

  ####.......######   ####.......######  ####.......######   ####.......######
  def getFeatureInfo(self,featuredataset ):
      desc = gp.describe(featuredataset)
      print 'FILENAME IS '+featuredataset
      print 'FEATURE CLASS INFO  \n'
      
      print 'DATASET TYPE         '+ str( desc.DatasetType )
      print 'HASM                 '+ str( desc.HasM )
      print 'HASZ                 '+ str( desc.HasZ )
      print 'HAS SPATIAL INDEX    '+ str( desc.HasSpatialIndex )


  ####.......######   ####.......######  ####.......######   ####.......######
  """
  returns raster band properties
  if a multiband dataset is specified than use the first band in the image and assume all bands are the same
  (can be used to tell if a dataset is multiband or not )
  """
  def getRasterInfo(self,rasterdataset ):
      desc = gp.describe(rasterdataset)
      OUTINFO = []
      QUIET   = 1 #TOGGLE FOR SCREEN OUTPUT
      #########################################
      BANDCOUNT = desc.BandCount
      
      if desc.BandCount ==1:
        if QUIET ==0:
           print 'DATASET IS SINGLE 8bit RASTER BAND '
        desciber = desc
      #/Band_1
      if desc.BandCount >1:
        if QUIET ==0:
           print '##..##..##..##..##..##..##..##..##..##..##..##..##'
           print 'DATASET CONTAINS MULTIPLE ('+str(desc.BandCount)+') 8bit RASTER BANDS '
           print 'USING FIRST BAND IN QUERY  '
        descband = gp.describe( (rasterdataset+'/Band_1') )
        desciber =  descband
      #################################################
      #print '##..##..##..##..##..##..##..##..##..##..##..##..##'
      if QUIET ==0:
        print 'FILENAME IS '+rasterdataset
        #################count starts here
        print 'BANDCOUNT            '+ str( BANDCOUNT )
        print 'IS INTEGER           '+ str( desciber.isInteger )
        print 'MEAN CELL HEIGHT     '+ str( desciber.MeanCellHeight )
        print 'MEAN CELL WIDTH      '+ str( desciber.MeanCellWidth )
        print 'WIDTH                '+ str( desciber.Width )
        print 'HEIGHT               '+ str( desciber.Height )
        print 'PIXEL TYPE           '+ str( desciber.PixelType ) #depth u8 = 8bit
        print 'NO DATA VALUE        '+ str( desciber.NoDataValue )
        print 'TABLE TYPE           '+ str( desciber.TableType )
        print '\n'
      ############################################
      OUTINFO.append(  BANDCOUNT  )
      OUTINFO.append(  desciber.isInteger   )
      OUTINFO.append(  desciber.MeanCellHeight   )
      OUTINFO.append(  desciber.MeanCellWidth   )
      OUTINFO.append(  desciber.Width   )
      OUTINFO.append(  desciber.Height  )
      OUTINFO.append(  desciber.PixelType  )
      OUTINFO.append(  desciber.NoDataValue  )
      OUTINFO.append(  desciber.TableType  )
      ########
      return OUTINFO


  ####.......######   ####.......######  ####.......######   ####.......######
  def getSHPType(self,feature):
    desc = gp.describe(feature)
    datatype=  desc.ShapeType
    output =[]

    if (datatype =='Polygon'):
      output.append('Polygon')
    if (datatype =='Point'):
      output.append('Point')
    if (datatype =='Polyline'):
      output.append('Polyline')
    return output

    ####.......######   ####.......######  ####.......######   ####.......######
  def listAttrs(self,feature):
      fcs = gp.ListFields(feature)     #sys.argv[1]

      fcs.reset()
      fc = fcs.next()
      print 'GETTING ATTRIBUTES (FIELDS) FOR NODE '+str(feature) +'\n'
      outarray = []
      
      while fc:
        array =[]
        #print '## ## ## ## \n'
        #print 'Name      ' +str(fc.Name     )
        array.append( str(fc.Name ) )
        #  pri  nt 'AliasName ' +str(fc.AliasName)
        #print 'Domain    ' +str(fc.Domain   )
        array.append( str(fc.Domain  ) )
        #print 'Editable  ' +str(fc.Editable )
        array.append( str(fc.Editable ) )
        #  print 'HasIndex  ' +str(fc.HasIndex )  #?? wont work
        #print 'Length    ' +str(fc.Length   )
        array.append( str(fc.Length ) )
        #print 'Type      ' +str(fc.Type     )
        array.append( str(fc.Type ) )
        #print 'Scale     ' +str(fc.Scale    )
        array.append( str(fc.Scale ) )
        outarray.append(array)
        ##
        fc = fcs.next()
      #
      return outarray
      
    ####.......######   ####.......######  ####.......######   ####.......######


    ####.......######   ####.......######  ####.......######   ####.......######


###############################################################################
#INFO = GET_INFO()
#INFO.getRasterInfo('C:/data/biggestcrop.tif')
#INFO.getFeatureInfo('C:/data_/shape/ClayShoot5_2007.shp')
#print INFO.getRasterResolution('C:/data/biggestcrop.tif')
#print INFO.getCentroid('C:/data/biggestcrop.tif')
#print INFO.getLengthXY('C:/data/biggestcrop.tif')



"""
## #ESRI_ATTR_EDIT
# filter_layers
# addAttr
# getFCtype
# readAttrs
# getAttrs

# #

"""
#####
"""
##SPATIAL RELATED & MORE ##
# #GET_INFO
desc
getSHPType
listAttrs

#??
getSpatReff
#? setSpatReff?




# #
"""
#####
"""
S_TREATMENT
getprojection
makeprojection from
batchreproject


"""

####.......######   ####.......######  ####.......######   ####.......######


#Define Projection: sets the projection information for a dataset.
#DefineProjection <in_dataset> <coordinate_system>


"""
Projections and Transformations Toolset
Contains tools to set the projection as well as reproject or transform a dataset.
..Define Projection: sets the projection information for a dataset.
DefineProjection <in_dataset> <coordinate_system>
Feature (Projections and Transformations) Toolset
Contains tools to convert a geographic dataset from one coordinate system to another.
..Batch Project: changes the coordinate system of one or more feature classes including
the datum or spheroid.
BatchProject <input_feature_class_or_dataset;
input_feature_class_or_dataset...> <output_workspace>
{output_coordinate_system} {template_dataset} {transformation}
Create Spatial Reference: creates spatial reference and domains.
CreateSpatialReference {spatial_reference} {spatial_reference_template}
{xy_domain} {z_domain} {m_domain} {template;template...} {expand_ratio}
..Project: changes the coordinate system of a feature class including its datum or spheroid.
Project <in_dataset> <out_dataset> <out_coordinate_system>
{transform_method;transform_method...}


"""



"""
RASTER
..Flip: flips a raster dataset along a horizontal axis.
Flip <in_raster> <out_raster>
..Mirror: fllips a raster dataset along the vertical axis.
Mirror <in_raster> <out_raster>
..Project Raster: converts a raster dataset between two coordinate systems.
ProjectRaster <in_raster> <out_raster> <out_coordinate_system>
{NEAREST | BILINEAR | CUBIC} {cell_size}
..Rescale: scales a raster by the specified x and y scale factors.
Rescale <in_raster> <out_raster> <x_scale> <y_scale>
..Rotate: rotates a raster dataset around a specified point by a specified angle.
Rotate <in_raster> <out_raster> <angle> {pivot_point} {NEAREST | BILINEAR |
CUBIC}
..Shift: shifts a raster by the specified x and y shift values.
Shift <in_raster> <out_raster> <x_value> <y_value> {in_snap_raster}
..Warp: transforms or rubber sheets a raster dataset along a set of links using a polynomial
transformation.
Warp <in_raster> <source_control_points;source_control_points...>
<target_control_points;target_control_points...> <out_raster> {POLYORDER1 |
POLYORDER2 | POLYORDER3} {NEAREST | BILINEAR | CUBIC}


"""

"""
Define Projection: sets the projection information for a dataset.
DefineProjection <in_dataset> <coordinate_system>




"""
#############

"""
EXAMPLE GMBATCHER

foogm = GM_BATCH('C:/base.prj','ee')
foogm.IMPORT_GEOTIFF('sexxy')
foogm.EXPORT_PNG_CROP()
foogm.show_output()
foogm.write_output('C:/test.txt')

"""
GLOB  = sys_kernel.sys_globals()
#globalvar.setuserpath('/staff') #THIS DETERMINES ALL WORKSPACES!!!
globalvars = GLOB.get()

####.......######   ####.......######  ####.......######   ####.......######
"""
PROJECTIONS AND On-The-Fly) CONVERSIONS OF ANY TYPE DATA

HANDLES ALL GEOMETRIC / PROJECTION RELATED ISSUES
FOR FIELD MANIPUTALTION USE arclink_ATTRS


"""


class SP_TREATMENT:
   ####
   #sys_gm_batcher
   
   def __init__(self):
        self.PROJECTION    = ''
        self.INPUTFOLDER   = ''
        self.FEATURES      = [] #VECTOR / ATTR TABLES
        self.RASTERS       = [] #ELEVATION
        ##############
        self.POINTS        = []
        self.LINES         = []
        self.POLYS         = []
        ###############
        if os.path.lexists( (globalvars[2]+ '/base.prj') )==0:
           raise 'NO VALID PROJECTION '
        self.GMBATCHER     = sys_gm_batcher.GM_BATCH( globalvars[2]+ '/base.prj','nullattr')
        
   def dumpmemory(self):
        print '######################'
        print self.PROJECTION
        print self.INPUTFOLDER
        print self.FEATURES       #VECTOR / ATTR TABLES
        print self.RASTERS        #ELEVATION
        print self.POINTS
        print self.LINES
        print self.POLYS

   ####.......######   ####....
   #PROJECTION INTERFACE
   ####.......######   ####....
   #BOTH ARCGIS AND GM_
   #def GM_
   ##############################
   #report projection of data
   def getprojection(self,data):
      pass
   ##########################
   #def sortdata(self):
   #  pass
     
   ##########################
   """

   """
   
   def sortdata(self):
     pass
     
   def clearalldata(self):
   
     pass
   ##########################
   #return spatial reference
   def getspatialreference (self,filename):
      desc = gp.describe(filename)
      SR = desc.SpatialReference
      del desc  #? debug
      return SR


   #report spatial reference
   def showspatialreference (self,filename):
      desc = gp.describe(filename)
      SR = desc.SpatialReference
      print '###############################'
      print SR.Type #Projected
      print SR.Name
      print SR.Domain
      print SR.Domain

      del desc  #? debug
   ##########################
   #define a projection
   def defineprojection(self,mode):
      #modes = 'createFromExisting',' ??'
      pass
   ####.......######   ####....
   #create a new projection
   def makeprojection(self,mode):
      #modes = 'createFromExisting',' ??'
      pass
      
   #save projection to disk
   def saveprojection(self,data):
      pass
   #load projection from disk
   def loadprojection(self,data):
      pass
   ####.......######   ####....
   #reporject to another
   def reproject(self,feature1,feature2):
      #modes = 'createFromExisting',' ??'
      pass
   ####.......######   ####....
   def batchReproject(self,mode):
      #modes = 'createFromExisting',' ??'
      pass
      
   ####.......######   ####....
   ####.......######   ####....
   
   
   ####.......######   ####....
   #GEOMETRY INTERFACE
   ####.......######   ####....


   def copyfeatures(self):
     #CopyFeatures <in_features> <out_feature_class> {configuration_keyword}
     #{spatial_grid_1} {spatial_grid_2} {spatial_grid_3}
     pass
   ####.......######   ####....
   def glueTogether(self,mode):
   
     pass
   ####.......######   ####....
   def breakApart(self,mode) :
   #Multipart to Singlepart: breaks any multipart features into single features.
   #MultipartToSinglepart <in_features> <out_feature_class>
   #modes  = #multiToSinglepart , #branchoff (new shape from elements of old shp based on rules)
   #   ,# ,#
     pass
   ####.......######   ####....
   def do_geo_cvt(self,mode):
      if mode == 'pnt_poly':
         pass
      if mode == 'line_poly':
        #FeatureToPolygon <in_features;in_features...> <out_feature_class>
        #{cluster_tolerance} {ATTRIBUTES | NO_ATTRIBUTES} {label_features}
        pass

      if mode == 'line_pnt':
         pass
      if mode == 'poly_pnt':
          #Feature to Point: creates a point feature class from the centroids or midpoints of the input
          #  features.
          # FeatureToPoint <in_features> <out_feature_class> {CENTROID | INSIDE}

          #############
          
          
          #poly -> line -> pnt (NOT just midpoints)
          
         pass
         
      if mode == 'poly_line':
         #FeatureToLine <in_features;in_features...> <out_feature_class>
         #{cluster_tolerance} {ATTRIBUTES | NO_ATTRIBUTES}
         pass

      if mode == 'pnt_line':
         pass



Personal tools