err = "Exception caught: unable to update row"
                printRow(row, names)
                dla.showTraceback()
                dla.addError(err)
    except:
        dla._errCount += 1
        success = False
        err = "Exception caught: unable to update dataset"
        if row != None:
            printRow(row, names)
        dla.showTraceback()
        dla.addError(err)

    finally:
        del updateCursor
        dla.cleanupGarbage()
        arcpy.ResetProgressor()

    return success


def getSplit(sourceValue, splitter, part):

    strVal = None
    try:
        strVal = sourceValue.split(str(splitter))[int(part)]
    except:
        pass

    return strVal
def calculate(xmlFileName, workspace, name, ignore):

    dla.workspace = workspace
    success = True
    arcpy.ClearWorkspaceCache_management(dla.workspace)
    xmlDoc = dla.getXmlDoc(xmlFileName)

    arcpy.env.Workspace = dla.workspace
    table = dla.getTempTable(name)

    if not arcpy.Exists(table):
        dla.addError("Feature Class " + table + " does not exist, exiting")
        arcpy.SetParameter(SUCCESS, False)
        return
    if not arcpy.TestSchemaLock(table):
        dla.addError("Unable to obtain a schema lock for " + table +
                     ", exiting")
        arcpy.SetParameter(SUCCESS, False)
        return -1

    desc = arcpy.Describe(table)
    fields = dla.getXmlElements(xmlFileName, "Field")
    sourceFields = dla.getXmlElements(xmlFileName, "SourceField")
    targetFields = dla.getXmlElements(xmlFileName, "TargetField")
    attrs = [f.name for f in arcpy.ListFields(table)]

    for field in fields:
        arcpy.env.Workspace = dla.workspace
        targetName = dla.getNodeValue(field, "TargetName")
        sourceName = dla.getNodeValue(field, "SourceName")

        type = "String"
        length = "50"
        for target in targetFields:
            nm = target.getAttributeNode("Name").nodeValue
            if nm == targetName:
                type = target.getAttributeNode("Type").nodeValue
                length = target.getAttributeNode("Length").nodeValue
        # uppercase compare, later need to check for orig/upper name for calc
        #ups = [nm.upper() for nm in attrs]
        dla.addDlaField(table, targetName, field, attrs, type, length)

    allFields = sourceFields + targetFields
    names = []
    types = []
    lengths = []
    for field in allFields:
        nm = field.getAttributeNode("Name").nodeValue
        if nm != dla.noneName:
            names.append(nm)
            typ = field.getAttributeNode("Type").nodeValue
            leng = field.getAttributeNode("Length").nodeValue
            types.append(typ)
            lengths.append(leng)

    retVal = setFieldValues(table, fields, names, types, lengths)
    if retVal == False:
        success = False
    arcpy.ClearWorkspaceCache_management(dla.workspace)
    dla.cleanupGarbage()

    arcpy.ResetProgressor()
    if ignore == True:
        success = True
    return success
예제 #3
0
def calculate(xmlFileName,workspace,name,ignore):

    dla.workspace = workspace    
    success = True
    arcpy.ClearWorkspaceCache_management(dla.workspace)
    xmlDoc = dla.getXmlDoc(xmlFileName)
    dla.addMessage("Field Calculator: " + xmlFileName)
    arcpy.env.Workspace = dla.workspace
    table = dla.getTempTable(name)

    if not arcpy.Exists(table):
        dla.addError("Feature Class " + table + " does not exist, exiting")
        arcpy.SetParameter(SUCCESS, False)
        return
    if not arcpy.TestSchemaLock(table):
        dla.addError("Unable to obtain a schema lock for " + table + ", exiting")
        arcpy.SetParameter(SUCCESS, False)
        return -1
    
    desc = arcpy.Describe(table)
    fields = dla.getXmlElements(xmlFileName,"Field")
    sourceFields = dla.getXmlElements(xmlFileName,"SourceField")
    targetFields = dla.getXmlElements(xmlFileName,"TargetField")
    attrs = [f.name for f in arcpy.ListFields(table)]

    for field in fields:
        arcpy.env.Workspace = dla.workspace
        targetName = dla.getNodeValue(field,"TargetName")
        sourceName = dla.getNodeValue(field,"SourceName")
            
        ftype = "String"
        length = "50"
        for target in targetFields:
            nm = target.getAttributeNode("Name").nodeValue
            if  nm == targetName:
                ftype = target.getAttributeNode("Type").nodeValue
                length = target.getAttributeNode("Length").nodeValue
        # uppercase compare, later need to check for orig/upper name for calc
        #ups = [nm.upper() for nm in attrs]
        dla.addDlaField(table,targetName,field,attrs,ftype,length)

    allFields = sourceFields + targetFields
    desc = arcpy.Describe(table)
    layerNames = []
    names = []
    ftypes = []
    lengths = []
    ignore = ['FID','OBJECTID','GLOBALID','SHAPE','SHAPE_AREA','SHAPE_LENGTH','SHAPE_LEN','STLENGTH()','STAREA()','raster']
    for name in ['OIDFieldName','ShapeFieldName','LengthFieldName','AreaFieldName','GlobalIDFieldName','RasterFieldName']:
        try:
            val = eval("desc." + name)
            val = val[val.rfind('.')+1:] 
            ignore.append(val).upper()
        except:
            pass

    for field in desc.fields:
        if field.name.upper() not in ignore:
            layerNames.append(field.name.upper())

    for field in allFields:
        nm = field.getAttributeNode("Name").nodeValue
        if nm != dla.noneName and nm.upper() not in ignore and nm.upper() in layerNames:
            try:
                names.index(nm)
            except:
                names.append(nm)
                typ = field.getAttributeNode("Type").nodeValue
                leng = field.getAttributeNode("Length").nodeValue      
                ftypes.append(typ)
                lengths.append(leng)

    retVal = setFieldValues(table,fields,names,ftypes,lengths)
    if retVal == False:
        success = False
    arcpy.ClearWorkspaceCache_management(dla.workspace)
    dla.cleanupGarbage()

    arcpy.ResetProgressor()
    if ignore == True:
        success = True
    return success
예제 #4
0
def setFieldValues(table,fields,names,ftypes,lengths):
    # from source xml file match old values to new values to prepare for append to target geodatabase
    success = False
    row = None
    try:
        updateCursor = arcpy.da.UpdateCursor(table,names)

        result = arcpy.GetCount_management(table)
        numFeat = int(result.getOutput(0))
        dla.addMessage(table + ", " + str(numFeat) + " features")
        i = 0
        arcpy.SetProgressor("Step","Calculating " + table + "...",0,numFeat,getProgressUpdate(numFeat))
        
        for row in updateCursor:
            success = True
            if dla._errCount > dla.maxErrorCount:
                #dla.addMessage("Exceeded max number of errors in dla.maxErrorCount: " + str(dla.maxErrorCount))
                dla.addError("Exceeded max number of errors in dla.maxErrorCount: " + str(dla.maxErrorCount))
                return False
            if i > dla.maxrows:
                #dla.addMessage("Exceeded max number of rows supported in dla.maxrows: " + str(dla.maxrows))
                dla.addError("Exceeded max number of rows supported in dla.maxrows: " + str(dla.maxrows))
                return True
            i = i + 1
            setProgressor(i,numFeat)
            
            for field in fields:
                method = "None"
                sourceName = dla.getNodeValue(field,"SourceName")
                targetName = dla.getNodeValue(field,"TargetName")
                    
                targetValue = getTargetValue(row,field,names,sourceName,targetName)
                sourceValue = getSourceValue(row,names,sourceName,targetName)
                method = dla.getNodeValue(field,"Method").replace(" ","")
                fnum = names.index(targetName)

                if method == "None" or (method == "Copy" and sourceName == dla._noneFieldName):
                    val = None
                    method = "None"
                elif method == "Copy":
                    val = sourceValue
                elif method == "DefaultValue":
                    val = dla.getNodeValue(field,"DefaultValue")
                elif method == "SetValue":
                    val = dla.getNodeValue(field,"SetValue")
                elif method == "ValueMap":
                    val = getValueMap(row,names,sourceValue,field)
                elif method == "ChangeCase":
                    case = dla.getNodeValue(field,method)                    
                    expression = getChangeCase(sourceValue,case)
                    val = getExpression(row,names,expression)
                elif method == "Concatenate":
                    val = getConcatenate(row,names,field)
                elif method == "Left":
                    chars = dla.getNodeValue(field,"Left")
                    val = getSubstring(sourceValue,"0",chars)
                elif method == "Right":
                    chars = dla.getNodeValue(field,"Right")
                    val = getSubstring(sourceValue,len(str(sourceValue))-int(chars),len(str(sourceValue)))
                elif method == "Substring":
                    start = int(dla.getNodeValue(field,"Start"))
                    lngth = int(dla.getNodeValue(field,"Length"))
                    if sourceValue != None:
                        lngth = start + lngth
                    val = getSubstring(sourceValue,start,lngth)
                elif method == "Split":
                    splitter = dla.getNodeValue(field,"SplitAt")
                    splitter = splitter.replace("(space)"," ")
                    part = dla.getNodeValue(field,"Part")
                    val = getSplit(sourceValue,splitter,part)
                elif method == "ConditionalValue":
                    sname = dla.getNodeValue(field,"SourceName")
                    oper = dla.getNodeValue(field,"Oper")
                    iif = dla.getNodeValue(field,"If")
                    if iif != " " and type(iif) == 'str':
                        for name in names:
                            if name in iif:
                                iif = iif.replace(name,"|"+name+"|")
                    tthen = dla.getNodeValue(field,"Then")
                    eelse = dla.getNodeValue(field,"Else")
                    for name in names:
                        if name in eelse:
                            eelse = eelse.replace(name,"|"+name+"|")
                    expression = "|" + tthen + "| " + " if |" + sname + "| " + oper + " |" + iif + "| else " + eelse
                    val = getExpression(row,names,expression)
                elif method == "Expression":
                    expression = dla.getNodeValue(field,method)
                    for name in names:
                        expression = expression.replace(name,"|" + name + "|")
                    val = getExpression(row,names,expression)
                # set field value
                if method != "None" and val != None:
                    newVal = getValue(names,ftypes,lengths,targetName,targetValue,val)
                    row[fnum] = newVal
                else:
                    row[fnum] = val
            try:
                updateCursor.updateRow(row)
            except:
                dla._errCount += 1
                success = False
                err = "Exception caught: unable to update row"
                printRow(row,names)
                dla.showTraceback()
                dla.addError(err)
    except:
        dla._errCount += 1
        success = False
        err = "Exception caught: unable to update dataset"
        if row != None:
            printRow(row,names)
        dla.showTraceback()
        dla.addError(err)

    finally:
        del updateCursor
        dla.cleanupGarbage()
        arcpy.ResetProgressor()

    return success
예제 #5
0
def calculate(xmlFileName, workspace, name, ignore):

    dla.workspace = workspace
    success = True
    arcpy.ClearWorkspaceCache_management(dla.workspace)
    xmlDoc = dla.getXmlDoc(xmlFileName)
    dla.addMessage("Field Calculator: " + xmlFileName)
    arcpy.env.Workspace = dla.workspace
    table = dla.getTempTable(name)

    if not arcpy.Exists(table):
        dla.addError("Feature Class " + table + " does not exist, exiting")
        arcpy.SetParameter(SUCCESS, False)
        return
    if not arcpy.TestSchemaLock(table):
        dla.addError("Unable to obtain a schema lock for " + table +
                     ", exiting")
        arcpy.SetParameter(SUCCESS, False)
        return -1

    desc = arcpy.Describe(table)
    fields = dla.getXmlElements(xmlFileName, "Field")
    sourceFields = dla.getXmlElements(xmlFileName, "SourceField")
    targetFields = dla.getXmlElements(xmlFileName, "TargetField")
    attrs = [f.name for f in arcpy.ListFields(table)]
    target_values = CaseInsensitiveDict()

    #Fix read into dict, using NM as key
    # at this point just getting the list of all target field names/types/lengths
    for target in targetFields:
        nm = target.getAttributeNode("Name").nodeValue
        target_values[nm] = dict(
            ftype=target.getAttributeNode("Type").nodeValue,
            flength=target.getAttributeNode("Length").nodeValue)

    for field in fields:
        arcpy.env.Workspace = dla.workspace
        targetName = dla.getNodeValue(field, "TargetName")
        sourceName = dla.getNodeValue(field, "SourceName")

        ftype = "String"
        flength = "50"
        if targetName in target_values:
            ftype = target_values[targetName]['ftype']
            flength = target_values[targetName]['flength']

        # make sure the field exists in the field calculator dataset, this will include all source and target fields.
        retcode = dla.addDlaField(table, targetName, field, attrs, ftype,
                                  flength)
        if retcode == False:
            addError("Unable to add field " + targetName +
                     " to database to calculate values, exiting")

    allFields = sourceFields + targetFields  # this should be the same as the dataset fields at this point
    desc = arcpy.Describe(table)
    layerNames = []
    names = []
    ftypes = []
    lengths = []
    ignore = dla.getIgnoreFieldNames(
        desc
    )  # gdb system fields that will be handled automatically and cannot be calculated
    ignore = [nm.upper() for nm in ignore]

    for field in desc.fields:  # get the uppercase names for everything that exists in the dataset
        if field.name.upper() not in ignore:
            layerNames.append(field.name.upper())

    for field in allFields:  # loop through everything that might exist
        nm = field.getAttributeNode("Name").nodeValue.replace(
            '.', '_')  #  handle joins and remaining . in field names
        if nm != dla._noneFieldName and nm.upper() not in ignore and nm.upper(
        ) in layerNames:  # ignore the None and ignore fields and names not in the dataset
            idx = dla.getFieldIndexList(names, nm)
            if idx is None:  # if the name is not already in the list
                names.append(nm)
                typ = field.getAttributeNode("Type").nodeValue
                leng = field.getAttributeNode("Length").nodeValue
                ftypes.append(typ)
                lengths.append(leng)

            #FIXME : Steve, was not sure why you were capturing an error here, and then doing something # from Steve - was looking for names that actually exist in the dataset and are not gdb system fields. No guarantee Xml matches dataset
            #try:
            #names.index(nm)
            #except:
            #names.append(nm)
            #typ = field.getAttributeNode("Type").nodeValue
            #leng = field.getAttributeNode("Length").nodeValue
            #ftypes.append(typ)
            #lengths.append(leng)
    retVal = setFieldValues(table, fields, names, ftypes, lengths)
    if retVal == False:
        success = False
    arcpy.ClearWorkspaceCache_management(dla.workspace)
    dla.cleanupGarbage()

    arcpy.ResetProgressor()
    if ignore == True:
        success = True
    return success
예제 #6
0
def setFieldValues(table, fields, names, ftypes, lengths):
    # from source xml file match old values to new values to prepare for append to target geodatabase
    success = False
    row = None
    try:
        updateCursor = arcpy.da.UpdateCursor(table, names)

        result = arcpy.GetCount_management(table)
        numFeat = int(result.getOutput(0))
        dla.addMessage(table + ", " + str(numFeat) + " features")
        i = 0
        arcpy.SetProgressor("Step", "Calculating " + table + "...", 0, numFeat,
                            getProgressUpdate(numFeat))

        for row in updateCursor:
            success = True
            if dla._errCount > dla.maxErrorCount:
                dla.addError(
                    "Exceeded max number of errors in dla.maxErrorCount: " +
                    str(dla.maxErrorCount))
                return False
            if i > dla.maxrows:
                dla.addError(
                    "Exceeded max number of rows supported in dla.maxrows: " +
                    str(dla.maxrows))
                return True
            i = i + 1
            setProgressor(i, numFeat)

            for field in fields:
                method = "None"
                sourceName = dla.getNodeValue(field,
                                              "SourceName").replace('.', '_')
                targetName = dla.getNodeValue(field,
                                              "TargetName").replace('.', '_')

                targetValue = getTargetValue(row, field, names, sourceName,
                                             targetName)
                sourceValue = getSourceValue(row, names, sourceName,
                                             targetName)
                method = dla.getNodeValue(field, "Method").replace(" ", "")
                try:
                    fnum = dla.getFieldIndexList(names, targetName)
                except:
                    fnum = None  # defensive check to skip fields that do not exist even though they are listed in Xml

                if fnum != None:
                    if method == "None" or (method == "Copy"
                                            and sourceName == '(None)'):
                        method = "None"
                        val = None
                    elif method == "Copy":
                        val = sourceValue
                    elif method == "DefaultValue":
                        val = dla.getNodeValue(field, "DefaultValue")
                    elif method == "SetValue":
                        val = dla.getNodeValue(field, "SetValue")
                    elif method == "ValueMap":
                        val = getValueMap(targetName, sourceValue, field)
                    elif method == "DomainMap":
                        val = getDomainMap(row, sourceValue, field)
                    elif method == "ChangeCase":
                        case = dla.getNodeValue(field, method)
                        expression = getChangeCase(sourceValue, case)
                        val = getExpression(row, names, expression)
                    elif method == "Concatenate":
                        val = getConcatenate(row, names, field)
                    elif method == "Left":
                        chars = dla.getNodeValue(field, "Left")
                        val = getSubstring(sourceValue, "0", chars)
                    elif method == "Right":
                        chars = dla.getNodeValue(field, "Right")
                        val = getSubstring(sourceValue,
                                           len(str(sourceValue)) - int(chars),
                                           len(str(sourceValue)))
                    elif method == "Substring":
                        start = dla.getNodeValue(field, "Start")
                        length = dla.getNodeValue(field, "Length")
                        val = getSubstring(sourceValue, start, length)
                    elif method == "Split":
                        splitter = dla.getNodeValue(field, "SplitAt")
                        splitter = splitter.replace("(space)", " ")
                        part = dla.getNodeValue(field, "Part")
                        val = getSplit(sourceValue, splitter, part)
                    elif method == "ConditionalValue":
                        sname = dla.getNodeValue(field, "SourceName")
                        oper = dla.getNodeValue(field, "Oper")
                        iif = dla.getNodeValue(field, "If")
                        if iif != " " and type(iif) == 'str':
                            for name in names:
                                if name in iif:
                                    iif = iif.replace(name, "|" + name + "|")
                        tthen = dla.getNodeValue(field, "Then")
                        eelse = dla.getNodeValue(field, "Else")
                        for name in names:
                            if name in eelse:
                                eelse = eelse.replace(name, "|" + name + "|")
                        expression = "|" + tthen + "| " + " if |" + sname + "| " + oper + " |" + iif + "| else " + eelse
                        val = getExpression(row, names, expression)
                    elif method == "Expression":
                        expression = dla.getNodeValue(field, method)
                        for name in names:
                            expression = expression.replace(
                                name, "|" + name + "|")
                        val = getExpression(row, names, expression)
                    # set field value
                    newVal = getValue(ftypes[fnum], lengths[fnum], targetName,
                                      targetValue, val)
                    row[fnum] = newVal
                    if dla.debug == True:
                        dla.addMessage(targetName + ':' + str(newVal) + ':' +
                                       str(targetValue))
            try:
                updateCursor.updateRow(row)
                #printRow(row,names)
            except:
                dla._errCount += 1
                success = False
                err = "Exception caught: unable to update row"
                if dla._errCount < 200:
                    printRow(row, names)
                    dla.showTraceback()
                else:
                    if dla._errCount < 2000:
                        dla.addMessage(
                            'More than 200 errors encountered... debug output suppressed'
                        )
                dla.addError(err)
    except:
        dla._errCount += 1
        success = False
        err = "Exception caught: unable to update dataset"
        if row != None:
            printRow(row, names)
        dla.showTraceback()
        dla.addError(err)

    finally:
        del updateCursor
        dla.cleanupGarbage()
        arcpy.ResetProgressor()

    return success
def calculate(xmlFileName,workspace,name,ignore):

    dla.workspace = workspace    
    success = True
    arcpy.ClearWorkspaceCache_management(dla.workspace)
    xmlDoc = dla.getXmlDoc(xmlFileName)
    
    arcpy.env.Workspace = dla.workspace
    table = dla.getTempTable(name)

    if not arcpy.Exists(table):
        dla.addError("Feature Class " + table + " does not exist, exiting")
        arcpy.SetParameter(SUCCESS, False)
        return
    if not arcpy.TestSchemaLock(table):
        dla.addError("Unable to obtain a schema lock for " + table + ", exiting")
        arcpy.SetParameter(SUCCESS, False)
        return -1
    
    desc = arcpy.Describe(table)
    fields = dla.getXmlElements(xmlFileName,"Field")
    sourceFields = dla.getXmlElements(xmlFileName,"SourceField")
    targetFields = dla.getXmlElements(xmlFileName,"TargetField")
    attrs = [f.name for f in arcpy.ListFields(table)]

    for field in fields:
        arcpy.env.Workspace = dla.workspace
        targetName = dla.getNodeValue(field,"TargetName")
        sourceName = dla.getNodeValue(field,"SourceName")
            
        type = "String"
        length = "50"
        for target in targetFields:
            nm = target.getAttributeNode("Name").nodeValue
            if  nm == targetName:
                type = target.getAttributeNode("Type").nodeValue
                length = target.getAttributeNode("Length").nodeValue
        # uppercase compare, later need to check for orig/upper name for calc
        #ups = [nm.upper() for nm in attrs]
        dla.addDlaField(table,targetName,field,attrs,type,length)

    allFields = sourceFields + targetFields
    names = []
    types = []
    lengths = []
    for field in allFields:
        nm = field.getAttributeNode("Name").nodeValue
        if nm != dla.noneName:
            names.append(nm)
            typ = field.getAttributeNode("Type").nodeValue
            leng = field.getAttributeNode("Length").nodeValue      
            types.append(typ)
            lengths.append(leng)

    retVal = setFieldValues(table,fields,names,types,lengths)
    if retVal == False:
        success = False
    arcpy.ClearWorkspaceCache_management(dla.workspace)
    dla.cleanupGarbage()

    arcpy.ResetProgressor()
    if ignore == True:
        success = True
    return success