def checkDistanceThresholdSWM(ssdo, threshold, maxExtent): if threshold < 0: #### Negative Values Not Valid #### ARCPY.AddIDMessage("ERROR", 933) raise SystemExit() softWarn = False if ssdo.useChordal: softMaxExtent = maxExtent hardMaxExtent = ARC._ss.get_max_gcs_distance(ssdo.spatialRef) if softMaxExtent < hardMaxExtent: maxExtent = softMaxExtent softWarn = True else: maxExtent = hardMaxExtent if threshold == 0: #### Infinite Radius Not Valid For Fixed and ZOI #### ARCPY.AddIDMessage("ERROR", 928) raise SystemExit() #### Assure that the Radius is Smaller than the Max Extent #### if threshold > maxExtent: #### Can Not be Greater or Equal to Extent #### #### Applies to Fixed (1) and ZOI (7) #### if ssdo.useChordal and not softWarn: ARCPY.AddIDMessage("ERROR", 1607) raise SystemExit() else: ARCPY.AddIDMessage("ERROR", 929) raise SystemExit() return threshold
def tProb(t, dof, type=0, silent=False): """Calculates the area under the curve of the studentized-t distribution. (A) INPUTS: t (float): t-statistic dof (int): degrees of freedom type {int, 0}: {0,1,2} (See (1)) NOTES: (1) 0 = area under the curve to the left 1 = area under the curve to the right 2 = two-tailed test REFERENCES: (A) Source - Algorithm AS 27: Applied Statistics, Vol. 19(1), 1970 """ if dof <= 1: #### Must Have More Than One Degree of Freedom #### ARCPY.AddIDMessage("ERROR", 1128, 1) raise SystemExit() else: if (2 <= dof <= 4) and not silent: #### Warn if Less Than Five Degrees of Freedom #### ARCPY.AddIDMessage("WARNING", 1130) return ARC._ss.t_prob(t, dof, type)
def CalcSurfaceLength(in_fc, dem, field): if not arcpy.Exists(in_fc): arcpy.AddIDMessage("ERROR", 110, in_fc) raise SystemExit() if not arcpy.Exists(dem): arcpy.AddIDMessage("ERROR", 110, in_fc) raise SystemExit() desc = arcpy.Describe(in_fc) if desc.shapeType.lower() not in ("polygon", "polyline"): arcpy.AddIDMessage("ERROR", 931) raise SystemExit() if desc.spatialReference.name == "Unknown": arcpy.AddIDMessage("ERROR", 1024) raise SystemExit() InitParams(desc.spatialReference) if field not in desc.fields: arcpy.AddField_management(in_fc, field, "DOUBLE") cursor = arcpy.da.UpdateCursor(in_fc, ["SHAPE@", field], spatial_reference=desc.spatialReference.GCS) for row in cursor: row[1] = CalcShapeLength(row[0], dem) / 1000.0 # unit: km cursor.updateRow(row) del cursor
def reportBadRecords(numObs, numBadObs, badIDs, label="OID", allowNULLs=False, explicitBadRecordID=None): """Formats a string that notifies the user of the records it had trouble reading. It only reports the first 30 bad records. INPUTS: numObs (int): total number of records numBadObs (int): number of bad records badIDs (list): list of all bad record IDs label {str, OID}: the master field that corresponds to badIds allowNULLs {bool, False}: allow NULL values in analysis? """ ARCPY.AddIDMessage("WARNING", 642, numBadObs, numObs) if len(badIDs) > 30: badIDs = badIDs[0:30] badIDs = ", ".join(badIDs) if allowNULLs: ARCPY.AddIDMessage("WARNING", 1158, label, badIDs) else: if explicitBadRecordID != None: ARCPY.AddIDMessage("WARNING", explicitBadRecordID, label, badIDs) else: ARCPY.AddIDMessage("WARNING", 848, label, badIDs)
def checkField(allFields, fieldName, types=[]): """Checks whether a field exists and whether it conforms to the specified type(s). INPUTS: allFields (dict): field name = field type fieldName (str): name of the field to check types {list, []}: list of allowed data types for the field in question. """ #### Upper Case the FieldName #### fieldNameUp = fieldName.upper() #### Make Sure Field Exists #### try: type = allFields[fieldNameUp].type except: ARCPY.AddIDMessage("ERROR", 728, fieldName) raise SystemExit() #### Make Sure Data Type Exists #### try: dataType = data2Type[type] except: ARCPY.AddIDMessage("Error", 724) raise SystemExit() #### Make Sure Data Type is Appropriate #### if dataType not in types: typeString = returnFieldTypes(types) ARCPY.AddIDMessage("ERROR", 640, fieldName, typeString) raise SystemExit() return type
def warningNoNeighbors(numObs, numObsNoNeighs, idsNoNeighs, masterField, forceNeighbor=False, contiguity=False): """Returns warning messages for observations with no neighbors. INPUTS: numObs (int): total number of observations numObsNoNeighs (int): number of observations with no neighbors idsNoNeighs (list): ids with no neighbors masterField (str): name of the unique ID field forceNeighbor {boolean, False}: method used assured at least one neighbor? contiguity {boolean, False}: input feature class comprised of polygons? """ idsNoNeighs = [str(i) for i in idsNoNeighs] idsNoNeighs = ", ".join(idsNoNeighs) if forceNeighbor: if contiguity: ARCPY.AddIDMessage("Warning", 718, numObsNoNeighs) else: ARCPY.AddIDMessage("Warning", 715, numObsNoNeighs) ARCPY.AddIDMessage("Warning", 716, masterField, idsNoNeighs) else: ARCPY.AddIDMessage("Warning", 846, numObsNoNeighs) ARCPY.AddIDMessage("Warning", 847, masterField, idsNoNeighs)
def calculate(self): """Calculates the nearest neighbor statistic.""" #### Attribute Shortcuts #### ssdo = self.ssdo gaTable = ssdo.gaTable N = ssdo.numObs studyArea = self.studyArea ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84007), 0, N, 1) #### Create k-Nearest Neighbor Search Type #### gaSearch = GAPY.ga_nsearch(gaTable) gaConcept = self.concept.lower() gaSearch.init_nearest(0.0, 1, gaConcept) neighDist = ARC._ss.NeighborDistances(gaTable, gaSearch) distances = NUM.empty((N, ), float) #### Add All NN Distances #### for row in xrange(N): distances[row] = neighDist[row][-1][0] ARCPY.SetProgressorPosition() maxDist = distances.max() if ssdo.useChordal: hardMaxExtent = ARC._ss.get_max_gcs_distance(ssdo.spatialRef) if maxDist > hardMaxExtent: ARCPY.AddIDMessage("ERROR", 1609) raise SystemExit() #### Calculate Mean Nearest Neighbor Distance #### ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84007)) observedMeanDist = distances.mean() #### Calculate Expected Mean Nearest Neighbor Distance #### expectedMeanDist = 1.0 / (2.0 * ((N / studyArea)**0.5)) #### Calculate the Z-Score #### standardError = 0.26136 / ((N**2.0 / studyArea)**0.5) #### Verify Results #### check1 = abs(expectedMeanDist) > 0.0 check2 = abs(standardError) > 0.0 if not (check1 and check2): ARCPY.AddIDMessage("Error", 907) raise SystemExit() #### Calculate Statistic #### ratio = observedMeanDist / expectedMeanDist zScore = (observedMeanDist - expectedMeanDist) / standardError pVal = STATS.zProb(zScore, type=2) #### Set Attributes #### self.nn = observedMeanDist self.en = expectedMeanDist self.ratio = ratio self.zn = zScore self.pVal = pVal
def initialize(self): """Performs additional validation and populates the SSDataObject.""" ARCPY.SetProgressor("default", ("Starting to perform OLS regression. " "Loading features...")) #### Shorthand Attributes #### ssdo = self.ssdo #### MasterField Can Not Be The Dependent Variable #### if ssdo.masterField == self.depVarName: ARCPY.AddIDMessage("ERROR", 945, ssdo.masterField, ARCPY.GetIDMessage(84112)) raise SystemExit() #### Remove the MasterField from Independent Vars #### if ssdo.masterField in self.indVarNames: self.indVarNames.remove(ssdo.masterField) ARCPY.AddIDMessage("Warning", 736, ssdo.masterField) #### Remove the Dependent Variable from Independent Vars #### if self.depVarName in self.indVarNames: self.indVarNames.remove(self.depVarName) ARCPY.AddIDMessage("Warning", 850, self.depVarName) #### Raise Error If No Independent Vars #### if not len(self.indVarNames): ARCPY.AddIDMessage("Error", 737) raise SystemExit() #### Create Dependent Variable #### self.allVars = [self.depVarName] + self.indVarNames self.y = ssdo.fields[self.depVarName].returnDouble() self.n = ssdo.numObs self.y.shape = (self.n, 1) #### Assure that Variance is Larger than Zero #### yVar = NUM.var(self.y) if NUM.isnan(yVar) or yVar <= 0.0: ARCPY.AddIDMessage("Error", 906) raise SystemExit() #### Create Design Matrix #### self.k = len(self.indVarNames) + 1 self.x = NUM.ones((self.n, self.k - 1), dtype=float) for column, variable in enumerate(self.indVarNames): self.x[:, column] = ssdo.fields[variable].data #### Resolve Weights #### if self.patW: self.w = self.patW.w self.wName = self.patW.wName else: self.w = None self.wName = None
def setAnalysisSSDO(self, tempFC, varName): #### Initial Data Assessment #### printOHSSection(84428, prependNewLine=True) self.varName = varName self.analysisSSDO = self.ssdo self.masterField = UTILS.setUniqueIDField(self.analysisSSDO) if UTILS.renderType[self.ssdo.shapeType.upper()]: stringShape = ARCPY.GetIDMessage(84502) else: stringShape = ARCPY.GetIDMessage(84501) #### Assure Enough Features (Q) #### printOHSSubject(84429, addNewLine=False) self.analysisSSDO.obtainDataGA(self.masterField, [self.varName]) if len(self.analysisSSDO.badRecords): ARCPY.AddMessage("\n") if self.analysisSSDO.numObs < 30: ARCPY.AddIDMessage("ERROR", 1571, '30', stringShape) self.cleanUp() raise SystemExit() msg = ARCPY.GetIDMessage(84485).format(self.analysisSSDO.numObs) printOHSAnswer(msg) #### Errors and Warnings #### printOHSSubject(84432, addNewLine=False) y = self.analysisSSDO.fields[self.varName].returnDouble() yVar = NUM.var(y) #### Zero Variance #### if NUM.isnan(yVar) or yVar <= 0.0: ARCPY.AddIDMessage("ERROR", 1575) self.cleanUp() raise SystemExit() #### Analysis Var Description #### msg = ARCPY.GetIDMessage(84446).format(self.varName) printOHSAnswer(msg, addNewLine=False) printWeightAnswer(y) #### Locational Outliers #### lo = UTILS.LocationInfo(self.analysisSSDO, concept="EUCLIDEAN", silentThreshold=True, stdDeviations=3) printOHSLocationalOutliers(lo, aggType=2) #### Raster Boundary #### if self.outputRaster: self.validateRaster(self.analysisSSDO.xyCoords)
def CalcSurfaceArea(in_fc, surface, area_field, out_field): if not arcpy.Exists(in_fc): arcpy.AddIDMessage("ERROR", 110, in_fc) raise SystemExit() desc = arcpy.Describe(in_fc) if desc.shapeType.lower() != "polygon": arcpy.AddIDMessage("ERROR", 931) raise SystemExit() if desc.spatialReference.name == "Unknown": arcpy.AddIDMessage("ERROR", 1024) raise SystemExit() if not arcpy.Exists(surface): arcpy.AddIDMessage("ERROR", 110, surface) raise SystemExit() if not out_field: out_field = area_field fieldmap = arcpy.FieldMap() fieldmap.addInputField(surface, area_field) fieldmap.mergeRule = "Sum" fieldmap.outputField.name = out_field fieldmappings = arcpy.FieldMappings() fieldmappings.addFieldMap(fieldmap) result = arcpy.SpatialJoin_analysis(in_fc, surface, "SURFACE2", field_mapping=fieldmappings, match_option="CONTAINS") if out_field not in desc.fields: arcpy.AddField_management(in_fc, out_field, "DOUBLE") cursor1 = arcpy.da.UpdateCursor(in_fc, [out_field]) cursor2 = arcpy.da.SearchCursor(result, [out_field]) for row1 in cursor1: row2 = cursor2.next() if row2[0] is None: row1[0] = 0.0 else: row1[0] = row2[0] cursor1.updateRow(row1) del cursor1, cursor2 arcpy.Delete_management(result)
def createOutput(self, outputTable): """Creates Moran's I Step Output Table. INPUTS outputTable (str): path to the output table """ #### Allow Overwrite Output #### ARCPY.env.overwriteOutput = 1 #### Get Output Table Name With Extension if Appropriate #### outputTable, dbf = UTILS.returnTableName(outputTable) #### Set Progressor #### ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84008)) #### Delete Table If Exists #### UTILS.passiveDelete(outputTable) #### Create Table #### outPath, outName = OS.path.split(outputTable) try: DM.CreateTable(outPath, outName) except: ARCPY.AddIDMessage("ERROR", 541) raise SystemExit() #### Add Result Fields #### self.outputFields = [] for field in iaFieldNames: fieldOut = ARCPY.ValidateFieldName(field, outPath) UTILS.addEmptyField(outputTable, fieldOut, "DOUBLE") self.outputFields.append(fieldOut) #### Create Insert Cursor #### try: insert = DA.InsertCursor(outputTable, self.outputFields) except: ARCPY.AddIDMessage("ERROR", 204) raise SystemExit() #### Add Rows to Output Table #### for testIter in xrange(self.nIncrements): insert.insertRow(self.giResults[testIter]) #### Clean Up #### del insert return outputTable, dbf
def CalcSphericalLength(in_fc, field): if not arcpy.Exists(in_fc): arcpy.AddIDMessage("ERROR", 110, in_fc) raise SystemExit() desc = arcpy.Describe(in_fc) if desc.shapeType.lower() not in ("polygon", "polyline"): arcpy.AddIDMessage("ERROR", 931) raise SystemExit() if field not in desc.fields: arcpy.AddField_management(in_fc, field, "DOUBLE") arcpy.CalculateField_management(in_fc, field, "!shape.length@kilometers!", "PYTHON_9.3")
def validateNumResults(self): candN = self.ssdoCand.numObs bothType = self.similarType == 'BOTH' if bothType: maxN = candN / 2 else: maxN = candN if self.numResults > maxN: if bothType: ARCPY.AddIDMessage("WARNING", 1587, str(maxN)) else: ARCPY.AddIDMessage("WARNING", 1586, str(maxN)) self.numResults = maxN
def setupNearestNeighbor(): """Retrieves the parameters from the User Interface and executes the appropriate commands.""" inputFC = ARCPY.GetParameterAsText(0) distanceConcept = ARCPY.GetParameterAsText(1).upper().replace(" ", "_") displayIt = ARCPY.GetParameter(2) studyArea = UTILS.getNumericParameter(3) concept = WU.conceptDispatch[distanceConcept] #### Create a Spatial Stats Data Object (SSDO) #### ssdo = SSDO.SSDataObject(inputFC, useChordal=True) #### Populate SSDO with Data #### ssdo.obtainDataGA(ssdo.oidName, minNumObs=2) #### Calculate #### nn = NearestNeighbor(ssdo, concept=concept, studyArea=studyArea) #### Report and Set Parameters #### nn.report() try: ARCPY.SetParameterAsText(4, nn.ratioString) ARCPY.SetParameterAsText(5, nn.znString) ARCPY.SetParameterAsText(6, nn.pvString) ARCPY.SetParameterAsText(7, nn.enString) ARCPY.SetParameterAsText(8, nn.nnString) except: ARCPY.AddIDMessage("WARNING", 902) #### Create HTML Output #### if displayIt: htmlOutFile = nn.reportHTML(htmlFile=None) ARCPY.SetParameterAsText(9, htmlOutFile)
def createOutput(self, outputFC): #### Build fields for output table #### self.templateDir = OS.path.dirname(SYS.argv[0]) candidateFields = {} candidateFields[FIELDNAMES[0]] = SSDO.CandidateField( FIELDNAMES[0], "Double", self.error.predy) candidateFields[FIELDNAMES[1]] = SSDO.CandidateField( FIELDNAMES[1], "Double", self.error.u) self.ssdo.output2NewFC(outputFC, candidateFields, appendFields=self.allVars) #### Set the Default Symbology #### params = ARCPY.gp.GetParameterInfo() try: renderType = UTILS.renderType[self.ssdo.shapeType.upper()] if renderType == 0: renderLayerFile = "ResidPoints.lyr" elif renderType == 1: renderLayerFile = "ResidPolylines.lyr" else: renderLayerFile = "ResidPolygons.lyr" if FIELDNAMES[0].startswith('Het'): renderLayerFile = "Het" + renderLayerFile fullRLF = OS.path.join(self.templateDir, "Layers", renderLayerFile) params[4].Symbology = fullRLF except: ARCPY.AddIDMessage("WARNING", 973)
def get_valid_attributes(desc_nds_attributes, input_attributes, attribute_type="Restriction", warning_message_id=30113): '''Return a list of attributes such as restrictions and cost that are valid for the network dataset. Report invaid attributes as warnings. input_attributes is the semicolon seperated string containing the attributes specified as input.''' #Get a list of all the attributes that the network dataset supports nds_attributes = [ attribute.name for attribute in desc_nds_attributes if attribute.usageType == attribute_type ] nds_attributes_set = set(nds_attributes) #ensure that we do not have single quotes in multi word attribute names #For example split will give us "'Non-routeable Segments'" but we need "Non-routeable Segments" input_attributes_set = set( [x.lstrip("'").rstrip("'") for x in input_attributes.split(";")]) attributes_to_use_set = input_attributes_set.intersection( nds_attributes_set) unused_attributes = list(input_attributes_set - attributes_to_use_set) if unused_attributes: arcpy.AddIDMessage("WARNING", warning_message_id, ", ".join(unused_attributes)) return list(attributes_to_use_set)
def setStudyArea(self): """Sets the study area for the nearest neighbor stat.""" #### Attribute Shortcuts #### ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84248)) ssdo = self.ssdo if self.studyArea == None: #### Create Min Enc Rect #### studyAreaFC = UTILS.returnScratchName("regularBound_FC") clearedMinBoundGeom = UTILS.clearExtent(UTILS.minBoundGeomPoints) clearedMinBoundGeom(ssdo.xyCoords, studyAreaFC, geomType="RECTANGLE_BY_AREA", spatialRef=ssdo.spatialRef) polyInfo = UTILS.returnPolygon(studyAreaFC, spatialRef=ssdo.spatialRefString, useGeodesic=ssdo.useChordal) studyAreaPoly, studyArea = polyInfo UTILS.passiveDelete(studyAreaFC) if studyArea == None: #### Invalid Study Area #### ARCPY.AddIDMessage("Error", 932) raise SystemExit() self.studyArea = studyArea
def reportBadLengths(numObs, numBadObs, badLengths, label="OID"): """Formats a string that notifies the user of the line records with the same start and end points. It only reports the first 30 bad records. INPUTS: numObs (int): total number of records numBadObs (int): number of line records with no length badLengths (list): list of all line record IDs with no length label {str, OID}: the master field that corresponds to badLengths """ ARCPY.AddIDMessage("WARNING", 911, numBadObs, numObs) if len(badLengths) > 30: badLengths = badLengths[0:30] badLengths = ", ".join(badLengths) ARCPY.AddIDMessage("WARNING", 912, label, badLengths)
def add_error(id, s=None): """ Return errors """ arcpy.AddIDMessage("ERROR", id, s if s else None) if __name__ == '__main__': sys.exit(1) else: raise arcpy.ExecuteError, arcpy.GetIDMessage(id)
def setDerivedOutput(countFieldNameOut, maxCount): #### Set Derived Output #### try: ARCPY.SetParameterAsText(2, countFieldNameOut) maxCount = maxCount * 1.0 ARCPY.SetParameterAsText(3, maxCount) except: ARCPY.AddIDMessage("WARNING", 902)
def deleteCopy(self): '''Deletes the copy of the input features''' if self.isCopy and arcpy.Exists(self.catalogPath): try: arcpy.management.Delete(self.catalogPath) except Exception as ex: arcpy.AddIDMessage("WARNING", 30133, self.catalogPath)
def checkPolygons(self, numObs): if numObs < minNumFeatures: ARCPY.AddIDMessage("ERROR", 1535, str(minNumFeatures)) self.cleanUp() raise SystemExit() else: msg = ARCPY.GetIDMessage(84491).format(numObs) printOHSAnswer(msg)
def initialize(self): """Performs additional validation and populates the SSDataObject.""" #### Shorthand Attributes #### ssdo = self.ssdo #### MasterField Can Not Be The Dependent Variable #### if ssdo.masterField == self.depVarName: ARCPY.AddIDMessage("ERROR", 945, ssdo.masterField, ARCPY.GetIDMessage(84112)) raise SystemExit() #### Remove the MasterField from Independent Vars #### if ssdo.masterField in self.indVarNames: self.indVarNames.remove(ssdo.masterField) ARCPY.AddIDMessage("WARNING", 736, ssdo.masterField) #### Remove the Dependent Variable from Independent Vars #### if self.depVarName in self.indVarNames: self.indVarNames.remove(self.depVarName) ARCPY.AddIDMessage("WARNING", 850, self.depVarName) #### Raise Error If No Independent Vars #### if not len(self.indVarNames): ARCPY.AddIDMessage("ERROR", 737) raise SystemExit() #### Create Dependent Variable #### self.allVars = [self.depVarName] + self.indVarNames self.y = ssdo.fields[self.depVarName].returnDouble() self.n = ssdo.numObs self.y.shape = (self.n, 1) #### Assure that Variance is Larger than Zero #### yVar = NUM.var(self.y) if NUM.isnan(yVar) or yVar <= 0.0: ARCPY.AddIDMessage("ERROR", 906) raise SystemExit() #### Create Design Matrix #### self.k = len(self.indVarNames) + 1 self.x = NUM.ones((self.n, self.k), dtype=float) for column, variable in enumerate(self.indVarNames): self.x[:, column + 1] = ssdo.fields[variable].data
def AddIDMessage(message, message_ID, add_argument1=None, add_argument2=None): arcpy.AddIDMessage(message, message_ID, add_argument1=add_argument1, add_argument2=add_argument2) print(message)
def calculateAreas(inputFC, outputFC): """Creates a new feature class from the input polygon feature class and adds a field that includes the area of the polygons. INPUTS: inputFC (str): path to the input feature class outputFC (str): path to the output feature class """ #### Validate Output Workspace #### ERROR.checkOutputPath(outputFC) outPath, outName = OS.path.split(outputFC) #### Create SSDataObject #### ssdo = SSDO.SSDataObject(inputFC, templateFC = outputFC, useChordal = False) #### Assure Polygon FC #### if ssdo.shapeType.lower() != "polygon": ARCPY.AddIDMessage("ERROR", 931) raise SystemExit() #### Check Number of Observations #### cnt = UTILS.getCount(inputFC) ERROR.errorNumberOfObs(cnt, minNumObs = 1) #### Copy Features #### try: clearCopy = UTILS.clearExtent(DM.CopyFeatures) clearCopy(inputFC, outputFC) except: ARCPY.AddIDMessage("ERROR", 210, outputFC) raise SystemExit() #### Add Area Field #### areaFieldNameOut = ARCPY.ValidateFieldName(areaFieldName, outPath) if not ssdo.allFields.has_key(areaFieldNameOut): UTILS.addEmptyField(outputFC, areaFieldNameOut, "DOUBLE") #### Calculate Field #### clearCalc = UTILS.clearExtent(DM.CalculateField) clearCalc(outputFC, areaFieldNameOut, "!shape.area!", "PYTHON_9.3")
def checkFC(inputFC): """Assesses whether a feature class exists and returns an appropriate error message if it does not. INPUTS: inputFC (str): catalogue path to the input feature class. """ if not ARCPY.Exists(inputFC): ARCPY.AddIDMessage("ERROR", 110, inputFC) raise SystemExit()
def RasterToSurface(dem, out_fc, field): if not arcpy.Exists(dem): arcpy.AddIDMessage("ERROR", 110, dem) raise SystemExit() desc = arcpy.Describe(dem) if desc.spatialReference.name == "Unknown": arcpy.AddIDMessage("ERROR", 1024) raise SystemExit() InitParams(desc.spatialReference) rowCount, colCount = desc.height, desc.width arcpy.env.outputCoordinateSystem = desc.SpatialReference.GCS result = arcpy.RasterToPoint_conversion(dem, "DEM2", "Value") demArray = arcpy.da.FeatureClassToNumPyArray(result, ("SHAPE@X", "SHAPE@Y", "grid_code")).reshape( (rowCount, colCount)) arcpy.Delete_management(result) dtype = np.dtype([('X', '<f4'), ('Y', '<f4'), ('{0}'.format(field), '<f4')]) surfaceArray = np.zeros(((rowCount - 1) * 2, (colCount - 1)), dtype) for row in xrange(0, rowCount - 1): for col in xrange(0, colCount - 1): pointA = demArray[row, col] pointB = demArray[row, col + 1] pointC = demArray[row + 1, col + 1] pointD = demArray[row + 1, col] xABC = (pointA[0] + pointB[0] + pointC[0]) / 3.0 yABC = (pointA[1] + pointB[1] + pointC[1]) / 3.0 sABC = CalcTriangleArea(pointA, pointB, pointC) surfaceArray[row * 2, col] = (xABC, yABC, sABC) xADC = (pointA[0] + pointD[0] + pointC[0]) / 3.0 yADC = (pointA[1] + pointD[1] + pointC[1]) / 3.0 sADC = CalcTriangleArea(pointA, pointD, pointC) # unit: km2 surfaceArray[row * 2 + 1, col] = (xADC, yADC, sADC) arcpy.da.NumPyArrayToFeatureClass(surfaceArray.reshape((rowCount - 1) * (colCount - 1) * 2, ), out_fc, ["X", "Y"], desc.spatialReference.GCS)
def check_valid_table_name(table_name, out_workspace, error_code, add_argument1=None, add_argument2=None): '''Check if the table name is valid for the output workspace and fail with an error if the name is invalid''' valid_name = arcpy.ValidateTableName(table_name, out_workspace) if valid_name != table_name: arcpy.AddIDMessage("ERROR", error_code, add_argument1, add_argument2) raise arcpy.ExecuteError
def renderResults(self): #### Set the Default Symbology #### params = ARCPY.gp.GetParameterInfo() try: renderType = UTILS.renderType[self.ssdo.shapeType.upper()] renderLayerFile = giRenderDict[renderType] templateDir = OS.path.dirname(OS.path.dirname(SYS.argv[0])) fullRLF = OS.path.join(templateDir, "Templates", "Layers", renderLayerFile) params[2].Symbology = fullRLF except: ARCPY.AddIDMessage("WARNING", 973)
def exportCSV(inputTable, delimiter, rowNumbers, outputFile, headers): #### Create Progressor Bar #### arcpy.AddMessage(arcpy.GetIDMessage(84012)) #arcpy.SetProgressor("step", arcpy.GetIDMessage(84012), 0, cnt, 1) #### Process Field Values #### try: rows = arcpy.da.SearchCursor(inputTable, "*") except: arcpy.AddIDMessage("ERROR", 204) raise SystemExit() #### Create Output File #### number_table_rows = long(arcpy.GetCount_management(inputTable)[0]) print(number_table_rows) filename = outputFile number_files = 1 rowsPerFile = 5 rowsWritten = 0 if (rowNumbers != -1): with arcpy.da.SearchCursor(inputTable, "*") as cursor: while (rowsWritten < number_table_rows): rowsWritten += writeFile( filename + '_' + str(number_files) + ".csv", cursor, rowsPerFile, delimiter) number_files += 1 else: with arcpy.da.SearchCursor(inputTable, "*") as cursor: with open(outputFile + ".csv", 'wb') as csvfile: writer = unicodecsv.writer(csvfile, encoding='utf-8', delimiter=delimiter) for row in cursor: writer.writerow(row) #### Write Field Names to File #### ''' if headers: #allFieldNames = arcpy.Describe(inputTable).Fields allFieldNames = [str(f.name) for f in arcpy.Describe(inputTable).Fields] outRow = delimiter.join(allFieldNames) writer.writerow(outRow) ''' arcpy.SetProgressorPosition() arcpy.AddMessage(outputFile)