def CreateFeatureRelationshipClass(FeatureClass, fd): #--------------------------------------------------------------------------- # Create feature relationship class try: print 'Creating the relationship class for: ' + FeatureClass origin_table = FeatureClass destination_table = drawing_facility out_relationship_class = origin_table + '_To_' + destination_table relationship_type = 'SIMPLE' forward_label = 'From ' + origin_table + ' To ' + destination_table backward_label = 'From ' + destination_table + ' To ' + origin_table message_direction = 'NONE' cardinality = 'ONE_TO_MANY' attributed = 'NONE' #TODO: when we use this script to create rel classes on our LGIM data #we will need to change the origin_primary_key to "FACILITYID" ##origin_primary_key = 'FACILITYID' origin_primary_key = 'fac_seq_num' origin_foreign_key = 'Rel_FACILITYID' destination_primary_key = '' destination_foreign_key = '' arcpy.CreateRelationshipClass_management( origin_table, destination_table, out_relationship_class, relationship_type, forward_label, backward_label, message_direction, cardinality, attributed, origin_primary_key, origin_foreign_key, destination_primary_key, destination_foreign_key) print 'Created relationship class: ' + out_relationship_class except Exception as e: print 'ERROR creating the relationship class' print str(e)
def create_relationship(self): origin = os.path.join(self.location, 'Stations') desitination = os.path.join(self.location, 'Results') key = 'StationId' arcpy.CreateRelationshipClass_management( origin, desitination, 'Stations_Have_Results', 'COMPOSITE', 'Results', 'Stations', 'FORWARD', 'ONE_TO_MANY', 'NONE', key, key)
def create_relationship_class(gdb_name, orig, dest): origin_table = "{}/{}".format(gdb_name, orig) dest_table = "{}/{}".format(gdb_name, dest) rel_class = "{}/{}_has_{}".format(gdb_name, orig, dest) arcpy.CreateRelationshipClass_management( origin_table=origin_table, destination_table=dest_table, out_relationship_class=rel_class, relationship_type="COMPOSITE", forward_label=dest, backward_label=orig, message_direction="NONE", cardinality="ONE_TO_MANY", attributed=False, origin_primary_key="GlobalID", origin_foreign_key="parentglobalid")
def create_relationship(self, destination, PK, label): """helper function for arcpy.management.CreateRelationshipClass""" class_name = os.path.join(self.gdb, "Routes_{}_{}".format(*label.split(" "))) return arcpy.CreateRelationshipClass_management( origin_table=os.path.join(self.gdb, ROUTES), destination_table=destination, out_relationship_class=class_name, relationship_type="SIMPLE", forward_label="Routes", backward_label=label, message_direction="NONE", cardinality="ONE_TO_ONE", attributed="NONE", origin_primary_key=PK, origin_foreign_key="Name", destination_primary_key=None, destination_foreign_key=None)
def rc_handler(key, value, foreign_search, primary_search, origin_search): try: #sanitize the field and table names in case everything is in lower or upper case origin = tname_find(origin_search) d_key = fname_find(foreign_search, value[1]) o_key = fname_find(primary_search, tab_dict[origin][1]) #check for existing relationship class rc_name = '{}_{}'.format(key, d_key) if arcpy.Exists(rc_name): arcpy.Delete_management(rc_name) #create the relationship class addMsgAndPrint('Building {}'.format(rc_name)) #print(tab_dict[origin][1],value[1],rc_name,'SIMPLE','{} in {}'.format(o_key, key),'{} in {}'.format(d_key, origin), #'NONE','ONE_TO_MANY','NONE',o_key,d_key, sep=' | ') arcpy.CreateRelationshipClass_management( tab_dict[origin][1], value[1], rc_name, 'SIMPLE', '{} in {}'.format(o_key, key), '{} in {}'.format(d_key, origin), 'NONE', 'ONE_TO_MANY', 'NONE', o_key, d_key) except: print('Could not create relationship class {}'.format(rc_name))
def _add_r(out_gdb, x): origin = x['originClassNames'][0] destination = x['destinationClassNames'][0] originField = x['originClassKeys'][0][0] destinationField = x['originClassKeys'][1][0] logger.debug("{0} {1} {2} {3}".format(origin, originField, destination, destinationField)) arcpy.CreateRelationshipClass_management( out_relationship_class=x['name'], origin_table=origin, destination_table=destination, relationship_type='COMPOSITE' if x['isComposite'] else 'SIMPLE', forward_label='To child', backward_label='To parent', message_direction='NONE', cardinality=_normalise_cardinality(x['cardinality']), attributed='NONE', origin_primary_key=originField, origin_foreign_key=destinationField)
def setUp(self): super(TestManyToManyField, self).setUp() self.rel_path = os.path.join(self.gdb_path, self.REL_NAME) # Create the relationship class. arcpy.CreateRelationshipClass_management( origin_table=self.fc_path, destination_table=self.rc_path, out_relationship_class=self.rel_path, relationship_type='SIMPLE', forward_label='Warehouse', backward_label='Widget', message_direction='NONE', cardinality='MANY_TO_MANY', attributed='NONE', origin_primary_key=self.ORIGIN_PK, origin_foreign_key=self.ORIGIN_FK, destination_primary_key=self.DESTINATION_PK, destination_foreign_key=self.DESTINATION_FK) # Insert data into the relationship class self.rel_fields = ["RID", self.ORIGIN_FK, self.DESTINATION_FK] self.data = [(1, 1, 1), (2, 1, 2), (3, 2, 1), (4, 2, 2), (5, 3, 1)] with arcpy.da.InsertCursor(self.rel_path, self.rel_fields) as cursor: for row in self.data: cursor.insertRow(row) del cursor warehouse = self.related_cls self.related_cls = self.cls self.cls = warehouse self.cls.widgets = ManyToManyField("Widgets", related_class=self.related_cls, relationship_class=self.REL_NAME, foreign_key=self.DESTINATION_FK, related_foreign_key=self.ORIGIN_FK, primary_key=self.DESTINATION_PK, related_primary_key=self.ORIGIN_PK) self.cls.register(self.rc_path) self.related_cls.register(self.fc_path)
def main (): # set overwrite to true arcpy.env.overwriteOutput = True # set workspace environment arcpy.env.workspace = geodatabase print ("Workspace environment set to " + arcpy.env.workspace) create_relationship_class_parameters_list = list() # read csv print ("Opening " + csv_file + " to read relationships details") with open(csv_file, encoding="utf-8-sig") as f: reader = csv.reader(f) for row in reader: # read column names in row 1 and store them in the create_relationship_class_parameters_list if not create_relationship_class_parameters_list: create_relationship_class_parameters_list = row else: params = CreateParametersList(create_relationship_class_parameters_list, row) print ("Creating relationship class between tables {0} and {1}".format(row[0], row[1])) arcpy.CreateRelationshipClass_management(**params) print ("Completed creating relationship class between tables {0}".format(row[3]))
'NONE', 'ONE_TO_MANY', 'NONE', 'DataSources_ID', 'LocationSourceID' ], [ DataSources, ORP, 'ORP_OrientationSource', 'SIMPLE', 'Orientation points with same OrientationSource', 'OrientationSource', 'NONE', 'ONE_TO_MANY', 'NONE', 'DataSources_ID', 'OrientationSourceID' ], [ Glossary, ORP, 'ORP_Type', 'SIMPLE', 'Orientation points with same Type', 'Type definition', 'NONE', 'ONE_TO_MANY', 'NONE', 'Term', 'Type' ] ] arcpy.env.workspace = inGdb if not arcpy.Exists(inGdb + '/RelationshipClasses'): arcpy.CreateFeatureDataset_management(inGdb, 'RelationshipClasses') for r in someRelationshipClasses: testAndDelete(r[2]) testAndDelete('RelationshipClasses/' + r[2]) if arcpy.Exists(r[0]) and arcpy.Exists(r[1]): addMsgAndPrint(' adding relationship class ' + r[2]) print ' adding relationship class ' + r[2] arcpy.CreateRelationshipClass_management(r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10]) addMsgAndPrint('Done')
copy_modify_fc(fc, citywide_gdb_path) count += 1 # Create required Relationship Classes arcpy.env.workspace = sde_path arcpy.env.overwriteOutput = True print("Creating CSCL_CenterlinesHaveAltAddresses Relationship Class") arcpy.CreateRelationshipClass_management("CSCL_Centerline", "CSCL_ALTSEGMENTDATA", "CSCL_CenterlinesHaveAltAddresses", "SIMPLE", "CSCL_ALTSEGMENTDATA", "CSCL_Centerline", "NONE", "ONE_TO_MANY", False, "PHYSICALID", "PHYSICALID") print("CSCL_CenterlinesHaveAltAddresses Relationship Class created") print("Creating CSCL_CenterlinesHaveNames Relationship Class") arcpy.CreateRelationshipClass_management("CSCL_Centerline", "CSCL_StreetName", "CSCL_CenterlinesHaveNames", "SIMPLE", "CSCL_StreetName", "CSCL_Centerline",
itin_path = MHN.break_path(itin_table) arcpy.CreateTable_management(itin_path['dir'], itin_path['name'], updated_itin_table) arcpy.Append_management(updated_itin_table, itin_table, 'TEST') arcpy.Delete_management(updated_itin_table) # Rebuild relationship class. arcpy.AddMessage('{0}Rebuilding relationship classes...'.format('\n')) bus_future_name = MHN.break_path(MHN.bus_future)['name'] itin_table_name = MHN.break_path(itin_table)['name'] rel_arcs = os.path.join(MHN.gdb, 'rel_arcs_to_{0}'.format(itin_table_name)) rel_sys = os.path.join( MHN.gdb, 'rel_{0}_to_{1}'.format( itin_table_name.rsplit('_', 1)[0], itin_table_name.rsplit('_', 1)[1])) arcpy.CreateRelationshipClass_management(MHN.arc, itin_table, rel_arcs, 'SIMPLE', itin_table_name, MHN.arc_name, 'NONE', 'ONE_TO_MANY', 'NONE', 'ABB', 'ABB') arcpy.CreateRelationshipClass_management(MHN.bus_future, itin_table, rel_sys, 'COMPOSITE', itin_table_name, bus_future_name, 'FORWARD', 'ONE_TO_MANY', 'NONE', common_id_field, common_id_field) # Clean up. arcpy.Compact_management(MHN.gdb) arcpy.Delete_management(MHN.mem) arcpy.Delete_management(backup_gdb) arcpy.AddMessage('\nChanges successfully applied!\n')
# --------------------------------------------------------------------------- # ImportRelationshipClasses.py # Created on: 2020-11-02 # Description: Created by PetarSimic # --------------------------------------------------------------------------- import arcpy Feature_Dataset = arcpy.GetParameterAsText(0) location_of_table = arcpy.GetParameterAsText(1) arcpy.env.workspace = Feature_Dataset # Creating Relationship Classes cursor = arcpy.SearchCursor(location_of_table) for row in cursor: arcpy.CreateRelationshipClass_management(row.getValue("origin"), row.getValue("destina"), row.getValue("out_rc"), row.getValue("r_type"), row.getValue("forw_label"), row.getValue("back_label"), row.getValue("msg_dir"), row.getValue("cardin"), row.getValue("attrib"), row.getValue("prim_key"), row.getValue("fore_key"), "", "")
"RockTicketsSR.PROJ_Num", "", "Date_Year =" + "\'" + str(Year_Edit) + "\'") arcpy.AddMessage( "Query out only the year you are calculating and dump the data into QueryTable1" ) # Process: Copy Rows (3) arcpy.CopyRows_management(QueryTable1, QueryTable_CopyRows, "") arcpy.AddMessage( "copy rows from QueryTable1 into QueryTable_copyRows of the year we are calculating" ) # Process: Create Relationship Class arcpy.CreateRelationshipClass_management( Rock_Shoulder_Right, QueryTable_CopyRows, Rock_Shoulder_Right_QueryTable_CopyRows, "SIMPLE", "QueryTable" + str(Year_Edit) + "_CopyRows", "Rock_Shoulder_Right", "NONE", "ONE_TO_MANY", "NONE", "RockPaved_Right", "RockTicketsSR_PROJ_Num", "", "") # Process: Delete Field (3) arcpy.DeleteField_management( Rock_Shoulder_Left, "RockTicketsSR_PROJ_Num;FREQUENCY;SUM_RockTicketsSR_ENGLISH_TONS;SUM_RockTicketsSR_AMT;LAST_RockTicketsSR_Rock_Class" ) # Process: Create Relationship Class (2) arcpy.CreateRelationshipClass_management( Rock_Shoulder_Left, QueryTable_CopyRows, Rock_Shoulder_Left_QueryTable_CopyRows, "SIMPLE", "QueryTable" + str(Year_Edit) + "_CopyRows", "Rock_Shoulder_Left", "NONE", "ONE_TO_MANY", "NONE", "RockPaved_Left", "RockTicketsSR_PROJ_Num", "", "")
def createTables(surveyGDB, outWorkspace, prefix): '''Creates the doamins, tables and relationships of the survey in the target workspace''' arcpy.AddMessage('\t-Creating Tables') arcpy.env.workspace = surveyGDB allTables = getSurveyTables(surveyGDB) dscW = arcpy.Describe(arcpy.env.workspace) #migrate the domains arcpy.AddMessage('\t\t-Creating Domains') for domainName in dscW.domains: if domainName[0:3] == 'cvd': arcpy.AddMessage('\t\t\t-'.format(domainName)) tempTable = 'in_memory\{0}'.format(domainName) domainTable = arcpy.DomainToTable_management(surveyGDB, domainName, tempTable,'CODE', 'DESC') newDomain = arcpy.TableToDomain_management(tempTable, 'CODE', 'DESC', outWorkspace, domainName, update_option='REPLACE') arcpy.Delete_management(tempTable) arcpy.AddMessage("\t\t-Creating Feature Classes & Tables") for table in allTables: dsc = arcpy.Describe(table) newTableName = "{0}_{1}".format(prefix, table) templateTable = template=os.path.join(surveyGDB, table) if dsc.datatype == u'FeatureClass': newTable = arcpy.CreateFeatureclass_management(outWorkspace, newTableName, "POINT", template=templateTable, spatial_reference=dsc.spatialReference) else: newTable = arcpy.CreateTable_management(outWorkspace, newTableName, template=templateTable) arcpy.AddMessage("\t\t\t-Created {0}".format(newTableName)) #Attach domains to fields tableFields = arcpy.ListFields(table) for field in tableFields: if field.domain != '': arcpy.AssignDomainToField_management(newTable, field.name, field.domain) if dscW.workspaceType == "RemoteDatabase": arcpy.RegisterAsVersioned_management(newTable) arcpy.AddMessage('\t\t-Creating Relationships') #Reconnect Relationship classes, checking for attachments CARDINALITIES = { 'OneToOne': "ONE_TO_ONE", 'OneToMany': "ONE_TO_MANY", 'ManyToMany': "MANY_TO_MANY" } for child in [(c.name, c.datatype) for c in dscW.children if c.datatype == u'RelationshipClass']: dscRC = arcpy.Describe(child[0]) RCOriginTable = dscRC.originClassNames[0] RCDestTable = dscRC.destinationClassNames[0] newOriginTable = "{0}_{1}".format(prefix, RCOriginTable) newOriginPath = os.path.join(outWorkspace, newOriginTable) if dscRC.isAttachmentRelationship: #Simple case - attachments have a dedicated tool arcpy.EnableAttachments_management(newOriginPath) else: newDestTable = "{0}_{1}".format(prefix, RCDestTable) newDestPath = os.path.join(outWorkspace, newDestTable) newRC = os.path.join(outWorkspace, "{0}_{1}".format(prefix, child[0])) relationshipType = "COMPOSITE" if dscRC.isComposite else "SIMPLE" fwd_label = dscRC.forwardPathLabel if dscRC.forwardPathLabel != '' else 'Repeat' bck_label = dscRC.backwardPathLabel if dscRC.backwardPathLabel != '' else 'MainForm' msg_dir = dscRC.notification.upper() cardinality = CARDINALITIES[dscRC.cardinality] attributed = "ATTRIBUTED" if dscRC.isAttributed else "NONE" originclassKeys = dscRC.originClassKeys originclassKeys_dict = {} for key in originclassKeys: originclassKeys_dict[key[1]] = key[0] originPrimaryKey = originclassKeys_dict[u'OriginPrimary'] originForiegnKey = originclassKeys_dict[u'OriginForeign'] arcpy.CreateRelationshipClass_management(newOriginPath, newDestPath, newRC, relationshipType, fwd_label, bck_label, msg_dir, cardinality, attributed, originPrimaryKey, originForiegnKey)
def create_relationship_classes(gdb_path, relationship_objects): arcpy.env.workspace = gdb_path for rel_object in relationship_objects: params = rel_object.output_properties arcpy.CreateRelationshipClass_management(**params)
# Process: Delete arcpy.Delete_management(Pierce_County_gdb, "Workspace") # Process: Create File GDB arcpy.CreateFileGDB_management(data, "Pierce_County", "CURRENT") # Process: Copy Features arcpy.CopyFeatures_management(TaxParcel_PRJ_Layer__3_, Parcels_Assessor, "", "0", "0", "0") # Process: Feature Class to Feature Class #http://gis.stackexchange.com/questions/255/how-to-change-feature-class-and-field-aliases-in-bulk see # build field map arcpy.FeatureClassToFeatureClass_conversion( Parcels_Assessor, Pierce_County_gdb, "TaxParcel", "", "TaxParcelNumber \"TaxParcelNumber\" true true false 10 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,TaxParcel_PRJ_TaxParcelN,-1,-1;TaxParcelType \"TaxParcelType\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,TaxParcel_PRJ_TaxParcelT,-1,-1;TaxParcelLevel \"TaxParcelLevel\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,TaxParcel_PRJ_TaxParcelL,-1,-1;TaxParcelUnit \"TaxParcelUnit\" true true false 80 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,TaxParcel_PRJ_TaxParcelU,-1,-1;TaxParcelUnitType \"TaxParcelUnitType\" true true false 80 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,TaxParcel_PRJ_TaxParce_1,-1,-1;Tax_Payer_Name \"TAXPAYERNAME\" true true false 93 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Taxpayer_TAXPAYERNAME,-1,-1;Taxpayer_CAREOF \"CAREOF\" true true false 50 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Taxpayer_CAREOF,-1,-1;Delivery_Address \"TAXPAYERADDRESS\" true true false 152 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Taxpayer_TAXPAYERADDRESS,-1,-1;Taxpayer_TAXPAYERCITY \"TAXPAYERCITY\" true true false 40 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Taxpayer_TAXPAYERCITY,-1,-1;Taxpayer_TAXPAYERSTATE \"TAXPAYERSTATE\" true true false 5 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Taxpayer_TAXPAYERSTATE,-1,-1;Taxpayer_TAXPAYERCOUNTRY \"TAXPAYERCOUNTRY\" true true false 50 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Taxpayer_TAXPAYERCOUNTRY,-1,-1;Zipcode \"TAXPAYERZIPCODE\" true true false 10 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Taxpayer_TAXPAYERZIPCODE,-1,-1;Tax_account_ACCOUNTTYPE \"ACCOUNTTYPE\" true true false 5 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_ACCOUNTTYPE,-1,-1;Tax_account_PROPERTYTYPE \"PROPERTYTYPE\" true true false 5 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_PROPERTYTYPE,-1,-1;Site_Address \"SITEADDRESS\" true true false 50 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_SITEADDRESS,-1,-1;Use_Code \"USECODE\" true true false 5 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_USECODE,-1,-1;Landuse_Description \"USEDESCRIPTION\" true true false 50 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_USEDESCRIPTION,-1,-1;Tax_account_TAXYEARPRIOR \"TAXYEARPRIOR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TAXYEARPRIOR,-1,-1;Tax_account_TAXCODEAREAPRIORYEAR \"TAXCODEAREAPRIORYEAR\" true true false 10 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TAXCODEAREAPRIORYEAR,-1,-1;Tax_account_EXEMPTIONTYPEPRIORYEAR \"EXEMPTIONTYPEPRIORYEAR\" true true false 40 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_EXEMPTIONTYPEPRIORYEAR,-1,-1;Tax_account_CURRENTUSECODEPRIORYEAR \"CURRENTUSECODEPRIORYEAR\" true true false 5 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_CURRENTUSECODEPRIORYEAR,-1,-1;Tax_account_LANDVALUEPRIORYEAR \"LANDVALUEPRIORYEAR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_LANDVALUEPRIORYEAR,-1,-1;Tax_account_IMPROVEMENTVALUEPRIORYEAR \"IMPROVEMENTVALUEPRIORYEAR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_IMPROVEMENTVALUEPRIORYEAR,-1,-1;Tax_account_TOTALMARKETVALUEPRIORYEAR \"TOTALMARKETVALUEPRIORYEAR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TOTALMARKETVALUEPRIORYEAR,-1,-1;Tax_account_TAXABLEVALUEPRIORYEAR \"TAXABLEVALUEPRIORYEAR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TAXABLEVALUEPRIORYEAR,-1,-1;Tax_account_TAXYEARCURRENT \"TAXYEARCURRENT\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TAXYEARCURRENT,-1,-1;Tax_Area_Code \"TAXCODEAREACURRENTYEAR\" true true false 10 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TAXCODEAREACURRENTYEAR,-1,-1;Exemption_Code \"EXEMPTIONTYPECURRENTYEAR\" true true false 40 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_EXEMPTIONTYPECURRENTYEAR,-1,-1;Tax_account_CURRENTUSECODECURRENTYEAR \"CURRENTUSECODECURRENTYEAR\" true true false 5 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_CURRENTUSECODECURRENTYEAR,-1,-1;Land_Value \"LANDVALUECURRENTYEAR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_LANDVALUECURRENTYEAR,-1,-1;Improvement_Value \"IMPROVEMENTVALUECURRENTYEAR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_IMPROVEMENTVALUECURRENTYEAR,-1,-1;Tax_account_TOTALMARKETVALUECURRENTYEAR \"TOTALMARKETVALUECURRENTYEAR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TOTALMARKETVALUECURRENTYEAR,-1,-1;Taxable_Value \"TAXABLEVALUECURRENTYEAR\" true true false 4 Long 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TAXABLEVALUECURRENTYEAR,-1,-1;Tax_account_RANGE \"RANGE\" true true false 10 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_RANGE,-1,-1;Tax_account_TOWNSHIP \"TOWNSHIP\" true true false 10 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_TOWNSHIP,-1,-1;Tax_account_SECTION \"SECTION\" true true false 20 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_SECTION,-1,-1;Tax_account_QUARTERSECTION \"QUARTERSECTION\" true true false 20 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_QUARTERSECTION,-1,-1;Tax_account_SUBDIVISIONNAME \"SUBDIVISIONNAME\" true true false 50 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_SUBDIVISIONNAME,-1,-1;Tax_account_LOCATEDONPARCEL \"LOCATEDONPARCEL\" true true false 10 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Tax_account_LOCATEDONPARCEL,-1,-1;Appraisal_account_APPRAISALACCOUNTTYPE \"APPRAISALACCOUNTTYPE\" true true false 15 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_APPRAISALACCOUNTTYPE,-1,-1;Business_Name \"BUSINESSNAME\" true true false 50 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_BUSINESSNAME,-1,-1;Appraisal_account_VALUEAREAID \"VALUEAREAID\" true true false 10 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_VALUEAREAID,-1,-1;Appraisal_account_LANDECONOMICAREA \"LANDECONOMICAREA\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LANDECONOMICAREA,-1,-1;Appraisal_account_BUILDINGS \"BUILDINGS\" true true false 2 Short 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_BUILDINGS,-1,-1;Appraisal_account_GROUPACCOUNTNUMBER \"GROUPACCOUNTNUMBER\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_GROUPACCOUNTNUMBER,-1,-1;Appraisal_account_LANDGROSSACRES \"LANDGROSSACRES\" true true false 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LANDGROSSACRES,-1,-1;Land_Acres \"LANDNETACRES\" true true false 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LANDNETACRES,-1,-1;Appraisal_account_LANDGROSSSQUAREFEET \"LANDGROSSSQUAREFEET\" true true false 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LANDGROSSSQUAREFEET,-1,-1;Appraisal_account_LANDNETSQUAREFEET \"LANDNETSQUAREFEET\" true true false 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LANDNETSQUAREFEET,-1,-1;Appraisal_account_LANDGROSSFRONTFEET \"LANDGROSSFRONTFEET\" true true false 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LANDGROSSFRONTFEET,-1,-1;Appraisal_account_LANDWIDTH \"LANDWIDTH\" true true false 2 Short 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LANDWIDTH,-1,-1;Appraisal_account_LANDDEPTH \"LANDDEPTH\" true true false 2 Short 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LANDDEPTH,-1,-1;Appraisal_account_SUBMERGEDAREASQUAREFEET \"SUBMERGEDAREASQUAREFEET\" true true false 2 Short 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_SUBMERGEDAREASQUAREFEET,-1,-1;Appraisal_account_APPRAISALDATE \"APPRAISALDATE\" true true false 8 Date 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_APPRAISALDATE,-1,-1;Appraisal_account_WATERFRONTTYPE \"WATERFRONTTYPE\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_WATERFRONTTYPE,-1,-1;Appraisal_account_VIEWQUALITY \"VIEWQUALITY\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_VIEWQUALITY,-1,-1;Appraisal_account_UTILITYELECTRIC \"UTILITYELECTRIC\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_UTILITYELECTRIC,-1,-1;Appraisal_account_UTILITYSEWER \"UTILITYSEWER\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_UTILITYSEWER,-1,-1;Appraisal_account_UTILITYWATER \"UTILITYWATER\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_UTILITYWATER,-1,-1;Appraisal_account_STREETTYPE \"STREETTYPE\" true true false 30 Text 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_STREETTYPE,-1,-1;Latitude \"LATITUDE\" true true false 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LATITUDE,-1,-1;Longitude \"LONGITUDE\" true true false 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Appraisal_account_LONGITUDE,-1,-1;Shape_Length \"Shape_Length\" false true true 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Shape_Length,-1,-1;Shape_Area \"Shape_Area\" false true true 8 Double 0 0 ,First,#,\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\Parcels_Assessor,Shape_Area,-1,-1", "") # Process: Feature Class to Geodatabase (multiple) arcpy.FeatureClassToGeodatabase_conversion( "\\\\geobase-win\\ced\\GADS\\R2014\\R506\\Process\\data\\Pierce_County.gdb\\TaxParcel", Pierce_County_FINAL_gdb) # Process: Create Relationship Class arcpy.CreateRelationshipClass_management(TaxParcel__3_, Tax_description, TaxParcel_Tax_description, "SIMPLE", "Tax_description", "TaxParcel", "NONE", "ONE_TO_MANY", "NONE", "TaxParcelNumber", "PARCELNUMBER", "", "")
if not arcpy.ListFields(destinationTablePath,originFKey): AddMsgAndPrint("\t" + originFKey + " NOT FOUND") continue relName = "x" + originTable.capitalize() + "_" + destinationTable.capitalize() theCardinality = "ONE_TO_MANY" # create Forward Label i.e. "> Horizon AASHTO Table" if tblAliasDict.has_key(destinationTable): fwdLabel = "> " + tblAliasDict.get(destinationTable) + " Table" else: fwdLabel = destinationTable + " Table" # create Backward Label i.e. "< Horizon Table" if tblAliasDict.has_key(originTable): backLabel = "< " + tblAliasDict.get(originTable) + " Table" else: backLabel = "< " + originTable + " Table" if not arcpy.Exists(relName): arcpy.CreateRelationshipClass_management(originTablePath, destinationTablePath, relName, "SIMPLE", fwdLabel, backLabel, "NONE", theCardinality, "NONE", originPKey, originFKey, "","") AddMsgAndPrint("\t" + relName) else: AddMsgAndPrint("\t" + relName)
# Add History # =========== # TODO: ArcGIS provides no way to add the history tables. # I think I need a direct database connection, then copy the *_H tables, # then convert them to a feature class. # Add Relationships # ================= print("Creating Relationships") arcpy.env.workspace = new_fgdb # Asset to Location # fmt: off arcpy.CreateRelationshipClass_management("FMSSExport", "FMSSExport_Asset", "Location_Asset_Relation", "COMPOSITE", "Assets", "Owning Location", "NONE", "ONE_TO_MANY", "NONE", "Location", "Location") # GIS Features to Locations arcpy.CreateRelationshipClass_management( "FMSSExport", "AKR_BLDG_PY", "Location_BuildingFootprint_Relation", "SIMPLE", "Building Footprints", "FMSS Location Record", "NONE", "ONE_TO_MANY", "NONE", "Location", "FACLOCID") arcpy.CreateRelationshipClass_management("FMSSExport", "AKR_BLDG_PT", "Location_BuildingCenter_Relation", "SIMPLE", "Building Centers", "FMSS Location Record", "NONE", "ONE_TO_MANY", "NONE", "Location", "FACLOCID") arcpy.CreateRelationshipClass_management("FMSSExport", "PARKLOTS_PY", "Location_ParkingLot_Relation",
log, 'Failed to create a domain for property: ' + '{0}! Exiting...'.format(prop)) GWRutils.logMessage(log, str(e)) sys.exit() # Create needed relationship classes rel_classes = [ 'Property_PropAct', 'Activity_Chemical_Existing', 'Activity_Chemical_New', 'HVunit_OPTproduct' ] # Property_PropAct try: arcpy.CreateRelationshipClass_management(property_fc, activity_fc, rel_classes[0], 'SIMPLE', 'forward', 'backward', 'NONE', 'ONE_TO_MANY', 'NONE', 'ObjectID', 'PropertyOID') print('...Relationship class created: {0}'.format(rel_classes[0])) GWRutils.logMessage( log, '...Relationship class created: {0}'.format(rel_classes[0])) except Exception as e: print('Failed to create relationship class: {0}! Exiting...'.format( rel_classes[0])) print(e) GWRutils.logMessage( log, 'Failed to create relationship class: {0}! ' + 'Exiting...'.format(rel_classes[0])) GWRutils.logMessage(log, str(e)) sys.exit()
# Import and process de02 defects report: # de02: Table to Table, xls to gdb arcpy.TableToTable_conversion(de02Input, defectGdb, "de02") # Link the two reports/feature classes for GIS users: # Create relationship class between 'de05' feature class and 'de02' table, which contains additional inspection information # The relationship is one to many because there may be multiple de02 rows per de05 feature. de02FC = "C:/Temp/Assignment/DefectInspections.gdb/de02" # Create de02 feature class variable relClass = "DefectInspections.gdb/DefectsRel" forLabel = "Attributes from de02" # Sets de02 relationship label when inspecting features in GIS software backLabel = "Attributes and Features from de05" # Sets de05 relationship label when inspecting features in GIS software primaryKey = "Defect_Id" foreignKey = "Defect_Id" arcpy.CreateRelationshipClass_management(de05v3, de02FC, relClass, "SIMPLE", forLabel, backLabel, "NONE", "ONE_TO_MANY", "NONE", primaryKey, foreignKey) # Add and Calculate field for setting the Display expression field for GIS end users # The display expression defaults to the first field of string type that contains the text "name" # More info: https://desktop.arcgis.com/en/arcmap/10.3/manage-data/tables/understanding-the-display-expression-for-a-field.htm # de05: arcpy.AddField_management(de05v3, "Display_Name", "STRING") arcpy.CalculateField_management(de05v3, "Display_Name", "\"de05: \" & [Defect_Id]") # de02: arcpy.AddField_management(de02FC, "Display_Name", "STRING") arcpy.CalculateField_management(de02FC, "Display_Name", "\"de02: \" & [Defect_Id]") print("Data analysis complete. Beginning data display exports...")
def create_rel_classes(): print("Relationship classes") for _rel in relClassDict: _out_relationship_class = os.path.join(get_workspace(), featuredataset, _rel) # _out_relationship_class = os.path.join(GetWorkspace(), _rel) if arcpy.Exists(_out_relationship_class) is False: _origin_table = os.path.join( get_workspace(), featuredataset, relClassDict[_rel][1] ) if relClassDict[_rel][2] == "FIDA_LFP": _relationship_type = "SIMPLE" elif relClassDict[_rel][2] == "FIDA_HFP": _relationship_type = "SIMPLE" elif relClassDict[_rel][2] == "FIDA_LSN": _relationship_type = "SIMPLE" elif relClassDict[_rel][2] == "FIDA_KONTAKT": _relationship_type = "SIMPLE" else: _relationship_type = "COMPOSITE" _destination_table = os.path.join(get_workspace(), relClassDict[_rel][2]) _forward_label = relClassDict[_rel][3] _backward_label = relClassDict[_rel][4] _cardinality = relClassDict[_rel][0] # _origin_primary_key = "PK" geändert damit Checkout möglich wird _origin_primary_key = "GlobalID" if _cardinality == "MANY_TO_MANY": _origin_foreign_key = "ORIGNIVLINIEN_HFP" _destination_primary_key = "GlobalID" _destination_foreign_key = "DESTHFP_NIVLINIEN" else: _origin_foreign_key = "FK_" + relClassDict[_rel][1] _destination_primary_key = "" _destination_foreign_key = "" arcpy.CreateRelationshipClass_management( origin_table=_origin_table, destination_table=_destination_table, out_relationship_class=_out_relationship_class, relationship_type=_relationship_type, forward_label=_forward_label, backward_label=_backward_label, cardinality=_cardinality, origin_primary_key=_origin_primary_key, origin_foreign_key=_origin_foreign_key, destination_primary_key=_destination_primary_key, destination_foreign_key=_destination_foreign_key, ) print( "Relationship class between origin_table: {} and destination_table: {}".format( _origin_table, _destination_table ) ) print("Create Relationship class: " + _rel) if _rel == "FIDA_NIVLINIEN_HFP": arcpy.AddGlobalIDs_management(_out_relationship_class) if sde_fida is True: arcpy.EnableEditorTracking_management( in_dataset=_out_relationship_class, creator_field="CREATOR_FIELD", creation_date_field="CREATOR_DATE_FIELD", last_editor_field="LAST_EDITOR_FIELD", last_edit_date_field="LAST_EDITOR_DATE_FIELD", add_fields="ADD_FIELDS", record_dates_in="UTC", ) print("add GlobalID and EditorTracking to FIDA_NIVLINIEN_HFP") else: print("Relationship class already created: " + _rel)
sdvLayer = arcpy.mapping.ListLayers(mxd, layerName, df)[0] gdb = os.path.dirname(arcpy.Describe(sdvLayer).catalogPath) env.workspace = gdb inputTbl = os.path.join(gdb, "SDV_Data") # table containing pre-aggregated data in gSSURGO database legendTbl = os.path.join(gdb, "legend") # table containing legend.areaname # Cleanup query table from previous run sdvTableName = "SDV_Data" #if arcpy.Exists(sdvTbl): # arcpy.Delete_management(sdvTbl, "FEATURELAYER") if arcpy.Exists(inputTbl): # Create relate between rating table and legend table to get areaname arcpy.CreateRelationshipClass_management(legendTbl, inputTbl, os.path.join(gdb, "xLegend_SDVData"), "SIMPLE", "SDV_Data", "Legend", None, "ONE_TO_ONE", None, "AREASYMBOL", "AREASYMBOL", "","") # Get SDV map layer information layerFields = arcpy.Describe(layerName).fields layerField = layerFields[-1] # assume the last field is the rating #layerRatingField = "SDV_Data." + layerField.baseName.upper().encode('ascii') layerRatingField = layerField.baseName.upper().encode('ascii') fieldType = layerField.type.lower() # Get SDV Rating table information fmFields = list() ratingFields = arcpy.Describe(inputTbl).fields ratingField = ratingFields[-1] # assume the last field is the rating ratingType = ratingFields[-1].type.lower() #ratingFieldName = "SDV_Data." + layerField.name.upper()
# ---------------------------------------------------------------------------------------------------------- Setup Topology # Validate Topology with a cluster of 0.1 meters if createTopology(FDpath): arcpy.SetProgressorLabel("Validating Topology at 0.1 meters") arcpy.ValidateTopology_management(os.path.join(FDpath,"FD_RTSD_Topology")) AddMsgAndPrint(" \tValidated Topology at 0.1 meters",0) else: AddMsgAndPrint(" \n\tFailed to Create Topology. Create Topology Manually",2) # Create Relationship class between project_record and SAPOLYGON feature class arcpy.SetProgressorLabel("Creating Relationship Class between Project_Record & SAPOLYGON") prjRecTable = os.path.join(FGDBpath,'ProjectRecord' + os.sep + 'Project_Record') saPolyPath = os.path.join(FDpath,soilSaFC) relName = "x" + prjRecTable.capitalize() + "_" + soilSaFC arcpy.CreateRelationshipClass_management(prjRecTable, saPolyPath, relName, "SIMPLE", "> SAPOLYGON", "< Project_Record", "NONE", "ONE_TO_ONE", "NONE", "AREASYMBOL", "AREASYMBOL", "", "") AddMsgAndPrint("\n" + "Successfully Created Relationship Class") arcpy.SetProgressorLabel("Compacting " + os.path.basename(FGDBpath)) arcpy.Compact_management(FGDBpath) AddMsgAndPrint("\n" + "Successfully Compacted " + os.path.basename(FGDBpath)) if updateAliasNames(regionChoice, FDpath): AddMsgAndPrint("\nSuccessfully Updated Alias Names for Feature Classes within " + os.path.basename(FGDBpath)) else: AddMsgAndPrint("\nUnable to Update Alias Names for Feature Classes within " + os.path.basename(FGDBpath),2) # ----------------------------------------------------------------------------------------- AddMsgAndPrint(" \n*****************************************************************************************",1) AddMsgAndPrint("Total # of SSURGO Datasets Appended: " + str(splitThousands(len(soilShpList))),1) AddMsgAndPrint(" \tTotal # of Mapunit Polygons: " + str(splitThousands(arcpy.GetCount_management(FDpath + os.sep + soilFC).getOutput(0))),1)
def AddRelationships(self, locyears, unityears, occyears): # Route - County arcpy.CreateRelationshipClass_management(self.countyFC, self.routeFC, self.gdb + '\\Coun_Route', "SIMPLE", "Route", "County", "NONE", "ONE_TO_MANY", "NONE", fields.route.County['name'], fields.route.County['name']) # Route - Attributes arcpy.CreateRelationshipClass_management( self.routeFC, self.CurbFC, self.gdb + '\\Route_Curb', "SIMPLE", "Curb", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.LanesFC, self.gdb + '\\Route_Lane', "SIMPLE", "Lane", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.LaneWidFC, self.gdb + '\\Route_LaneWid', "SIMPLE", "LaneWid", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.MedTypeFC, self.gdb + '\\Route_MedType', "SIMPLE", "MedTyp", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.MedWidFC, self.gdb + '\\Route_MedWid', "SIMPLE", "MedWid", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.OtherFC, self.gdb + '\\Route_Other', "SIMPLE", "Other", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.ShTrtFC, self.gdb + '\\Route_ShTrt', "SIMPLE", "ShTrt", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.ShWidFC, self.gdb + '\\Route_ShWid', "SIMPLE", "ShWid", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.SurWidFC, self.gdb + '\\Route_SurWid', "SIMPLE", "SurWid", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.SwTrtFC, self.gdb + '\\Route_SwTrt', "SIMPLE", "SwTrt", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) arcpy.CreateRelationshipClass_management( self.routeFC, self.RailCFC, self.gdb + '\\Route_Rail', "SIMPLE", "RailC", "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Route_LRS['name'], fields.route.Route_LRS['name']) # Loc - County for y in locyears: arcpy.CreateRelationshipClass_management( self.countyFC, self.gdb + '\\' + self.loc + str(y), self.gdb + '\\Coun_Loc' + str(y), "SIMPLE", "Loc" + str(y), "County", "NONE", "ONE_TO_MANY", "NONE", fields.route.County['name'], fields.loc.CTY['name']) # Loc - Route for y in locyears: arcpy.CreateRelationshipClass_management( self.routeFC, self.gdb + '\\' + self.loc + str(y), self.gdb + '\\Route_Loc' + str(y), "SIMPLE", "Loc" + str(y), "Route", "NONE", "ONE_TO_MANY", "NONE", fields.route.Name['name'], fields.loc.MLRS['name']) # Loc - Jurisdiction for y in locyears: arcpy.CreateRelationshipClass_management( self.jurFC, self.gdb + '\\' + self.loc + str(y), self.gdb + '\\Jur_Loc' + str(y), "SIMPLE", "Loc" + str(y), "Jur", "NONE", "ONE_TO_MANY", "NONE", 'JUR', fields.loc.JUR['name']) # Loc - Unit for y in list(set(locyears).intersection(unityears)): arcpy.CreateRelationshipClass_management( self.gdb + '\\' + self.loc + str(y), self.gdb + '\\' + self.unit + str(y), self.gdb + '\\Loc_Unit' + str(y), "SIMPLE", "Unit", "Loc", "NONE", "ONE_TO_MANY", "NONE", fields.loc.ANO['name'], fields.loc.ANO['name']) # Unit - Occ for y in list(set(unityears).intersection(occyears)): arcpy.CreateRelationshipClass_management( self.gdb + '\\' + self.unit + str(y), self.gdb + '\\' + self.occ + str(y), self.gdb + '\\Unit_Occ' + str(y), "SIMPLE", "Occ", "Unit", "NONE", "ONE_TO_MANY", "NONE", fields.unit.ID['name'], fields.unit.ID['name'])
def execute(self, parameters, messages): configuration_files_location = str(parameters[0].value) arcpy.env.workspace = parameters[1].value spatial_reference_param = parameters[3].value create_classes = parameters[4].values create_tables = parameters[5].values create_relationships = parameters[6].values create_domains = parameters[7].values create_multipatches = True if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") else: arcpy.AddWarning( "3D Analyst extension is not licensed. The script will not create Multipatch feature classes." ) create_multipatches = False arcpy.AddMessage("Creating Domains...") if create_domains is not None: # read configuration file for domains createDomainParams = {} for line in open(configuration_files_location + '\\Domains.csv'): line = line.rstrip() lineParams = line.split(";") createDomainParams[lineParams[0]] = lineParams[1:] # create domains as indicated by user for new_domain in create_domains: if new_domain not in arcpy.da.ListDomains(): arcpy.AddMessage("Adding domain " + new_domain + " with params " + str(createDomainParams[new_domain])) arcpy.CreateDomain_management( arcpy.env.workspace, new_domain, domain_description=createDomainParams[new_domain][0], field_type=createDomainParams[new_domain][1], domain_type=createDomainParams[new_domain][2]) for line in open(configuration_files_location + '\\CodedValues.csv'): line = line.rstrip() codedValueParams = line.split(";") if codedValueParams[0] == new_domain: arcpy.AddCodedValueToDomain_management( arcpy.env.workspace, domain_name=codedValueParams[0], code=codedValueParams[1], code_description=codedValueParams[2]) arcpy.AddMessage("...Added coded value " + codedValueParams[1] + " to domain " + codedValueParams[0]) arcpy.AddMessage("Completed adding of Domains and Coded Values") # read configuration file for feature classes createClassParams = {} for line in open(configuration_files_location + '\\FeatureClasses.csv'): line = line.rstrip() lineClassParams = line.split(";") createClassParams[lineClassParams[0]] = lineClassParams[1:] # create Feature classes that have been selected. arcpy.AddMessage("Create Feature classes...") if create_classes is not None: for new_class in create_classes: # Test existence of class to create first. if not arcpy.ListFeatureClasses(new_class): arcpy.AddMessage("Adding Feature class " + new_class + ", type " + createClassParams[new_class][0]) # Create class if str(createClassParams[new_class] [0]) == "MULTIPATCH" and create_multipatches: arcpy.Import3DFiles_3d( in_files=configuration_files_location + '\\multipatch_template.wrl', out_featureClass=new_class, root_per_feature="ONE_FILE_ONE_FEATURE", spatial_reference=spatial_reference_param) arcpy.DeleteFeatures_management(new_class) else: arcpy.CreateFeatureclass_management( arcpy.env.workspace, new_class, geometry_type=createClassParams[new_class][0], template=None, has_m=createClassParams[new_class][1], has_z=createClassParams[new_class][2], spatial_reference=spatial_reference_param) arcpy.AddField_management(new_class, "name", "TEXT", None, None, 100, "Name", None, None) # add common attributes arcpy.AddField_management(new_class, new_class + "FID", "TEXT", None, None, 50, new_class + " Feature ID", None, None) arcpy.AddField_management(new_class, "description", "TEXT", None, None, 250, "Description", None, None) arcpy.AddField_management(new_class, "attribution", "TEXT", None, None, 250, "Attribution/Source", None, None) arcpy.AddField_management(new_class, "subtype", "TEXT", None, None, 50, "Subtype", None, None) # add specific attributes to feature classes that have been selected for line in open(configuration_files_location + '\\FeatureClassAttributes.csv'): line = line.rstrip() attributeParams = line.split(";") if attributeParams[0] in create_classes: arcpy.AddMessage("Adding Attribute " + attributeParams[1] + " to table " + attributeParams[0] + ", parameters " + str(attributeParams[2:])) arcpy.AddField_management( in_table=attributeParams[0], field_name=attributeParams[1], field_type=attributeParams[2], field_length=attributeParams[3], field_alias=attributeParams[4], field_is_nullable=attributeParams[5], field_is_required=attributeParams[6]) # add domains to field if defined if str(attributeParams[7]) != "NO_DOMAIN": arcpy.AssignDomainToField_management( in_table=attributeParams[0], field_name=attributeParams[1], domain_name=attributeParams[7]) arcpy.AddMessage("Added fields to Feature Classes") # read configuration file for tables createClassParams = {} for line in open(configuration_files_location + '\\Tables.csv'): line = line.rstrip() lineClassParams = line.split(";") createClassParams[lineClassParams[0]] = lineClassParams[1:] # create Tables that have been selected. arcpy.AddMessage("Create Tables...") if create_tables is not None: for new_class in create_tables: # Test existence of class to create first. if arcpy.ListTables(new_class): break # Then create table (if necessary) arcpy.AddMessage("Adding Table class " + new_class) arcpy.CreateTable_management(arcpy.env.workspace, new_class) # add specific attributes for tables for line in open(configuration_files_location + '\\TableAttributes.csv'): line = line.rstrip() attributeParams = line.split(";") if attributeParams[0] in create_tables: arcpy.AddField_management( in_table=attributeParams[0], field_name=attributeParams[1], field_type=attributeParams[2], field_length=attributeParams[3], field_alias=attributeParams[4], field_is_nullable=attributeParams[5], field_is_required=attributeParams[6]) # add domains to field if defined if str(attributeParams[7]) != "NO_DOMAIN": arcpy.AssignDomainToField_management( in_table=attributeParams[0], field_name=attributeParams[1], domain_name=attributeParams[7]) # create Relationship classes arcpy.AddMessage("Create Relationship classes...") createClassParams = {} for line in open(configuration_files_location + '\\RelationshipClasses.csv'): line = line.rstrip() lineClassParams = line.split(";") createClassParams[lineClassParams[0]] = lineClassParams[1:] if create_relationships is not None: for new_class in create_relationships: # check if origin and destination relationship classes have been created beforehand. if (arcpy.ListTables(createClassParams[new_class][0]) or arcpy.ListFeatureClasses( createClassParams[new_class][0]) ) and (arcpy.ListTables(createClassParams[new_class][1]) or arcpy.ListFeatureClasses( createClassParams[new_class][1])): arcpy.AddMessage("Adding Relationship class " + new_class) arcpy.CreateRelationshipClass_management( origin_table=createClassParams[new_class][0], destination_table=createClassParams[new_class][1], out_relationship_class=new_class, relationship_type=createClassParams[new_class][2], forward_label=createClassParams[new_class][3], backward_label=createClassParams[new_class][4], message_direction=createClassParams[new_class][5], cardinality=createClassParams[new_class][6], attributed=createClassParams[new_class][7], origin_primary_key=createClassParams[new_class][8], origin_foreign_key=createClassParams[new_class][9]) if create_multipatches: arcpy.CheckInExtension("3D") # ------------------------------------------------------------------------------
arcpy.Merge_management(["fromInter", "toInter"], "mergedRtes") print "Merged" ## fields = arcpy.ListFields("mergedRtes", "INTERSECTION_ID") ## for field in fields: ## field.type = "Integer" arcpy.DeleteIdentical_management("mergedRtes", ["RTE_NM", "Intersection_ID"]) print "Identical features deleted" arcpy.CreateRelationshipClass_management( interFC, "mergedRtes", outFC, "SIMPLE", "Attributes from mergedRtes", "Atts and Features from intersectionsFC", "NONE", "ONE_TO_MANY", origin_primary_key="INTERSECTION_ID", origin_foreign_key="INTERSECTION_ID") print "Complete" except Exception as e: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string # pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str( sys.exc_info()[1])
vfieldmappings.addTable(violationsfinal) arcpy.Append_management(violationsstaging, violationsfinal, schema_type="NO_TEST", field_mapping=vfieldmappings) ############################################################################### # CREATE RELATIONSHIP CLASS IF NOT EXISTS if not arcpy.Exists(facilitiesviolations_relationship): arcpy.CreateRelationshipClass_management( origin_table=facilitiesfinal, destination_table=violationsfinal, out_relationship_class=facilitiesviolations_relationship, relationship_type="SIMPLE", forward_label="VIOLATIONS", backward_label="FACILITIES", message_direction="NONE", cardinality="ONE_TO_MANY", attributed="NONE", origin_primary_key="FACILITY_ID", origin_foreign_key="FACILITY_ID", destination_primary_key="", destination_foreign_key="") ############################################################################### # LOG COMPLETION TIME endtime = datetime.datetime.now() # Process Completed log.write(" Completed successfully in " + str(endtime - starttime) + "\n") log.write("\n")
# Rebuild relationship classes. arcpy.AddMessage('\nRebuilding relationship classes...') for route_system in MHN.route_systems: header = route_system header_name = MHN.break_path(header)['name'] itin = MHN.route_systems[route_system][0] itin_name = MHN.break_path(itin)['name'] common_id_field = MHN.route_systems[route_system][1] rel_arcs = os.path.join(MHN.gdb, 'rel_arcs_to_{0}'.format(itin_name)) rel_sys = os.path.join( MHN.gdb, 'rel_{0}_to_{1}'.format( itin_name.rsplit('_', 1)[0], itin_name.rsplit('_', 1)[1])) arcpy.CreateRelationshipClass_management(MHN.arc, itin, rel_arcs, 'SIMPLE', itin_name, MHN.arc_name, 'NONE', 'ONE_TO_MANY', 'NONE', 'ABB', 'ABB') arcpy.CreateRelationshipClass_management(header, itin, rel_sys, 'COMPOSITE', itin_name, header_name, 'FORWARD', 'ONE_TO_MANY', 'NONE', common_id_field, common_id_field) rel_pnr = os.path.join(MHN.gdb, 'rel_nodes_to_{0}'.format(MHN.pnr_name)) arcpy.CreateRelationshipClass_management(MHN.node, MHN.pnr, rel_pnr, 'SIMPLE', MHN.pnr_name, MHN.node_name, 'NONE', 'ONE_TO_MANY', 'NONE', 'NODE', 'NODE') # Clean up. arcpy.Compact_management(MHN.gdb) arcpy.Delete_management(MHN.mem)
arcpy.CreateTable_management(coding_table_path['dir'], coding_table_path['name'], updated_coding_table) arcpy.Append_management(updated_coding_table, coding_table, 'TEST') arcpy.Delete_management(updated_coding_table) # Rebuild relationship classes. arcpy.AddMessage('{0}Rebuilding relationship classes...'.format('\n')) hwyproj_name = MHN.break_path(MHN.hwyproj)['name'] coding_table_name = MHN.break_path(coding_table)['name'] rel_arcs = os.path.join(MHN.gdb, 'rel_arcs_to_{0}'.format(coding_table_name)) rel_sys = os.path.join( MHN.gdb, 'rel_{0}_to_{1}'.format( coding_table_name.rsplit('_', 1)[0], coding_table_name.rsplit('_', 1)[1])) arcpy.CreateRelationshipClass_management(MHN.arc, coding_table, rel_arcs, 'SIMPLE', coding_table_name, MHN.arc_name, 'NONE', 'ONE_TO_MANY', 'NONE', 'ABB', 'ABB') arcpy.CreateRelationshipClass_management(MHN.hwyproj, coding_table, rel_sys, 'COMPOSITE', coding_table_name, hwyproj_name, 'FORWARD', 'ONE_TO_MANY', 'NONE', common_id_field, common_id_field) # Clean up. arcpy.Compact_management(MHN.gdb) arcpy.Delete_management(MHN.mem) arcpy.Delete_management(backup_gdb) arcpy.AddMessage( '{0}Highway project coding successfully imported!{0}'.format('\n'))
def build_relationships(fgdb, protocol): """Create the relationships between the various PO feature classes.""" gps_points_table = os.path.join(fgdb, protocol["csv"]["gps_points"]["name"]) track_logs_table = os.path.join(fgdb, protocol["csv"]["track_logs"]["name"]) observations_table = os.path.join(fgdb, "Observations") arcpy.CreateRelationshipClass_management( track_logs_table, gps_points_table, os.path.join(fgdb, "GpsPoints_to_TrackLog"), "COMPOSITE", "GpsPoints", "TrackLog", "NONE", "ONE_TO_MANY", "NONE", "OBJECTID", "TrackLog_ID", ) arcpy.CreateRelationshipClass_management( gps_points_table, observations_table, os.path.join(fgdb, "Observations_to_GpsPoint"), "SIMPLE", "Observations", "GpsPoints", "NONE", "ONE_TO_ONE", "NONE", "OBJECTID", "GpsPoint_ID", ) for feature_obj in protocol["features"]: feature = arcpy.ValidateTableName(feature_obj["name"], fgdb) feature_table = os.path.join(fgdb, feature) arcpy.CreateRelationshipClass_management( gps_points_table, feature_table, os.path.join(fgdb, "{0}_to_GpsPoint".format(feature)), "SIMPLE", feature, "GpsPoint", "NONE", "ONE_TO_ONE", "NONE", "OBJECTID", "GpsPoint_ID", ) arcpy.CreateRelationshipClass_management( observations_table, feature_table, os.path.join(fgdb, "{0}_to_Observation".format(feature)), "SIMPLE", feature, "Observation", "NONE", "ONE_TO_ONE", "NONE", "OBJECTID", "Observation_ID", )