コード例 #1
0
    def createOutput(self, outputFC):
        """Creates an Output Feature Class with the Directional Mean
        Results.

        INPUTS:
        outputFC (str): path to the output feature class
        """

        #### Validate Output Workspace ####
        ERROR.checkOutputPath(outputFC)

        #### Shorthand Attributes ####
        ssdo = self.ssdo
        caseField = self.caseField

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)

        try:
            DM.CreateFeatureclass(outPath, outName, "POLYLINE", "", ssdo.mFlag,
                                  ssdo.zFlag, ssdo.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Fields to Output FC ####
        dataFieldNames = UTILS.getFieldNames(lmFieldNames, outPath)
        shapeFieldNames = ["SHAPE@"]
        for fieldName in dataFieldNames:
            UTILS.addEmptyField(outputFC, fieldName, "DOUBLE")

        caseIsDate = False
        if caseField:
            fcCaseField = ssdo.allFields[caseField]
            validCaseName = UTILS.validQFieldName(fcCaseField, outPath)
            caseType = UTILS.convertType[fcCaseField.type]
            UTILS.addEmptyField(outputFC, validCaseName, caseType)
            dataFieldNames.append(validCaseName)
            if caseType.upper() == "DATE":
                caseIsDate = True

        #### Populate Output Feature Class ####
        allFieldNames = shapeFieldNames + dataFieldNames
        rows = DA.InsertCursor(outputFC, allFieldNames)
        for case in self.caseKeys:
            #### Get Results ####
            start, end, length, rAngle, dAngle, circVar = self.dm[case]
            meanX, meanY = self.meanCenter[case]
            dirMean = 360. - dAngle + 90.
            if not dirMean < 360:
                dirMean = dirMean - 360.

            #### Create Start and End Points ####
            x0, y0 = start
            startPoint = ARCPY.Point(x0, y0, ssdo.defaultZ)
            x1, y1 = end
            endPoint = ARCPY.Point(x1, y1, ssdo.defaultZ)

            #### Create And Populate Line Array ####
            line = ARCPY.Array()
            line.add(startPoint)
            line.add(endPoint)
            line = ARCPY.Polyline(line, None, True)

            #### Create and Populate New Line Feature ####
            rowResult = [line, dAngle, dirMean, circVar, meanX, meanY, length]

            if caseField:
                caseValue = case
                if caseIsDate:
                    caseValue = TUTILS.iso2DateTime(caseValue)
                rowResult.append(caseValue)
            rows.insertRow(rowResult)

        #### Clean Up ####
        del rows

        #### Set Attribute ####
        self.outputFC = outputFC

        #### Set the Default Symbology ####
        params = ARCPY.gp.GetParameterInfo()
        if self.orientationOnly:
            renderLayerFile = "LinearMeanTwoWay.lyr"
        else:
            renderLayerFile = "LinearMeanOneWay.lyr"
        templateDir = OS.path.dirname(OS.path.dirname(SYS.argv[0]))
        fullRLF = OS.path.join(templateDir, "Templates", "Layers",
                               renderLayerFile)
        params[1].Symbology = fullRLF
コード例 #2
0
    def createOutput(self, outputFC):
        """Creates an Output Feature Class with the Standard Distances.

        INPUTS:
        outputFC (str): path to the output feature class
        """

        #### Validate Output Workspace ####
        ERROR.checkOutputPath(outputFC)

        #### Shorthand Attributes ####
        ssdo = self.ssdo
        caseField = self.caseField

        #### Increase Extent if not Projected ####
        if ssdo.spatialRefType != "Projected":
            sdValues = self.sd.values()
            if len(sdValues):
                maxRadius = max(sdValues)
                largerExtent = UTILS.increaseExtentByConstant(
                    ssdo.extent, constant=maxRadius)
                largerExtent = [LOCALE.str(i) for i in largerExtent]
                ARCPY.env.XYDomain = " ".join(largerExtent)

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)

        try:
            DM.CreateFeatureclass(outPath, outName, "POLYGON", "", ssdo.mFlag,
                                  ssdo.zFlag, ssdo.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Fields to Output FC ####
        dataFieldNames = UTILS.getFieldNames(sdFieldNames, outPath)
        shapeFieldNames = ["SHAPE@"]
        for fieldName in dataFieldNames:
            UTILS.addEmptyField(outputFC, fieldName, "DOUBLE")

        caseIsDate = False
        if caseField:
            fcCaseField = ssdo.allFields[caseField]
            validCaseName = UTILS.validQFieldName(fcCaseField, outPath)
            caseType = UTILS.convertType[fcCaseField.type]
            UTILS.addEmptyField(outputFC, validCaseName, caseType)
            dataFieldNames.append(validCaseName)
            if caseType.upper() == "DATE":
                caseIsDate = True

        #### Write Output ####
        badCaseRadians = []
        allFieldNames = shapeFieldNames + dataFieldNames
        rows = DA.InsertCursor(outputFC, allFieldNames)
        for case in self.caseKeys:

            #### Get Results ####
            xVal, yVal = self.meanCenter[case]
            radius = self.sd[case]

            #### Create Empty Polygon Geomretry ####
            poly = ARCPY.Array()

            #### Check for Valid Radius ####
            radiusZero = UTILS.compareFloat(0.0, radius, rTol=.0000001)
            radiusNan = NUM.isnan(radius)
            radiusBool = radiusZero + radiusNan
            if radiusBool:
                badRadian = 6
                badCase = UTILS.caseValue2Print(case, self.caseIsString)
                badCaseRadians.append(badCase)
            else:
                badRadian = 0

                #### Calculate a Point For Each ####
                #### Degree in Circle Polygon ####
                for degree in NUM.arange(0, 360):
                    try:
                        radians = NUM.pi / 180.0 * degree
                        pntX = xVal + (radius * NUM.cos(radians))
                        pntY = yVal + (radius * NUM.sin(radians))
                        pnt = ARCPY.Point(pntX, pntY, ssdo.defaultZ)
                        poly.add(pnt)
                    except:
                        badRadian += 1
                        if badRadian == 6:
                            badCase = UTILS.caseValue2Print(
                                case, self.caseIsString)
                            badCaseRadians.append(badCase)
                            break

            if badRadian < 6:
                #### Create and Populate New Feature ####
                poly = ARCPY.Polygon(poly, None, True)
                rowResult = [poly, xVal, yVal, radius]

                if caseField:
                    caseValue = case.item()
                    if caseIsDate:
                        caseValue = TUTILS.iso2DateTime(caseValue)
                    rowResult.append(caseValue)
                rows.insertRow(rowResult)

        #### Report Bad Cases Due to Geometry (coincident pts) ####
        nBadRadians = len(badCaseRadians)
        if nBadRadians:
            if caseField:
                badCaseRadians = " ".join(badCaseRadians)
                ARCPY.AddIDMessage("WARNING", 1011, caseField, badCaseRadians)
            else:
                ARCPY.AddIDMessage("ERROR", 978)
                raise SystemExit()

        #### Return Extent to Normal if not Projected ####
        if ssdo.spatialRefType != "Projected":
            ARCPY.env.XYDomain = None

        #### Clean Up ####
        del rows

        #### Set Attribute ####
        self.outputFC = outputFC
コード例 #3
0
    def createOutput(self, outputFC):
        """Creates an Output Feature Class with the Standard Distances.

        INPUTS:
        outputFC (str): path to the output feature class
        """

        #### Validate Output Workspace ####
        ERROR.checkOutputPath(outputFC)

        #### Shorthand Attributes ####
        ssdo = self.ssdo
        caseField = self.caseField

        #### Increase Extent if not Projected ####
        if ssdo.spatialRefType != "Projected":
            sdValues = self.sd.values()
            if len(sdValues):
                maxRadius = max(sdValues)
                largerExtent = UTILS.increaseExtentByConstant(ssdo.extent, 
                                                    constant = maxRadius)
                largerExtent = [ LOCALE.str(i) for i in largerExtent ]
                ARCPY.env.XYDomain = " ".join(largerExtent)

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)

        try:
            DM.CreateFeatureclass(outPath, outName, "POLYGON", 
                                  "", ssdo.mFlag, ssdo.zFlag, 
                                  ssdo.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Fields to Output FC ####
        dataFieldNames = UTILS.getFieldNames(sdFieldNames, outPath)
        shapeFieldNames = ["SHAPE@"]
        for fieldName in dataFieldNames:
            UTILS.addEmptyField(outputFC, fieldName, "DOUBLE")

        caseIsDate = False
        if caseField:
            fcCaseField = ssdo.allFields[caseField]
            validCaseName = UTILS.validQFieldName(fcCaseField, outPath)
            caseType = UTILS.convertType[fcCaseField.type]
            UTILS.addEmptyField(outputFC, validCaseName, caseType)
            dataFieldNames.append(validCaseName)
            if caseType.upper() == "DATE":
                caseIsDate = True

        #### Write Output ####
        badCaseRadians = []
        allFieldNames = shapeFieldNames + dataFieldNames
        rows = DA.InsertCursor(outputFC, allFieldNames)
        for case in self.caseKeys:

            #### Get Results ####
            xVal, yVal = self.meanCenter[case]
            radius = self.sd[case]

            #### Create Empty Polygon Geomretry ####
            poly = ARCPY.Array()

            #### Check for Valid Radius ####
            radiusZero = UTILS.compareFloat(0.0, radius, rTol = .0000001)
            radiusNan = NUM.isnan(radius)
            radiusBool = radiusZero + radiusNan
            if radiusBool:
                badRadian = 6
                badCase = UTILS.caseValue2Print(case, self.caseIsString)
                badCaseRadians.append(badCase)
            else:
                badRadian = 0

                #### Calculate a Point For Each ####
                #### Degree in Circle Polygon ####
                for degree in NUM.arange(0, 360):  
                    try:
                        radians = NUM.pi / 180.0 * degree
                        pntX = xVal + (radius * NUM.cos(radians))
                        pntY = yVal + (radius * NUM.sin(radians))
                        pnt = ARCPY.Point(pntX, pntY, ssdo.defaultZ)
                        poly.add(pnt)
                    except:
                        badRadian += 1
                        if badRadian == 6:
                            badCase = UTILS.caseValue2Print(case, 
                                               self.caseIsString)
                            badCaseRadians.append(badCase)
                            break

            if badRadian < 6:
                #### Create and Populate New Feature ####
                poly = ARCPY.Polygon(poly, None, True)
                rowResult = [poly, xVal, yVal, radius]

                if caseField:
                    caseValue = case.item()
                    if caseIsDate:
                        caseValue = TUTILS.iso2DateTime(caseValue)
                    rowResult.append(caseValue)
                rows.insertRow(rowResult)

        #### Report Bad Cases Due to Geometry (coincident pts) ####
        nBadRadians = len(badCaseRadians)
        if nBadRadians:
            if caseField:
                badCaseRadians = " ".join(badCaseRadians)
                ARCPY.AddIDMessage("WARNING", 1011, caseField,
                                badCaseRadians)
            else:
                ARCPY.AddIDMessage("ERROR", 978)
                raise SystemExit()

        #### Return Extent to Normal if not Projected ####
        if ssdo.spatialRefType != "Projected":
            ARCPY.env.XYDomain = None

        #### Clean Up ####
        del rows

        #### Set Attribute ####
        self.outputFC = outputFC
コード例 #4
0
    def createOutput(self, outputFC):
        """Creates an Output Feature Class with the Median Centers.

        INPUTS:
        outputFC (str): path to the output feature class
        """

        #### Validate Output Workspace ####
        ERROR.checkOutputPath(outputFC)

        #### Shorthand Attributes ####
        ssdo = self.ssdo
        caseField = self.caseField
        attFields = self.attFields

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)

        try:
            DM.CreateFeatureclass(outPath, outName, "POINT", "", ssdo.mFlag, 
                                  ssdo.zFlag, ssdo.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Field Names ####
        dataFieldNames = UTILS.getFieldNames(mdcFieldNames, outPath)
        shapeFieldNames = ["SHAPE@"]
        for fieldName in dataFieldNames:
            UTILS.addEmptyField(outputFC, fieldName, "DOUBLE")

        caseIsDate = False
        if caseField:
            fcCaseField = ssdo.allFields[caseField]
            validCaseName = UTILS.validQFieldName(fcCaseField, outPath)
            caseType = UTILS.convertType[fcCaseField.type]
            UTILS.addEmptyField(outputFC, validCaseName, caseType)
            dataFieldNames.append(validCaseName)
            if caseType.upper() == "DATE":
                caseIsDate = True

        if attFields:
            for attField in attFields:
                fcAttField = ssdo.allFields[attField]
                validAttName = UTILS.validQFieldName(fcAttField, outPath)
                if caseField:
                    if validCaseName == validAttName:
                        validAttName = ARCPY.GetIDMessage(84195)
                UTILS.addEmptyField(outputFC, validAttName, "DOUBLE") 
                dataFieldNames.append(validAttName)

        outShapeFileBool = UTILS.isShapeFile(outputFC)
            
        #### Add Median X, Y, Dim ####
        allFieldNames = shapeFieldNames + dataFieldNames
        rows = DA.InsertCursor(outputFC, allFieldNames)
        for case in self.caseKeys:

            #### Median Centers ####
            medX, medY = self.medianCenter[case]
            pnt = (medX, medY, ssdo.defaultZ)
            rowResult = [pnt, medX, medY]

            #### Set Attribute Fields ####
            if caseField:
                caseValue = case.item()
                if caseIsDate:
                    caseValue = TUTILS.iso2DateTime(caseValue)
                rowResult.append(caseValue)

            #### Set Attribute Fields ####
            if attFields:
                for attInd, attField in enumerate(self.attFields):
                    medAtt = self.attCenter[case][attInd]
                    rowResult.append(medAtt)

            rows.insertRow(rowResult)
        
        #### Clean Up ####
        del rows

        #### Set Attribute ####
        self.outputFC = outputFC
コード例 #5
0
def daysInMonth(month, year):
    return TUTIL.monthConvert(month, year)
コード例 #6
0
ファイル: Weights.py プロジェクト: leochin/GSWMtest
def spaceTime2SWM(inputFC, swmFile, masterField, concept = "EUCLIDEAN",
                  threshold = None, rowStandard = True,
                  timeField = None, timeType = None,
                  timeValue = None):
    """
    inputFC (str): path to the input feature class
    swmFile (str): path to the SWM file.
    masterField (str): field in table that serves as the mapping.
    concept: {str, EUCLIDEAN}: EUCLIDEAN or MANHATTAN 
    threshold {float, None}: distance threshold
    rowStandard {bool, True}: row standardize weights?
    timeField {str, None}: name of the date-time field
    timeType {str, None}: ESRI enumeration of date-time intervals
    timeValue {float, None}: value forward and backward in time
    """

    #### Assure Temporal Parameters are Set ####
    if not timeField:
        ARCPY.AddIDMessage("ERROR", 1320)
        raise SystemExit()
    if not timeType:
        ARCPY.AddIDMessage("ERROR", 1321)
        raise SystemExit()
    if not timeValue or timeValue <= 0:
        ARCPY.AddIDMessage("ERROR", 1322)
        raise SystemExit()

    #### Create SSDataObject ####
    ssdo = SSDO.SSDataObject(inputFC, templateFC = inputFC,
                             useChordal = True)
    cnt = UTILS.getCount(inputFC)
    ERROR.errorNumberOfObs(cnt, minNumObs = 2)
    ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84001), 0, cnt, 1)

    #### Validation of Master Field ####
    verifyMaster = ERROR.checkField(ssdo.allFields, masterField, types = [0,1])
    badIDs = []

    #### Create Temporal Hash ####
    timeInfo = {}
    xyCoords = NUM.empty((cnt, 2), float)

    #### Process Field Values ####
    fieldList = [masterField, "SHAPE@XY", timeField]
    try:
        rows = DA.SearchCursor(ssdo.catPath, fieldList, "", 
                               ssdo.spatialRefString)
    except:
        ARCPY.AddIDMessage("ERROR", 204)
        raise SystemExit()

    #### Add Data to GATable and Time Dictionary ####
    c = 0
    for row in rows:
        badRow = False

        #### Assure Masterfield is Valid ####
        masterID = row[0]
        if masterID == None or masterID == "":
            badRow = True

        #### Assure Date/Time is Valid ####
        timeStamp = row[-1]
        if timeStamp == None or timeStamp == "":
            badRow = True

        #### Assure Centroid is Valid ####
        badXY = row[1].count(None)
        if not badXY:
            x,y = row[1]
            xyCoords[c] = (x,y)
        else:
            badRow = True

        #### Process Data ####
        if not badRow:
            if timeInfo.has_key(masterID):
                #### Assure Uniqueness ####
                ARCPY.AddIDMessage("Error", 644, masterField)
                ARCPY.AddIDMessage("Error", 643)
                raise SystemExit()
            else:
                #### Fill Date/Time Dict ####
                startDT, endDT = TUTILS.calculateTimeWindow(timeStamp, 
                                                            timeValue, 
                                                            timeType)
                timeInfo[masterID] = (timeStamp, startDT, endDT)

        else:
            badIDs.append(masterID)

        #### Set Progress ####
        c += 1
        ARCPY.SetProgressorPosition()

    #### Clean Up ####
    del rows

    #### Get Set of Bad IDs ####
    numBadObs = len(badIDs)
    badIDs = list(set(badIDs))
    badIDs.sort()
    badIDs = [ str(i) for i in badIDs ]
    
    #### Process any bad records encountered ####
    if numBadObs:
        ERROR.reportBadRecords(cnt, numBadObs, badIDs, label = masterField)

    #### Load Neighbor Table ####
    gaTable, gaInfo = WU.gaTable(ssdo.inputFC, 
                                 fieldNames = [masterField, timeField],
                                 spatRef = ssdo.spatialRefString)
    numObs = len(gaTable)
    xyCoords = xyCoords[0:numObs]

    #### Set the Distance Threshold ####
    concept, gaConcept = WU.validateDistanceMethod(concept, ssdo.spatialRef)
    if threshold == None:
        #### Set Progressor for Search ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84144))

        #### Create k-Nearest Neighbor Search Type ####
        gaSearch = GAPY.ga_nsearch(gaTable)
        gaSearch.init_nearest(0.0, 1, gaConcept)
        neighDist = ARC._ss.NeighborDistances(gaTable, gaSearch)
        N = len(neighDist)
        threshold = 0.0
        sumDist = 0.0 

        #### Find Maximum Nearest Neighbor Distance ####
        for row in xrange(N):
            dij = neighDist[row][-1][0]
            if dij > threshold:
                threshold = dij
            sumDist += dij

            ARCPY.SetProgressorPosition()

        #### Increase For Rounding Error ####
        threshold = threshold * 1.0001
        avgDist = sumDist / (N * 1.0)

        #### Add Linear/Angular Units ####
        thresholdStr = ssdo.distanceInfo.printDistance(threshold)
        ARCPY.AddIDMessage("Warning", 853, thresholdStr)

        #### Chordal Default Check ####
        if ssdo.useChordal:
            hardMaxExtent = ARC._ss.get_max_gcs_distance(ssdo.spatialRef)
            if threshold > hardMaxExtent:
                ARCPY.AddIDMessage("ERROR", 1609)
                raise SystemExit()

        #### Clean Up ####
        del gaSearch

    #### Create Missing SSDO Info ####
    extent = UTILS.resetExtent(xyCoords)

    #### Reset Coordinates for Chordal ####
    if ssdo.useChordal:
        sliceInfo = UTILS.SpheroidSlice(extent, ssdo.spatialRef)
        maxExtent = sliceInfo.maxExtent
    else:
        env = UTILS.Envelope(extent)
        maxExtent = env.maxExtent

    threshold = checkDistanceThresholdSWM(ssdo, threshold, maxExtent)
    
    #### Set Default Progressor for Neigborhood Structure ####
    ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84143))

    #### Create Distance Neighbor Search Type ####
    gaSearch = GAPY.ga_nsearch(gaTable)
    gaSearch.init_nearest(threshold, 0, gaConcept)
    neighSearch = ARC._ss.NeighborSearch(gaTable, gaSearch)

    #### Set Progressor for Weights Writing ####
    ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84127), 0, numObs, 1)

    #### Initialize Spatial Weights Matrix File ####
    swmWriter = WU.SWMWriter(swmFile, masterField, ssdo.spatialRefName, 
                             numObs, rowStandard, inputFC = inputFC,
                             wType = 9, distanceMethod = concept,
                             threshold = threshold, timeField = timeField,
                             timeType = timeType, timeValue = timeValue)

    for row in xrange(numObs):
        masterID = gaTable[row][2]

        #### Get Date/Time Info ####
        dt0, startDT0, endDT0 = timeInfo[masterID]

        nhs = neighSearch[row]
        neighs = []
        weights = []
        for nh in nhs:
            #### Search Through Spatial Neighbors ####
            neighID = gaTable[nh][2]

            #### Get Date/Time Info ####
            dt1, startDT1, endDT1 = timeInfo[neighID]

            #### Filter Based on Date/Time ####
            insideTimeWindow = TUTILS.isTimeNeighbor(startDT0, endDT0, dt1)
            if insideTimeWindow:
                neighs.append(neighID)
                weights.append(1.0)

        #### Add Spatial Weights Matrix Entry ####
        swmWriter.swm.writeEntry(masterID, neighs, weights) 

        #### Set Progress ####
        ARCPY.SetProgressorPosition()

    swmWriter.close()
    del gaTable

    #### Report Warning/Max Neighbors ####
    swmWriter.reportNeighInfo()

    #### Report Spatial Weights Summary ####
    swmWriter.report()

    #### Report SWM File is Large ####
    swmWriter.reportLargeSWM()
コード例 #7
0
def daysInMonth(month, year):
    return TUTIL.monthConvert(month, year)
コード例 #8
0
if __name__ == '__main__':
    ARCPY.env.overwriteOutput = True
    inputFC = r"C:\Data\time\starbucks.shp"
    timeField = "DATE"
    #### Create SSDataObject ####
    ssdo = SSDO.SSDataObject(inputFC)
    #### Retrive time data from ssdo ####
    ssdo.obtainData(ssdo.oidName, [timeField], dateStr = True)
    timeData = ssdo.fields[timeField].data
    ## print timeData
    #### Convert string to datetime64 object ####
    # method A
    dt = NUM.array([DT.datetime.strptime(dtString, "%Y-%m-%d %H:%M:%S") for dtString in timeData])

    # method B
    dt = NUM.array([TUTIL.iso2DateTime(dtString) for dtString in timeData])
    ## print dt
    '''
    After converted to datetime64 object, you can have property as second, minute, hour...
    For example:
        print dt[0].year
        print dt[0].second
    '''

    #### Find how many days in the month ####
    days1 = daysInMonth(dt[0].month, dt[0].year)
    print "There are {0} days in this {1}-{2}".format(days1, dt[0].year, dt[0].month)

    #### Find how many days in the year ####
    days2 = daysInYear(dt[0].year)
    print "There are {0} days in {1}".format(days2, dt[0].year)
コード例 #9
0
    def createOutput(self, outputFC):
        """Creates an Output Feature Class with the Mean Centers.

        INPUTS:
        outputFC (str): path to the output feature class
        """

        #### Validate Output Workspace ####
        ERROR.checkOutputPath(outputFC)

        #### Shorthand Attributes ####
        ssdo = self.ssdo
        caseField = self.caseField
        dimField = self.dimField

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)

        try:
            DM.CreateFeatureclass(outPath, outName, "POINT", "", ssdo.mFlag,
                                  ssdo.zFlag, ssdo.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Field Names ####
        fn = UTILS.getFieldNames(mcFieldNames, outPath)
        xFieldName, yFieldName, zFieldName = fn
        shapeFieldNames = ["SHAPE@"]
        dataFieldNames = [xFieldName, yFieldName]
        if ssdo.zBool:
            dataFieldNames.append(zFieldName)

        for fieldName in dataFieldNames:
            UTILS.addEmptyField(outputFC, fieldName, "DOUBLE")

        caseIsDate = False
        if caseField:
            fcCaseField = ssdo.allFields[caseField]
            validCaseName = UTILS.validQFieldName(fcCaseField, outPath)
            caseType = UTILS.convertType[fcCaseField.type]
            UTILS.addEmptyField(outputFC, validCaseName, caseType)
            dataFieldNames.append(validCaseName)
            if caseType.upper() == "DATE":
                caseIsDate = True

        if dimField:
            fcDimField = ssdo.allFields[dimField]
            validDimName = UTILS.validQFieldName(fcDimField, outPath)
            if caseField:
                if validCaseName == validDimName:
                    validDimName = ARCPY.GetIDMessage(84199)
            UTILS.addEmptyField(outputFC, validDimName, "DOUBLE")
            dataFieldNames.append(validDimName)

        #### Write Output ####
        allFieldNames = shapeFieldNames + dataFieldNames
        rows = DA.InsertCursor(outputFC, allFieldNames)
        for case in self.caseKeys:

            #### Mean Centers ####
            meanX, meanY, meanZ = self.meanCenter[case]
            pnt = (meanX, meanY, meanZ)
            if ssdo.zBool:
                rowResult = [pnt, meanX, meanY, meanZ]
            else:
                rowResult = [pnt, meanX, meanY]

            #### Set Attribute Fields ####
            if caseField:
                caseValue = case.item()
                if caseIsDate:
                    caseValue = TUTILS.iso2DateTime(caseValue)
                rowResult.append(caseValue)

            if dimField:
                meanDim = self.dimCenter[case]
                rowResult.append(meanDim)

            rows.insertRow(rowResult)

        #### Clean Up ####
        del rows

        #### Set Attribute ####
        self.outputFC = outputFC
コード例 #10
0
    timeField = "DATE"
    #### Create SSDataObject ####
    ssdo = SSDO.SSDataObject(inputFC)
    #### Retrive time data from ssdo ####
    ssdo.obtainData(ssdo.oidName, [timeField], dateStr=True)
    timeData = ssdo.fields[timeField].data
    ## print timeData
    #### Convert string to datetime64 object ####
    # method A
    dt = NUM.array([
        DT.datetime.strptime(dtString, "%Y-%m-%d %H:%M:%S")
        for dtString in timeData
    ])

    # method B
    dt = NUM.array([TUTIL.iso2DateTime(dtString) for dtString in timeData])
    ## print dt
    '''
    After converted to datetime64 object, you can have property as second, minute, hour...
    For example:
        print dt[0].year
        print dt[0].second
    '''

    #### Find how many days in the month ####
    days1 = daysInMonth(dt[0].month, dt[0].year)
    print "There are {0} days in this {1}-{2}".format(days1, dt[0].year,
                                                      dt[0].month)

    #### Find how many days in the year ####
    days2 = daysInYear(dt[0].year)
コード例 #11
0
def spaceTime2SWM(inputFC, swmFile, masterField, concept = "EUCLIDEAN",
                  threshold = None, rowStandard = True,
                  timeField = None, timeType = None,
                  timeValue = None):
    """
    inputFC (str): path to the input feature class
    swmFile (str): path to the SWM file.
    masterField (str): field in table that serves as the mapping.
    concept: {str, EUCLIDEAN}: EUCLIDEAN or MANHATTAN 
    threshold {float, None}: distance threshold
    rowStandard {bool, True}: row standardize weights?
    timeField {str, None}: name of the date-time field
    timeType {str, None}: ESRI enumeration of date-time intervals
    timeValue {float, None}: value forward and backward in time
    """

    #### Assure Temporal Parameters are Set ####
    if not timeField:
        ARCPY.AddIDMessage("ERROR", 1320)
        raise SystemExit()
    if not timeType:
        ARCPY.AddIDMessage("ERROR", 1321)
        raise SystemExit()
    if not timeValue or timeValue <= 0:
        ARCPY.AddIDMessage("ERROR", 1322)
        raise SystemExit()

    #### Create SSDataObject ####
    ssdo = SSDO.SSDataObject(inputFC, templateFC = inputFC,
                             useChordal = True)
    cnt = UTILS.getCount(inputFC)
    ERROR.errorNumberOfObs(cnt, minNumObs = 2)
    ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84001), 0, cnt, 1)

    #### Validation of Master Field ####
    verifyMaster = ERROR.checkField(ssdo.allFields, masterField, types = [0,1])
    badIDs = []

    #### Create Temporal Hash ####
    timeInfo = {}
    xyCoords = NUM.empty((cnt, 2), float)

    #### Process Field Values ####
    fieldList = [masterField, "SHAPE@XY", timeField]
    try:
        rows = DA.SearchCursor(ssdo.catPath, fieldList, "", 
                               ssdo.spatialRefString)
    except:
        ARCPY.AddIDMessage("ERROR", 204)
        raise SystemExit()

    #### Add Data to GATable and Time Dictionary ####
    c = 0
    for row in rows:
        badRow = False

        #### Assure Masterfield is Valid ####
        masterID = row[0]
        if masterID == None or masterID == "":
            badRow = True

        #### Assure Date/Time is Valid ####
        timeStamp = row[-1]
        if timeStamp == None or timeStamp == "":
            badRow = True

        #### Assure Centroid is Valid ####
        badXY = row[1].count(None)
        if not badXY:
            x,y = row[1]
            xyCoords[c] = (x,y)
        else:
            badRow = True

        #### Process Data ####
        if not badRow:
            if timeInfo.has_key(masterID):
                #### Assure Uniqueness ####
                ARCPY.AddIDMessage("Error", 644, masterField)
                ARCPY.AddIDMessage("Error", 643)
                raise SystemExit()
            else:
                #### Fill Date/Time Dict ####
                startDT, endDT = TUTILS.calculateTimeWindow(timeStamp, 
                                                            timeValue, 
                                                            timeType)
                timeInfo[masterID] = (timeStamp, startDT, endDT)

        else:
            badIDs.append(masterID)

        #### Set Progress ####
        c += 1
        ARCPY.SetProgressorPosition()

    #### Clean Up ####
    del rows

    #### Get Set of Bad IDs ####
    numBadObs = len(badIDs)
    badIDs = list(set(badIDs))
    badIDs.sort()
    badIDs = [ str(i) for i in badIDs ]
    
    #### Process any bad records encountered ####
    if numBadObs:
        ERROR.reportBadRecords(cnt, numBadObs, badIDs, label = masterField)

    #### Load Neighbor Table ####
    gaTable, gaInfo = WU.gaTable(ssdo.inputFC, 
                                 fieldNames = [masterField, timeField],
                                 spatRef = ssdo.spatialRefString)
    numObs = len(gaTable)
    xyCoords = xyCoords[0:numObs]

    #### Set the Distance Threshold ####
    concept, gaConcept = WU.validateDistanceMethod(concept, ssdo.spatialRef)
    if threshold == None:
        #### Set Progressor for Search ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84144))

        #### Create k-Nearest Neighbor Search Type ####
        gaSearch = GAPY.ga_nsearch(gaTable)
        gaSearch.init_nearest(0.0, 1, gaConcept)
        neighDist = ARC._ss.NeighborDistances(gaTable, gaSearch)
        N = len(neighDist)
        threshold = 0.0
        sumDist = 0.0 

        #### Find Maximum Nearest Neighbor Distance ####
        for row in xrange(N):
            dij = neighDist[row][-1][0]
            if dij > threshold:
                threshold = dij
            sumDist += dij

            ARCPY.SetProgressorPosition()

        #### Increase For Rounding Error ####
        threshold = threshold * 1.0001
        avgDist = sumDist / (N * 1.0)

        #### Add Linear/Angular Units ####
        thresholdStr = ssdo.distanceInfo.printDistance(threshold)
        ARCPY.AddIDMessage("Warning", 853, thresholdStr)

        #### Chordal Default Check ####
        if ssdo.useChordal:
            hardMaxExtent = ARC._ss.get_max_gcs_distance(ssdo.spatialRef)
            if threshold > hardMaxExtent:
                ARCPY.AddIDMessage("ERROR", 1609)
                raise SystemExit()

        #### Clean Up ####
        del gaSearch

    #### Create Missing SSDO Info ####
    extent = UTILS.resetExtent(xyCoords)

    #### Reset Coordinates for Chordal ####
    if ssdo.useChordal:
        sliceInfo = UTILS.SpheroidSlice(extent, ssdo.spatialRef)
        maxExtent = sliceInfo.maxExtent
    else:
        env = UTILS.Envelope(extent)
        maxExtent = env.maxExtent

    threshold = checkDistanceThresholdSWM(ssdo, threshold, maxExtent)
    
    #### Set Default Progressor for Neigborhood Structure ####
    ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84143))

    #### Create Distance Neighbor Search Type ####
    gaSearch = GAPY.ga_nsearch(gaTable)
    gaSearch.init_nearest(threshold, 0, gaConcept)
    neighSearch = ARC._ss.NeighborSearch(gaTable, gaSearch)

    #### Set Progressor for Weights Writing ####
    ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84127), 0, numObs, 1)

    #### Initialize Spatial Weights Matrix File ####
    swmWriter = WU.SWMWriter(swmFile, masterField, ssdo.spatialRefName, 
                             numObs, rowStandard, inputFC = inputFC,
                             wType = 9, distanceMethod = concept,
                             threshold = threshold, timeField = timeField,
                             timeType = timeType, timeValue = timeValue)

    for row in xrange(numObs):
        masterID = gaTable[row][2]

        #### Get Date/Time Info ####
        dt0, startDT0, endDT0 = timeInfo[masterID]

        nhs = neighSearch[row]
        neighs = []
        weights = []
        for nh in nhs:
            #### Search Through Spatial Neighbors ####
            neighID = gaTable[nh][2]

            #### Get Date/Time Info ####
            dt1, startDT1, endDT1 = timeInfo[neighID]

            #### Filter Based on Date/Time ####
            insideTimeWindow = TUTILS.isTimeNeighbor(startDT0, endDT0, dt1)
            if insideTimeWindow:
                neighs.append(neighID)
                weights.append(1.0)

        #### Add Spatial Weights Matrix Entry ####
        swmWriter.swm.writeEntry(masterID, neighs, weights) 

        #### Set Progress ####
        ARCPY.SetProgressorPosition()

    swmWriter.close()
    del gaTable

    #### Report Warning/Max Neighbors ####
    swmWriter.reportNeighInfo()

    #### Report Spatial Weights Summary ####
    swmWriter.report()

    #### Report SWM File is Large ####
    swmWriter.reportLargeSWM()
コード例 #12
0
    def createOutput(self, outputFC):
        """Creates an Output Feature Class with the Standard Distances.

        INPUTS:
        outputFC (str): path to the output feature class
        """

        #### Validate Output Workspace ####
        ERROR.checkOutputPath(outputFC)

        #### Shorthand Attributes ####
        ssdo = self.ssdo
        caseField = self.caseField

        #### Increase Extent if not Projected ####
        if ssdo.spatialRefType != "Projected":
            seValues = self.se.values()
            if len(seValues):
                maxSE = NUM.array([i[0:2] for i in seValues]).max()
                largerExtent = UTILS.increaseExtentByConstant(ssdo.extent,
                                                              constant=maxSE)
                largerExtent = [LOCALE.str(i) for i in largerExtent]
                ARCPY.env.XYDomain = " ".join(largerExtent)

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)

        try:
            DM.CreateFeatureclass(outPath, outName, "POLYGON", "", ssdo.mFlag,
                                  ssdo.zFlag, ssdo.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Fields to Output FC ####
        dataFieldNames = UTILS.getFieldNames(seFieldNames, outPath)
        shapeFieldNames = ["SHAPE@"]
        for fieldName in dataFieldNames:
            UTILS.addEmptyField(outputFC, fieldName, "DOUBLE")

        caseIsDate = False
        if caseField:
            fcCaseField = ssdo.allFields[caseField]
            validCaseName = UTILS.validQFieldName(fcCaseField, outPath)
            caseType = UTILS.convertType[fcCaseField.type]
            UTILS.addEmptyField(outputFC, validCaseName, caseType)
            dataFieldNames.append(validCaseName)
            if caseType.upper() == "DATE":
                caseIsDate = True

        #### Write Output ####
        badCaseRadians = []
        allFieldNames = shapeFieldNames + dataFieldNames
        rows = DA.InsertCursor(outputFC, allFieldNames)
        for case in self.caseKeys:

            #### Get Results ####
            xVal, yVal = self.meanCenter[case]
            seX, seY, degreeRotation, radianR1, radianR2 = self.se[case]
            seX2 = seX**2.0
            seY2 = seY**2.0

            #### Create Empty Polygon Geomretry ####
            poly = ARCPY.Array()

            #### Check for Valid Radius ####
            seXZero = UTILS.compareFloat(0.0, seX, rTol=.0000001)
            seXNan = NUM.isnan(seX)
            seXBool = seXZero + seXNan
            seYZero = UTILS.compareFloat(0.0, seY, rTol=.0000001)
            seYNan = NUM.isnan(seY)
            seYBool = seYZero + seYNan
            if seXBool or seYBool:
                badRadian = 6
                badCase = UTILS.caseValue2Print(case, self.caseIsString)
                badCaseRadians.append(badCase)
            else:
                badRadian = 0
                cosRadian = NUM.cos(radianR1)
                sinRadian = NUM.sin(radianR1)

                #### Calculate a Point For Each ####
                #### Degree in Ellipse Polygon ####
                for degree in NUM.arange(0, 360):
                    try:
                        radians = UTILS.convert2Radians(degree)
                        tanVal2 = NUM.tan(radians)**2.0
                        dX = MATH.sqrt(
                            (seX2 * seY2) / (seY2 + (seX2 * tanVal2)))
                        dY = MATH.sqrt((seY2 * (seX2 - dX**2.0)) / seX2)

                        #### Adjust for Quadrant ####
                        if 90 <= degree < 180:
                            dX = -dX
                        elif 180 <= degree < 270:
                            dX = -dX
                            dY = -dY
                        elif degree >= 270:
                            dY = -dY

                        #### Rotate X and Y ####
                        dXr = dX * cosRadian - dY * sinRadian
                        dYr = dX * sinRadian + dY * cosRadian

                        #### Create Point Shifted to ####
                        #### Ellipse Centroid ####
                        pntX = dXr + xVal
                        pntY = dYr + yVal
                        pnt = ARCPY.Point(pntX, pntY, ssdo.defaultZ)
                        poly.add(pnt)
                    except:
                        badRadian += 1
                        if badRadian == 6:
                            badCase = UTILS.caseValue2Print(
                                case, self.caseIsString)
                            badCaseRadians.append(badCase)
                            break

            if badRadian < 6:
                #### Create and Populate New Feature ####
                poly = ARCPY.Polygon(poly, None, True)
                rowResult = [poly, xVal, yVal, seX, seY, radianR2]

                if caseField:
                    caseValue = case.item()
                    if caseIsDate:
                        caseValue = TUTILS.iso2DateTime(caseValue)
                    rowResult.append(caseValue)
                rows.insertRow(rowResult)

        #### Report Bad Cases Due to Geometry (coincident pts) ####
        nBadRadians = len(badCaseRadians)
        if nBadRadians:
            if caseField:
                badCaseRadians = " ".join(badCaseRadians)
                ARCPY.AddIDMessage("WARNING", 1011, caseField, badCaseRadians)
            else:
                ARCPY.AddIDMessage("ERROR", 978)
                raise SystemExit()

        #### Return Extent to Normal if not Projected ####
        if ssdo.spatialRefType != "Projected":
            ARCPY.env.XYDomain = ""

        #### Clean Up ####
        del rows

        #### Set Attribute ####
        self.outputFC = outputFC
コード例 #13
0
    def createOutput(self, outputFC):
        """Creates an Output Feature Class with the Standard Distances.

        INPUTS:
        outputFC (str): path to the output feature class
        """

        #### Validate Output Workspace ####
        ERROR.checkOutputPath(outputFC)

        #### Shorthand Attributes ####
        ssdo = self.ssdo
        caseField = self.caseField

        #### Increase Extent if not Projected ####
        if ssdo.spatialRefType != "Projected":
            seValues = self.se.values()
            if len(seValues):
                maxSE = NUM.array([ i[0:2] for i in seValues ]).max()
                largerExtent = UTILS.increaseExtentByConstant(ssdo.extent,
                                                        constant = maxSE)
                largerExtent = [ LOCALE.str(i) for i in largerExtent ]
                ARCPY.env.XYDomain = " ".join(largerExtent)

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)

        try:
            DM.CreateFeatureclass(outPath, outName, "POLYGON", 
                                  "", ssdo.mFlag, ssdo.zFlag, 
                                  ssdo.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Fields to Output FC ####
        dataFieldNames = UTILS.getFieldNames(seFieldNames, outPath)
        shapeFieldNames = ["SHAPE@"]
        for fieldName in dataFieldNames:
            UTILS.addEmptyField(outputFC, fieldName, "DOUBLE")

        caseIsDate = False
        if caseField:
            fcCaseField = ssdo.allFields[caseField]
            validCaseName = UTILS.validQFieldName(fcCaseField, outPath)
            caseType = UTILS.convertType[fcCaseField.type]
            UTILS.addEmptyField(outputFC, validCaseName, caseType)
            dataFieldNames.append(validCaseName)
            if caseType.upper() == "DATE":
                caseIsDate = True

        #### Write Output ####
        badCaseRadians = []
        allFieldNames = shapeFieldNames + dataFieldNames
        rows = DA.InsertCursor(outputFC, allFieldNames)
        for case in self.caseKeys:

            #### Get Results ####
            xVal, yVal = self.meanCenter[case]
            seX, seY, degreeRotation, radianR1, radianR2 = self.se[case]
            seX2 = seX**2.0
            seY2 = seY**2.0

            #### Create Empty Polygon Geomretry ####
            poly = ARCPY.Array()

            #### Check for Valid Radius ####
            seXZero = UTILS.compareFloat(0.0, seX, rTol = .0000001)
            seXNan = NUM.isnan(seX)
            seXBool = seXZero + seXNan
            seYZero = UTILS.compareFloat(0.0, seY, rTol = .0000001)
            seYNan = NUM.isnan(seY)
            seYBool = seYZero + seYNan
            if seXBool or seYBool:
                badRadian = 6
                badCase = UTILS.caseValue2Print(case, self.caseIsString)
                badCaseRadians.append(badCase)
            else:
                badRadian = 0
                cosRadian = NUM.cos(radianR1)
                sinRadian = NUM.sin(radianR1)

                #### Calculate a Point For Each ####
                #### Degree in Ellipse Polygon ####                
                for degree in NUM.arange(0, 360): 
                    try:
                        radians = UTILS.convert2Radians(degree)
                        tanVal2 = NUM.tan(radians)**2.0
                        dX = MATH.sqrt((seX2 * seY2) /
                                      (seY2 + (seX2 * tanVal2)))
                        dY = MATH.sqrt((seY2 * (seX2 - dX**2.0)) /
                                       seX2)

                        #### Adjust for Quadrant ####
                        if 90 <= degree < 180:
                            dX = -dX
                        elif 180 <= degree < 270:
                            dX = -dX
                            dY = -dY
                        elif degree >= 270:
                            dY = -dY

                        #### Rotate X and Y ####
                        dXr = dX * cosRadian - dY * sinRadian
                        dYr = dX * sinRadian + dY * cosRadian

                        #### Create Point Shifted to ####
                        #### Ellipse Centroid ####
                        pntX = dXr + xVal
                        pntY = dYr + yVal
                        pnt = ARCPY.Point(pntX, pntY, ssdo.defaultZ)
                        poly.add(pnt)
                    except:
                        badRadian += 1
                        if badRadian == 6:
                            badCase = UTILS.caseValue2Print(case, 
                                               self.caseIsString)
                            badCaseRadians.append(badCase)
                            break

            if badRadian < 6:
                #### Create and Populate New Feature ####
                poly = ARCPY.Polygon(poly, None, True)
                rowResult = [poly, xVal, yVal, seX, seY, radianR2]

                if caseField:
                    caseValue = case.item()
                    if caseIsDate:
                        caseValue = TUTILS.iso2DateTime(caseValue)
                    rowResult.append(caseValue)
                rows.insertRow(rowResult)

        #### Report Bad Cases Due to Geometry (coincident pts) ####
        nBadRadians = len(badCaseRadians)
        if nBadRadians:
            if caseField:
                badCaseRadians = " ".join(badCaseRadians)
                ARCPY.AddIDMessage("WARNING", 1011, caseField, badCaseRadians)
            else:
                ARCPY.AddIDMessage("ERROR", 978)
                raise SystemExit()

        #### Return Extent to Normal if not Projected ####
        if ssdo.spatialRefType != "Projected":
            ARCPY.env.XYDomain = ""

        #### Clean Up ####
        del rows

        #### Set Attribute ####
        self.outputFC = outputFC
コード例 #14
0
    def createOutputShapes(self, outputFC):
        #### Shorthand Attributes ####
        ssdoBase = self.ssdoBase
        ssdoCand = self.ssdoCand

        #### Validate Output Workspace ####
        ARCPY.overwriteOutput = True
        ERROR.checkOutputPath(outputFC)

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)
        tempFC = UTILS.returnScratchName("TempSS_FC", fileType = "FEATURECLASS",
                                         scratchWS = outPath)
        outTempPath, outTempName = OS.path.split(tempFC)

        try:
            DM.CreateFeatureclass(outTempPath, outTempName, ssdoBase.shapeType, 
                                  "", ssdoBase.mFlag, 
                                  ssdoBase.zFlag, ssdoBase.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Null Value Flag ####
        outIsShapeFile = UTILS.isShapeFile(outputFC)
        setNullable = outIsShapeFile == False

        #### Make Feature Layer and Select Result OIDs/Shapes ####
        featureCount = ssdoBase.numObs + ssdoCand.numObs
        ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84003), 0,
                                                 featureCount, 1)

        #### Add Shape/ID Field Names ####
        matchID, candID = outputIDFieldNames
        outFieldNames = ["SHAPE@"] + outputIDFieldNames
        inFieldNames = ["OID@", "SHAPE@"]
        UTILS.addEmptyField(tempFC, matchID, "LONG", nullable = True)
        UTILS.addEmptyField(tempFC, candID, "LONG", nullable = True)

        #### Add Append Fields ####
        lenAppend = len(self.appendFields) 
        appendIsDate = []
        in2OutFieldNames = {}
        if lenAppend:
            for fieldName in self.appendFields:
                fcField = ssdoCand.allFields[fieldName]
                fieldType = UTILS.convertType[fcField.type]
                fieldOutName = UTILS.validQFieldName(fcField, outPath)
                in2OutFieldNames[fieldName] = fieldOutName
                if fieldType == "DATE":
                    appendIsDate.append(fieldName)
                UTILS.addEmptyField(tempFC, fieldOutName, fieldType,
                                    alias = fcField.alias)
                outFieldNames.append(fieldOutName)

        #### Add Analysis Fields ####
        for fieldName in self.fieldNames:
            fcField = ssdoBase.allFields[fieldName]
            fieldType = UTILS.convertType[fcField.type]
            fieldOutName = UTILS.validQFieldName(fcField, outPath)
            in2OutFieldNames[fieldName] = fieldOutName
            UTILS.addEmptyField(tempFC, fieldOutName, fieldType,
                                alias = fcField.alias)
            outFieldNames.append(fieldOutName)

        dataFieldNames = matchFieldInfo[self.similarType]
        dataFieldInfo = outputFieldInfo[self.matchMethod]
        baseValues = []
        for fieldName in dataFieldNames:
            outAlias, outType, baseValue = dataFieldInfo[fieldName]
            UTILS.addEmptyField(tempFC, fieldName, outType, 
                                alias = outAlias, 
                                nullable = setNullable) 
            outFieldNames.append(fieldName)
            baseValues.append(baseValue)

        #### Get Insert Cursor ####
        baseRows = DA.SearchCursor(ssdoBase.inputFC, inFieldNames)
        candRows = DA.SearchCursor(ssdoCand.inputFC, inFieldNames)
        rows = DA.InsertCursor(tempFC, outFieldNames)

        #### Set Base Data ####
        useShapeNull = outIsShapeFile
        if useShapeNull:
            nullIntValue = UTILS.shpFileNull['LONG']
        else:
            nullIntValue = None

        #### Set Base Null For Append ####
        appendNull = {}
        for fieldName in self.appendFields:
            if fieldName not in ssdoBase.fields:
                if useShapeNull:
                    outType = ssdoCand.fields[fieldName].type
                    outNullValue = UTILS.shpFileNull[outType]
                else:
                    outNullValue = None
                appendNull[fieldName] = outNullValue

        #### Add Base Data ####
        for masterID, shp in baseRows:
            orderID = ssdoBase.master2Order[masterID]

            #### Insert Shape, Match_ID and NULL (Cand_ID) ####
            rowRes = [shp, masterID, nullIntValue]

            #### Add Append Fields ####
            for fieldName in self.appendFields:
                if fieldName in appendNull:
                    rowRes.append(appendNull[fieldName])
                else:
                    value = ssdoBase.fields[fieldName].data[orderID]
                    if fieldName in appendIsDate:
                        value = TUTILS.iso2DateTime(value)
                    rowRes.append(value)

            #### Add Analysis Fields ####
            for fieldName in self.fieldNames:
                rowRes.append(ssdoBase.fields[fieldName].data[orderID])

            #### Add Null Base Values ####
            rowRes += baseValues

            rows.insertRow(rowRes)
            ARCPY.SetProgressorPosition()
        del baseRows
        
        #### First Add Similar Results ####
        for masterID, shp in candRows:
            orderID = ssdoCand.master2Order[masterID]
            indTop = NUM.where(self.topIDs == orderID)[0]
            indBot = NUM.where(self.botIDs == orderID)[0]
            if self.similarType in ['MOST_SIMILAR', 'BOTH'] and len(indTop):
                ind = indTop[0]
                #### Insert Shape, NULL (Match_ID) and Cand_ID ####
                rowRes = [shp, nullIntValue, masterID]
                
                #### Add Append Fields ####
                for fieldName in self.appendFields:
                    rowRes.append(ssdoCand.fields[fieldName].data[orderID])

                #### Add Analysis Fields ####
                for fieldName in self.fieldNames:
                    rowRes.append(ssdoCand.fields[fieldName].data[orderID])

                #### Add Results ####
                rank = ind + 1
                ss = self.totalDist[orderID]

                if self.similarType == 'BOTH':
                    rowRes += [rank, nullIntValue, ss, rank]
                else:
                    rowRes += [rank, ss, rank]

                rows.insertRow(rowRes)
            if self.similarType in ['LEAST_SIMILAR', 'BOTH'] and len(indBot):
                ind = indBot[0]
                #### Insert Shape, NULL (Match_ID) and Cand_ID ####
                rowRes = [shp, nullIntValue, masterID]

                #### Add Append Fields ####
                for fieldName in self.appendFields:
                    rowRes.append(ssdoCand.fields[fieldName].data[orderID])

                #### Add Analysis Fields ####
                for fieldName in self.fieldNames:
                    rowRes.append(ssdoCand.fields[fieldName].data[orderID])

                #### Add Results ####
                rank = ind + 1
                labRank = rank * -1
                ss = self.totalDist[orderID]

                if self.similarType == 'BOTH':
                    rowRes += [nullIntValue, rank, ss, labRank]
                else:
                    rowRes += [rank, ss, labRank]

                rows.insertRow(rowRes)

            ARCPY.SetProgressorPosition()
        del candRows
        del rows

        #### Do Final Sort ####
        if self.matchMethod == 'ATTRIBUTE_PROFILES':
            if self.similarType == 'MOST_SIMILAR':
                sortString = "SIMINDEX DESCENDING;SIMRANK DESCENDING"
            else:
                sortString = "SIMINDEX DESCENDING"
        else:
            if self.similarType == 'MOST_SIMILAR':
                sortString = "SIMINDEX ASCENDING;SIMRANK ASCENDING"
            else:
                sortString = "SIMINDEX ASCENDING"
        DM.Sort(tempFC, outputFC, sortString, "UR")

        #### Clean Up ####
        DM.Delete(tempFC)

        #### Symbology ####
        params = ARCPY.gp.GetParameterInfo()
        try:
            renderType = UTILS.renderType[self.ssdoBase.shapeType.upper()]
            renderKey = (self.similarType, renderType)
            renderLayerFile = outputRenderInfo[renderKey]
            templateDir = OS.path.dirname(OS.path.dirname(SYS.argv[0]))
            fullRLF = OS.path.join(templateDir, "Templates",
                                   "Layers", renderLayerFile)
            params[2].Symbology = fullRLF
        except:
            ARCPY.AddIDMessage("WARNING", 973)
コード例 #15
0
    def createOutput(self, outputFC):
        #### Shorthand Attributes ####
        ssdoBase = self.ssdoBase
        ssdoCand = self.ssdoCand

        #### Validate Output Workspace ####
        ARCPY.overwriteOutput = True
        ERROR.checkOutputPath(outputFC)

        #### Create Output Feature Class ####
        ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84003))
        outPath, outName = OS.path.split(outputFC)

        try:
            DM.CreateFeatureclass(outPath, outName, "POINT", "", ssdoBase.mFlag, 
                                  ssdoBase.zFlag, ssdoBase.spatialRefString)
        except:
            ARCPY.AddIDMessage("ERROR", 210, outputFC)
            raise SystemExit()

        #### Add Null Value Flag ####
        outIsShapeFile = UTILS.isShapeFile(outputFC)
        setNullable = outIsShapeFile == False

        #### Add Shape/ID Field Names ####
        matchID, candID = outputIDFieldNames
        outFieldNames = ["SHAPE@"] + outputIDFieldNames
        UTILS.addEmptyField(outputFC, matchID, "LONG", nullable = True)
        UTILS.addEmptyField(outputFC, candID, "LONG", nullable = True)

        #### Add Append Fields ####
        lenAppend = len(self.appendFields) 
        appendIsDate = []
        in2OutFieldNames = {}
        if lenAppend:
            for fieldName in self.appendFields:
                fcField = ssdoCand.allFields[fieldName]
                fieldType = UTILS.convertType[fcField.type]
                fieldOutName = UTILS.validQFieldName(fcField, outPath)
                in2OutFieldNames[fieldName] = fieldOutName
                if fieldType == "DATE":
                    appendIsDate.append(fieldName)
                UTILS.addEmptyField(outputFC, fieldOutName, fieldType,
                                    alias = fcField.alias)
                outFieldNames.append(fieldOutName)

        #### Add Analysis Fields ####
        for fieldName in self.fieldNames:
            fcField = ssdoBase.allFields[fieldName]
            fieldType = UTILS.convertType[fcField.type]
            fieldOutName = UTILS.validQFieldName(fcField, outPath)
            in2OutFieldNames[fieldName] = fieldOutName
            UTILS.addEmptyField(outputFC, fieldOutName, fieldType,
                                alias = fcField.alias)
            outFieldNames.append(fieldOutName)

        dataFieldNames = matchFieldInfo[self.similarType]
        dataFieldInfo = outputFieldInfo[self.matchMethod]
        baseValues = []
        for fieldName in dataFieldNames:
            outAlias, outType, baseValue = dataFieldInfo[fieldName]
            UTILS.addEmptyField(outputFC, fieldName, outType, 
                                alias = outAlias, 
                                nullable = setNullable) 
            outFieldNames.append(fieldName)
            baseValues.append(baseValue)

        #### Step Progress ####
        featureCount = ssdoBase.numObs + self.numResults
        if self.similarType == "BOTH":
            featureCount += self.numResults
        ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84003), 0,
                                                 featureCount, 1)
        #### Get Insert Cursor ####
        rows = DA.InsertCursor(outputFC, outFieldNames)
        
        #### Set Base Data ####
        useShapeNull = outIsShapeFile
        if useShapeNull:
            nullIntValue = UTILS.shpFileNull['LONG']
        else:
            nullIntValue = None

        #### Set Base Null For Append ####
        appendNull = {}
        for fieldName in self.appendFields:
            if fieldName not in ssdoBase.fields:
                if useShapeNull:
                    outType = ssdoCand.fields[fieldName].type
                    outNullValue = UTILS.shpFileNull[outType]
                else:
                    outNullValue = None
                appendNull[fieldName] = outNullValue

        #### Add Base Data ####
        for orderID in xrange(ssdoBase.numObs):
            x,y = ssdoBase.xyCoords[orderID]
            pnt = (x, y, ssdoBase.defaultZ)

            #### Insert Shape, Match_ID and NULL (Cand_ID) ####
            rowRes = [pnt, ssdoBase.order2Master[orderID], nullIntValue]

            #### Add Append Fields ####
            for fieldName in self.appendFields:
                if fieldName in appendNull:
                    rowRes.append(appendNull[fieldName])
                else:
                    value = ssdoBase.fields[fieldName].data[orderID]
                    if fieldName in appendIsDate:
                        value = TUTILS.iso2DateTime(value)
                    rowRes.append(value)

            #### Add Analysis Fields ####
            for fieldName in self.fieldNames:
                rowRes.append(ssdoBase.fields[fieldName].data[orderID])

            #### Add Null Base Values ####
            rowRes += baseValues

            rows.insertRow(rowRes)
            ARCPY.SetProgressorPosition()
        
        if self.similarType in ['MOST_SIMILAR', 'BOTH']:
            #### First Add Similar Results ####
            for ind, orderID in enumerate(self.topIDs):
                x,y = ssdoCand.xyCoords[orderID]
                pnt = (x, y, ssdoBase.defaultZ)

                #### Insert Shape, NULL (Match_ID) and Cand_ID ####
                rowRes = [pnt, nullIntValue, ssdoCand.order2Master[orderID]]

                #### Add Append Fields ####
                for fieldName in self.appendFields:
                    rowRes.append(ssdoCand.fields[fieldName].data[orderID])

                #### Add Analysis Fields ####
                for fieldName in self.fieldNames:
                    rowRes.append(ssdoCand.fields[fieldName].data[orderID])

                #### Add Results ####
                rank = ind + 1
                ss = self.totalDist[orderID]

                if self.similarType == 'BOTH':
                    rowRes += [rank, nullIntValue, ss, rank]
                else:
                    rowRes += [rank, ss, rank]

                rows.insertRow(rowRes)
                ARCPY.SetProgressorPosition()

        if self.similarType in ['LEAST_SIMILAR', 'BOTH']:
            #### Add Least Similar #### 
            for ind, orderID in enumerate(self.botIDs):
                x,y = ssdoCand.xyCoords[orderID]
                pnt = (x, y, ssdoBase.defaultZ)

                #### Insert Shape, NULL (Match_ID) and Cand_ID ####
                rowRes = [pnt, nullIntValue, ssdoCand.order2Master[orderID]]

                #### Add Append Fields ####
                for fieldName in self.appendFields:
                    rowRes.append(ssdoCand.fields[fieldName].data[orderID])

                #### Add Analysis Fields ####
                for fieldName in self.fieldNames:
                    rowRes.append(ssdoCand.fields[fieldName].data[orderID])

                #### Add Results ####
                rank = ind + 1
                labRank = rank * -1
                ss = self.totalDist[orderID]

                if self.similarType == 'BOTH':
                    rowRes += [nullIntValue, rank, ss, labRank]
                else:
                    rowRes += [rank, ss, labRank]

                rows.insertRow(rowRes)
                ARCPY.SetProgressorPosition()

        #### Clean Up ####
        del rows

        #### Symbology ####
        params = ARCPY.gp.GetParameterInfo()
        try:
            renderKey = (self.similarType, 0)
            renderLayerFile = outputRenderInfo[renderKey]
            templateDir = OS.path.dirname(OS.path.dirname(SYS.argv[0]))
            fullRLF = OS.path.join(templateDir, "Templates",
                                   "Layers", renderLayerFile)
            params[2].Symbology = fullRLF
        except:
            ARCPY.AddIDMessage("WARNING", 973)