def __init__(self): """Setup arcpy and the list of tool parameters.""" import arcpy self.params = arcpy.GetParameterInfo() mxd = arcpy.mapping.MapDocument("CURRENT") # Document blocs = arcpy.mapping.ListDataFrames(mxd) couches = arcpy.mapping.ListLayers(mxd)
def __init__(self): """Setup arcpy and the list of tool parameters.""" self.params = arcpy.GetParameterInfo() self.current_path = sys.argv[0] self.sdefile = os.path.join(self.current_path, "vector.sde") self.project = os.path.join(self.sdefile, 'SDE.PROJECT') self.fields = ['PRODUCT_TY', 'LOCATION', 'PRJ_ID', 'PRO_YEAR', 'RESOLUTION', 'PRJ_NAME']
def __init__(self): """ Define the tool (tool name is the name of the class). """ self.label = "Decode QA" self.description = "" self.params = arcpy.GetParameterInfo() self.canRunInBackground = False
def iniciar(sede, subsede, carpeta): rutaGeodatabase = crearFileGDB(sede, subsede, carpeta) rutaFD = os.path.join(rutaGeodatabase, 'Generales') importarFeatureClass(sede, subsede, rutaFD) arcpy.env.workspace = rutaGeodatabase arcpy.env.scratchWorkspace = rutaGeodatabase arcpy.SetParameterAsText(3, r'{}\HIDRO_{}_{}'.format(rutaFD, sede, subsede)) arcpy.SetParameterAsText( 4, r'{}\CCPP_URBANO_{}_{}'.format(rutaFD, sede, subsede)) arcpy.SetParameterAsText(5, r'{}\AES_{}_{}'.format(rutaFD, sede, subsede)) arcpy.SetParameterAsText(6, r'{}\SEDE_OPERATIVA'.format(rutaFD)) arcpy.SetParameterAsText(7, r'{}\DEPARTAMENTO'.format(rutaFD)) arcpy.SetParameterAsText(8, r'{}\PROVINCIA'.format(rutaFD)) arcpy.SetParameterAsText( 9, r'{}\DISTRITO_{}_{}'.format(rutaFD, sede, subsede)) arcpy.SetParameterAsText(10, r'{}\ZONAS'.format(rutaFD)) arcpy.SetParameterAsText(11, r'{}\TRACK_{}_{}'.format(rutaFD, sede, subsede)) params = arcpy.GetParameterInfo() print params arcpy.AddWarning("params {}".format(params)) for param in params: print param arcpy.AddWarning("param {}".format(param)) if '{}'.format(param.name) == 'aes': param.symbology = lyrAe elif '{}'.format(param.name) == 'hidro': param.symbology = lyrHidro elif '{}'.format(param.name) == 'distrito': param.symbology = lyrDistrito elif '{}'.format(param.name) == 'zona': param.symbology = lyrZona elif '{}'.format(param.name) == 'track': param.symbology = lyrTrack elif '{}'.format(param.name) == 'ccpp_urbano': param.symbology = lyrCcppUrbano elif '{}'.format(param.name) == 'departamento': param.symbology = lyrDepartamento elif '{}'.format(param.name) == 'provincia': param.symbology = lyrProvincia elif '{}'.format(param.name) == 'sede_operativa': param.symbology = lyrSede
def __init__(self): # set self.params for use in other function self.params = arcpy.GetParameterInfo() # Set map projection such that footprints show up wgs84 = arcpy.SpatialReference(4326) activeMap = arcpy.mp.ArcGISProject("CURRENT").activeMap map_reference_code = activeMap.spatialReference.PCSCode original = arcpy.SpatialReference(map_reference_code) if not activeMap.spatialReference == wgs84: activeMap.spatialReference = wgs84
def __init__(self): """ Define the tool (tool name is the name of the class). """ #import lookup_dict #self.bit_flags = lookup_dict.bit_flags self.label = "Extract QA Bands" self.description = "" self.params = arcpy.GetParameterInfo() self.canRunInBackground = True
def validarUsuario(ubigeo, usuario, carpeta): cursor = cursorDB() cursor.execute( "SELECT SEGMENTISTA FROM TB_MODULO_ASIGN_R WHERE UBIGEO = '{}' AND SEGMENTISTA = '{}'" .format(ubigeo, usuario)) validacion = len([x[0] for x in cursor]) if validacion == 1: rutaFD = crearFileGDB(ubigeo, carpeta) importarFeatureClass(ubigeo, rutaFD) arcpy.env.scratchWorkspace = rutaFD arcpy.AlterField_management(r'{}\CCPP_{}'.format(rutaFD, ubigeo), "LLAVE_CCPP", "IDCCPP") arcpy.AlterField_management(r'{}\CCPP_N_{}'.format(rutaFD, ubigeo), "LLAVE_CCPP", "IDCCPP") arcpy.SetParameterAsText(3, r'{}\CCPP_{}'.format(rutaFD, ubigeo)) arcpy.SetParameterAsText(4, r'{}\TRACK_{}'.format(rutaFD, ubigeo)) arcpy.SetParameterAsText(5, r'{}\AER_{}'.format(rutaFD, ubigeo)) arcpy.SetParameterAsText(6, r'{}\DIST_{}'.format(rutaFD, ubigeo)) arcpy.SetParameterAsText(7, r'{}\CN_{}'.format(rutaFD, ubigeo)) arcpy.SetParameterAsText(8, r'{}\HIDRO_{}'.format(rutaFD, ubigeo)) # **************************************************** arcpy.SetParameterAsText(9, r'{}\CCPP_N_{}'.format(rutaFD, ubigeo)) arcpy.SetParameterAsText(10, r'{}\RUTA_OLD_{}'.format(rutaFD, ubigeo)) params = arcpy.GetParameterInfo() for param in params: if '{}'.format(param.name) == 'centrosPoblados': param.symbology = lyrCcpp elif '{}'.format(param.name) == 'track': param.symbology = lyrTrack elif '{}'.format(param.name) == 'aer': param.symbology = lyrAer elif '{}'.format(param.name) == 'distrito': param.symbology = lyrDist ##-------------------------------------------------- elif '{}'.format(param.name) == 'curvasnivel': param.symbology = lyrCN elif '{}'.format(param.name) == 'hidrografia': param.symbology = lyrHidro else: arcpy.AddError("\n" * 2 + "-" * 80 + "\n") arcpy.AddError("OBSERVACION:") arcpy.AddWarning( "EL usuario ingresado no esta relacionado a este ubigeo.") arcpy.AddError("\n" + "-" * 80 + "\n" * 2) raise arcpy.ExecuteError cursor.close()
def main(): # Get all of the input parameters as text parameters = arcpy.GetParameterInfo() input_fc = parameters[0].valueAsText output_path = arcpy.Describe(parameters[5].value).path output_name = arcpy.Describe(parameters[5].value).name in_spatial_ref = parameters[1].valueAsText x_field = parameters[2].valueAsText y_field = parameters[3].valueAsText z_field = parameters[4].valueAsText update_geom(input_fc, output_path, output_name, in_spatial_ref, x_field, y_field, z_field)
def __init__(self): """Setup arcpy and the list of tool parameters.""" self.params = arcpy.GetParameterInfo() self.current_path = setting.env[0] self.sdefile = os.path.join(self.current_path, "vector.sde") self.boundary = os.path.join(self.sdefile, 'SDE.Boundary') self.province = os.path.join(self.boundary, "SDE.全国省界") self.city = os.path.join(self.boundary, "SDE.全国市界") self.country = os.path.join(self.boundary, "SDE.全国区县界") self.project = os.path.join(self.sdefile, 'SDE.PROJECT') self.fields = ['NAME', "ADMINCODE", 'SHAPE@'] self.prj_fields = [ 'PRODUCT_TY', 'LOCATION', 'PRJ_ID', 'PRO_YEAR', 'RESOLUTION', 'PRJ_NAME', 'SHAPE@' ]
def updateParameters(self): """Modify the values and properties of parameters before internal validation is performed. This method is called whenever a parameter has been changed.""" import csv self.params = arcpy.GetParameterInfo() if self.params[0].value: CSV_Table = str(self.params[0].value) with open(CSV_Table, "rb") as f: reader = csv.reader(f) i = reader.next() self.params[1].filter.list = i return
def __init__(self): """Setup arcpy and the list of tool parameters.""" self.params = arcpy.GetParameterInfo() self.input_raster = self.params[0] self.approach = self.params[1] self.predefined_pattern = self.params[2] self.pattern_workspace = self.params[3] self.point_matrix_size = self.params[4] self.point_vectors = self.params[5] self.mapping_field = self.params[6] self.move_to_max = self.params[7] self.move_to_max_distance = self.params[8] self.mh_iteration = self.params[9] self.mh_dil_val = self.params[10] self.mh_dil_start = self.params[11] self.mh_dil_stop = self.params[12] self.mh_dil_step = self.params[13] self.transform = self.params[14] self.size_of_the_cell = self.params[15] self.output_sim_matrix = self.params[16] self.output_table = self.params[17] self.output_raster_workspace = self.params[18]
def validarGDB(gdb): desc = arcpy.Describe(gdb) validacion = desc.basename if validacion[0:10] == 'BD_SEGM_R_': if arcpy.Exists(r'{}\Procesamiento'.format(gdb)): ubigeo = validacion[10:16] dataset = r'{}\Procesamiento'.format(gdb) output = crearFeature(ubigeo, dataset) arcpy.SetParameterAsText(1, output) params = arcpy.GetParameterInfo() for param in params: if '{}'.format(param.name) == 'rutas': param.symbology = lyrRuta else: arcpy.AddError("OBSERVACION:") arcpy.AddError( "No se encuentra el dataset 'Procesamiento' dentro de la GDB ingresada" ) else: arcpy.AddError("OBSERVACION:") arcpy.AddError("Ingrese la GDB correcta")
import arcpy print(arcpy.GetParameterCount("Buffer_analysis")) params = arcpy.GetParameterInfo("Buffer_analysis") i = 0 for param in params: print("Name: {}, Type: {}, Value: {}".format( param.name, param.parameterType, param.value)) print(arcpy.GetParameterValue("Buffer_analysis", i)) i = i + 1
import arcpy import re params = arcpy.GetParameterInfo("Union_analysis") test = str(help(arcpy.Union_analysis)) left = " " right = " " print(test[test.index(left)+len(left):test.index(right)]) from ipywidgets import interact @interact_manual(slow_function,b = widgets.Text( value="None", description='Linear Unit Value', style=dict(description_width='initial'), disabled=False ), c = widgets.Dropdown( options=['None','Centimeters','DecimalDegrees', 'Decimeters', 'Feet', 'Inches', 'Kilometers', 'Meters','Miles','Millimeters','NauticalMiles','Points', 'Unknown', 'Yards'], value='None', description='Linear Unit Type:', style=dict(description_width='initial'), disabled=False ))
def main(): arg = dict([(p.name, p.valueAsText) for p in arcpy.GetParameterInfo()]) arcpy.AddMessage('Arg: ' + str(arg)) showLabels(**arg)
import arcpy arcpy.ImportToolbox(r"C:\Users\Admin\Desktop\GetParameter\GetParameter.tbx") print(arcpy.GetParameterCount("TestGetParameter")) params = arcpy.GetParameterInfo("TestGetParameter") i = 0 for param in params: print("Name: {}, Type: {}, Value: {}".format(param.name.encode('gb2312'), param.parameterType, param.value)) print(arcpy.GetParameterValue("TestGetParameter", i)) i = i + 1
'travel_direction', 'time_of_day', 'time_of_day_usage', 'time_zone_usage', 'uturn_policy', 'point_barriers', 'line_barriers', 'polygon_barriers', 'time_attribute', 'time_attribute_units', 'distance_attribute', 'distance_attribute_units', 'use_hierarchy', 'restrictions', 'attribute_parameters', 'accumulate_attributes', 'max_snap_tolerance', 'feature_locator_where_clause', 'route_shape', 'route_line_simplification_tolerance', 'populate_directions', 'directions_language', 'directions_distance_units', 'directions_style_name', 'max_features_point_barriers', 'max_features_line_barriers', 'max_features_polygon_barriers', 'max_facilities', 'max_facilities_to_find', 'max_incidents', 'force_hierarchy_beyond_distance', 'save_output_layer', 'solve_succeeded', 'out_routes', 'out_directions', 'out_facilities') parameter_index = {value: index for index, value in enumerate(parameter_names)} parameter_info = arcpy.GetParameterInfo(TOOL_NAME) #Get all the input parameter values facilities = arcpy.GetParameter(parameter_index['facilities']) incidents = arcpy.GetParameter(parameter_index['incidents']) network_dataset = arcpy.GetParameterAsText(parameter_index['network_dataset']) measurement_units = arcpy.GetParameterAsText( parameter_index['measurement_units']) out_gdb_workspace = arcpy.GetParameterAsText( parameter_index['out_gdb_workspace']) out_routes_name = arcpy.GetParameterAsText(parameter_index['out_routes_name']) out_directions_name = arcpy.GetParameterAsText( parameter_index['out_directions_name']) out_facilities_name = arcpy.GetParameterAsText( parameter_index['out_facilities_name']) num_facilities_to_find = arcpy.GetParameter(
def __init__(self): import arcpy self.params = arcpy.GetParameterInfo() return
i = i + 1 arcpy.AddMessage("Step1 Distance list Complete!") arcpy.MultipleRingBuffer_analysis(InputFeature, OutputFeature, distances, bufferUnit, "", "ALL", "OUTSIDE_ONLY") arcpy.AddMessage("Step2 Success to execute Multi Ring Buffer.") arcpy.AddField_management(OutputFeature, NewField, "double") arcpy.AddMessage("Step3 Success to add Transparency Percent Field.") arcpy.CalculateField_management(OutputFeature, NewField, "!OBJECTID! *10", "PYTHON", "") OutputFeatureCount = int(arcpy.GetCount_management(OutputFeature).getOutput(0)) if OutputFeatureCount == 0: arcpy.AddWarning("{0} has no features.".format(OutputFeature)) else: arcpy.AddMessage("Step4 Success to Calculate Transparency Percent Field.") # Layer files are located in same folder as the .py file PythonFilePath = os.path.dirname(__file__) params = arcpy.GetParameterInfo() params[2].symbology = os.path.join(PythonFilePath, "FeatheringEffectTemplate.lyr") arcpy.AddMessage("Finding Feathering Effect Template Layer ..." + "/r/n" + os.path.join(PythonFilePath, "FeatheringEffectTemplate.lyr")) arcpy.AddMessage("Success!")
def main(): arg = dict([(p.name, p.valueAsText) for p in arcpy.GetParameterInfo()]) arcpy.AddMessage('Arg: ' + str(arg)) splitByExisting(**arg)
from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient from azure.cognitiveservices.vision.customvision.prediction import models from azure.cognitiveservices.vision.customvision.training.models import ImageUrlCreateEntry from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient from arcgis.gis import GIS from arcgis.features import FeatureLayer, Feature import sys import arcpy import datetime as dt import requests import json # TRAIN MODELS IF NEEDED***************************************************************************************************** mode = arcpy.GetParameterInfo()[1].displayName mode = bool("dev" in mode) def imageListChunks(imgList,chunkSize): return [imgList[pos:pos + chunkSize] for pos in range(0, len(imgList), chunkSize)] def imageList(tagName): errorMessage = "Error building image detection model. Unable to retrieve model training images." try: resolveShortlink = requests.get("http://links.esri.com/localgovernment/photosurvey/images") resolveUrl = resolveShortlink.url branch = "blight-images" if mode: branch = "blight-images-dev" else: branch = "blight-images" comm_url = "{}/{}?ref={}".format(resolveUrl,tagName, branch) response = requests.get(comm_url)
import arcpy for tool in arcpy.ListTools(): for p in arcpy.GetParameterInfo(tool): if p.parameterType == 'Derived' and p.datatype == 'Long': print('Tool: {}\n\tparameter: {}'.format(tool, p.displayName))
def main(): # Get all of the input parameters as text parameters = arcpy.GetParameterInfo() input_fc = parameters[0].valueAsText output_fc = parameters[1].valueAsText enable_copy_attachments(input_fc, output_fc)
def validarGDB(gdb): informacion = [] desc = arcpy.Describe(gdb) validacion = desc.basename if validacion[0:10] == 'BD_SEGM_R_': if arcpy.Exists(r'{}\Procesamiento'.format(gdb)): ubigeo = validacion[10:16] dataset = r'{}\Procesamiento'.format(gdb) if arcpy.Exists(r'{}\CCPPRUTAS_{}'.format(dataset, ubigeo)): ccppsRuta = fcCcppRutas(gdb, ubigeo) rutas = fcRutas(gdb, ubigeo) con01 = consistencia01(ccppsRuta) con02 = consistencia02(rutas, ccppsRuta) if len(con01) > 0 or len(con02) > 0: informacion.extend(con01) informacion.extend(con02) for x in informacion: if x[0] == 1: arcpy.AddWarning( "El ccpp {} no presenta un numero de orden en la ruta" .format(x[1])) elif x[0] == 2: arcpy.AddWarning( "La ruta: {} contiene centros poblados en orden NO correlativos" .format(x[1])) elif x[0] == 3: arcpy.AddWarning( "El centro poblado {} no existe en la base de datos (posiblemente agrego un centro poblado nuevo)" .format(x[1])) elif x[0] == 4: arcpy.AddWarning( "El centro poblado {} no se encuentra o fue eliminado, asegurese de que todos los centros poblados RURALES del distrito se encuentren presentes en la Segmentacion" .format(x[1])) else: output = crearFeature(ubigeo, dataset) arcpy.SetParameterAsText(1, output) params = arcpy.GetParameterInfo() for param in params: if '{}'.format(param.name) == 'seccion': param.symbology = lyrScr arcpy.RefreshActiveView() mxd = arcpy.mapping.MapDocument("CURRENT") for i in arcpy.mapping.ListLayers(mxd): if i.name == "SCR_{}".format(ubigeo): i.replaceDataSource(gdb, "FILEGDB_WORKSPACE", "SCR_{}".format(ubigeo), True) arcpy.AssignDefaultToField_management( output, 'UBIGEO', ubigeo) else: arcpy.AddError( "Debes asignar el orden de visita a los centros poblados") else: arcpy.AddError("OBSERVACION:") arcpy.AddError( "No se encuentra el dataset 'Procesamiento' dentro de la GDB ingresada" ) else: arcpy.AddError("El dataset ingresado es incorrecto")
def validarGDB(gdb): informacion = [] desc = arcpy.Describe(gdb) validacion = desc.basename if validacion[0:10] == 'BD_SEGM_R_': if arcpy.Exists(r'{}\Procesamiento'.format(gdb)): ubigeo = validacion[10:16] dataset = r'{}\Procesamiento'.format(gdb) if arcpy.Exists(r'{}\Procesamiento\RUTAS_{}'.format(gdb, ubigeo)): rutas = fcRutas(gdb, ubigeo) ccpps = fcCcpp(gdb, ubigeo) con01 = consistencia01(rutas) con02 = consistencia02(rutas, ccpps) con03 = consistencia03(rutas, ccpps) # con04 = consistencia04(ubigeo, ccpps) if len(con01) > 0 or len(con02) > 0 or len(con03) > 0: informacion.extend(con01) informacion.extend(con02) informacion.extend(con03) # informacion.extend(con04) for x in informacion: if x[0] == 1: arcpy.AddWarning( "La ruta FID:{}; no presenta cantidad de empadronadores" .format(x[1])) elif x[0] == 2: arcpy.AddWarning( "El centro poblado {} | {} | {} no tiene una ruta asociada" .format(x[1], x[2], x[3])) elif x[0] == 3: arcpy.AddWarning( "El centro poblado {} | {} | {} esta asociado a mas de una ruta" .format(x[1], x[2], x[3])) elif x[0] == 4: arcpy.AddWarning( "El centro poblado {} no existe en la base de datos (posiblemente agrego un centro poblado nuevo)" .format(x[1])) elif x[0] == 5: arcpy.AddWarning( "El centro poblado {} no se encuentra o fue eliminado, asegurese de que todos los centros poblados RURALES del distrito se encuentren presentes en la Segmentacion" .format(x[1])) else: output = crearFeature(ccpps, dataset, ubigeo) actualizarRegistros(rutas, output) arcpy.SetParameterAsText(1, output) params = arcpy.GetParameterInfo() for param in params: if '{}'.format(param.name) == 'ccpp': param.symbology = lyrCcpp else: arcpy.AddError("OBSERVACION:") arcpy.AddError("Debes realizar la asignacion de rutas") else: arcpy.AddError("OBSERVACION:") arcpy.AddError( "No se encuentra el dataset 'Procesamiento' dentro de la GDB ingresada" ) else: arcpy.AddError("OBSERVACION:") arcpy.AddError("Ingrese la GDB correcta")
def __init__(self): """Setup arcpy and the list of tool parameters.""" self.params = arcpy.GetParameterInfo()
def main(): scratch_datasets = [] new_fields = [ 'Crash_Count', 'Crash_Count_Weight', 'Crash_Frequency', 'Crash_Rate', 'Weighted_Crash_Frequency', 'Weighted_Crash_Rate' ] try: streets_intersection = arcpy.GetParameterAsText(0) crashes = arcpy.GetParameterAsText(1) time_interval, time_unit = arcpy.GetParameterAsText(2).split(' ') time_interval = float(time_interval) if time_unit == 'Years': time_interval = time_interval * 365 elif time_unit == 'Weeks': time_interval = time_interval * 7 snap_distance = arcpy.GetParameterAsText(3) weight_field = arcpy.GetParameterAsText(4) weight_table = arcpy.GetParameter(5) adt_field = arcpy.GetParameterAsText(6) output_crash_rates = arcpy.GetParameterAsText(7) params = arcpy.GetParameterInfo() shape_type = arcpy.Describe(streets_intersection).shapeType weight_provided = False if weight_field is not None and weight_field != '': weight_provided = True adt_provided = False if adt_field is not None and adt_field != '': adt_provided = True arcpy.SetProgressorLabel("Creating Temporary Crash Layer...") arcpy.MakeFeatureLayer_management(crashes, "Crash Layer") crashes_snap = os.path.join(arcpy.env.scratchGDB, "Crash_Snap") if arcpy.Exists(crashes_snap): arcpy.Delete_management(crashes_snap) arcpy.CopyFeatures_management("Crash Layer", crashes_snap) scratch_datasets.append(crashes_snap) crash_count_field = new_fields[0] crash_count_weight_field = new_fields[1] arcpy.AddField_management(crashes_snap, crash_count_field, "Double", field_alias="Crash Count") fields = [crash_count_field] if weight_provided: arcpy.AddField_management(crashes_snap, crash_count_weight_field, "Double", field_alias="Crash Count Weight") fields.append(crash_count_weight_field) fields.append(weight_field) for field in arcpy.Describe(crashes).fields: if field.name == weight_field: if field.domain is not None and field.domain != '': database = get_workspace(crashes) if database is not None: for domain in arcpy.da.ListDomains(database): if domain.name == field.domain: if domain.domainType == 'CodedValue': for key, value in domain.codedValues.items( ): for i in range( 0, weight_table.rowCount): if weight_table.getValue( i, 0) == value: weight_table.setValue( i, 0, str(key)) break with arcpy.da.UpdateCursor(crashes_snap, fields) as cursor: for row in cursor: row[0] = 1.0 if len(fields) == 3: value = str(row[2]) for i in range(0, weight_table.rowCount): if value == weight_table.getValue(i, 0): row[1] = weight_table.getValue(i, 1) break cursor.updateRow(row) if (shape_type == "Polyline"): arcpy.SetProgressorLabel("Snapping Crashes to Nearest Street...") else: arcpy.SetProgressorLabel( "Snapping Crashes to Nearest Intersection...") snapEnv = [streets_intersection, "EDGE", snap_distance] arcpy.Snap_edit(crashes_snap, [snapEnv]) fms = arcpy.FieldMappings() desc = arcpy.Describe(streets_intersection) for field in desc.fields: if field.type == 'Geometry' or field.type == 'OID' or field.name in new_fields: continue if shape_type == "Polyline" and field.name == desc.AreaFieldName: continue fm = arcpy.FieldMap() fm.addInputField(streets_intersection, field.name) fms.addFieldMap(fm) fm = arcpy.FieldMap() fm.addInputField(crashes_snap, crash_count_field) fm.mergeRule = 'Sum' fms.addFieldMap(fm) if weight_provided: fm = arcpy.FieldMap() fm.addInputField(crashes_snap, crash_count_weight_field) fm.mergeRule = 'Sum' fms.addFieldMap(fm) crashes_join = os.path.join(arcpy.env.scratchGDB, "Crash") if arcpy.Exists(crashes_join): arcpy.Delete_management(crashes_join) arcpy.SpatialJoin_analysis(streets_intersection, crashes_snap, crashes_join, "JOIN_ONE_TO_ONE", "KEEP_ALL", fms, "Intersect", "0 Feet") scratch_datasets.append(crashes_join) if weight_provided: with arcpy.da.UpdateCursor(crashes_join, [crash_count_weight_field]) as cursor: for row in cursor: if row[0] == 0: row[0] = None cursor.updateRow(row) arcpy.SetProgressorLabel("Calculating Crash Statistics") templateDir = os.path.dirname(__file__) crash_frequency_field = new_fields[2] crash_rate_field = new_fields[3] weighted_crash_frequency_field = new_fields[4] weighted_crash_rate_field = new_fields[5] add_fields = [] fields = [crash_count_field] if (shape_type == "Polyline"): fields.append('SHAPE@') add_fields = [[crash_frequency_field, "Crashes Per Mile Per Year"], [ crash_rate_field, "Crashes Per Million Vehicle Miles" ], [ weighted_crash_frequency_field, "Weighted Crashes Per Mile Per Year" ], [ weighted_crash_rate_field, "Weighted Crashes Per Million Vehicle Miles" ]] else: add_fields = [ [crash_frequency_field, "Crashes Per Year"], [crash_rate_field, "Crashes Per Million Entering Vehicles"], [weighted_crash_frequency_field, "Weighted Crashes Per Year"], [ weighted_crash_rate_field, "Weighted Crashes Per Million Entering Vehicles" ] ] arcpy.AddField_management(crashes_join, add_fields[0][0], "Double", field_alias=add_fields[0][1]) fields.append(add_fields[0][0]) if adt_provided: arcpy.AddField_management(crashes_join, add_fields[1][0], "Double", field_alias=add_fields[1][1]) fields.append(add_fields[1][0]) fields.append(adt_field) if weight_provided: fields.append(crash_count_weight_field) arcpy.AddField_management(crashes_join, add_fields[2][0], "Double", field_alias=add_fields[2][1]) fields.append(add_fields[2][0]) if adt_provided: arcpy.AddField_management(crashes_join, add_fields[3][0], "Double", field_alias=add_fields[3][1]) fields.append(add_fields[3][0]) with arcpy.da.UpdateCursor(crashes_join, fields) as cursor: for row in cursor: if row[cursor.fields.index(crash_count_field)] is None: continue miles = 1.0 if 'SHAPE@' in cursor.fields: miles = row[cursor.fields.index('SHAPE@')].getLength( 'GEODESIC', 'MILES') row[cursor.fields.index(crash_frequency_field)] = row[ cursor.fields.index(crash_count_field)] / ( (time_interval / 365) * miles) if crash_count_weight_field in cursor.fields and row[ cursor.fields.index( crash_count_weight_field)] is not None: row[cursor.fields.index( weighted_crash_frequency_field )] = row[cursor.fields.index(crash_count_weight_field)] / ( (time_interval / 365) * miles) if adt_field in cursor.fields and row[cursor.fields.index( adt_field)] is not None: row[cursor.fields.index(crash_rate_field)] = ( row[cursor.fields.index(crash_count_field)] * 1000000 ) / (time_interval * row[cursor.fields.index(adt_field)] * miles) if crash_count_weight_field in cursor.fields and row[ cursor.fields.index( crash_count_weight_field)] is not None: row[cursor.fields.index(weighted_crash_rate_field)] = ( row[cursor.fields.index(crash_count_weight_field)] * 1000000) / (time_interval * row[cursor.fields.index(adt_field)] * miles) cursor.updateRow(row) arcpy.SetProgressorLabel("Creating Crash Rate Layer...") field_info = "" fields_to_hide = ['Join_Count', 'TARGET_FID', new_fields[0]] if weight_provided: fields_to_hide.append(new_fields[1]) field_list = arcpy.ListFields(crashes_join) for field in field_list: if field.name in fields_to_hide: field_info = "{0}{1} {1} HIDDEN;".format( field_info, field.name) else: field_info = "{0}{1} {1} VISIBLE;".format( field_info, field.name) arcpy.MakeFeatureLayer_management(crashes_join, "Output Crash Layer", field_info=field_info[:-1]) arcpy.SelectLayerByAttribute_management( "Output Crash Layer", "NEW_SELECTION", '{0} IS NOT NULL'.format(new_fields[2])) arcpy.CopyFeatures_management("Output Crash Layer", output_crash_rates) lyrx_json = _CRASH_RATE_POINT if (shape_type == "Polyline"): lyrx_json = _CRASH_RATE_POLYLINE with tempfile.NamedTemporaryFile(delete=False) as temp_lyrx: temp_lyrx.write(lyrx_json.encode()) lyrx_path = "{0}.lyrx".format(temp_lyrx.name) os.rename(temp_lyrx.name, lyrx_path) params[7].symbology = lyrx_path finally: for dataset in scratch_datasets: if arcpy.Exists(dataset): arcpy.Delete_management(dataset)
def main(): arcpy.AddMessage('CWD: ' + os.getcwd()) arg = dict([(p.name, p.valueAsText) for p in arcpy.GetParameterInfo()]) arcpy.AddMessage('Arg: ' + str(arg)) bufferIntersect(**arg)
def main(): arg = dict([(p.name, p.valueAsText) for p in arcpy.GetParameterInfo()]) arcpy.AddMessage('Arg: ' + str(arg)) generate_results(**arg)