예제 #1
0
파일: Weights.py 프로젝트: leochin/GSWMtest
def polygon2SWM(inputFC, swmFile, masterField, 
                concept = "EUCLIDEAN", kNeighs = 0,
                rowStandard = True, contiguityType = "ROOK"):
    """Creates a sparse spatial weights matrix (SWM) based on polygon
    contiguity. 

    INPUTS: 
    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
    kNeighs {int, 0}: number of neighbors to return (1)
    rowStandard {bool, True}: row standardize weights?
    contiguityType {str, Rook}: {Rook = Edges Only, Queen = Edges/Vertices}

    NOTES:
    (1) kNeighs is used if polygon is not contiguous. E.g. Islands
    """

    #### Set Default Progressor for Neigborhood Structure ####
    ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84143))

    #### Create SSDataObject ####
    ssdo = SSDO.SSDataObject(inputFC, templateFC = inputFC,
                             useChordal = True)
    cnt = UTILS.getCount(inputFC)
    ERROR.errorNumberOfObs(cnt, minNumObs = 2)

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

    #### Create GA Data Structure ####
    gaTable, gaInfo = WU.gaTable(ssdo.catPath, [masterField],
                                 spatRef = ssdo.spatialRefString)

    #### Assure Enough Observations ####
    N = gaInfo[0]
    ERROR.errorNumberOfObs(N, minNumObs = 2)

    #### Assure k-Nearest is Less Than Number of Features ####
    if kNeighs >= N:
        ARCPY.AddIDMessage("ERROR", 975)
        raise SystemExit()

    #### Create Nearest Neighbor Search Type For Islands ####
    if kNeighs > 0:
        gaSearch = GAPY.ga_nsearch(gaTable)
        concept, gaConcept = WU.validateDistanceMethod(concept, ssdo.spatialRef)
        gaSearch.init_nearest(0.0, kNeighs, gaConcept)
        forceNeighbor = True
        neighWeights = ARC._ss.NeighborWeights(gaTable, gaSearch, 
                                               weight_type = 1,
                                               row_standard = False)
    else:
        forceNeighbor = False
        neighSearch = None

    #### Create Polygon Neighbors ####
    polyNeighborDict = WU.polygonNeighborDict(inputFC, masterField, 
                                   contiguityType = contiguityType)

    #### Write Poly Neighbor List (Dict) ####
    #### Set Progressor for SWM Writing ####
    ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84127), 0, N, 1)

    #### Initialize Spatial Weights Matrix File ####
    if contiguityType == "ROOK":
        wType = 4
    else:
        wType = 5

    swmWriter = WU.SWMWriter(swmFile, masterField, ssdo.spatialRefName, 
                             N, rowStandard, inputFC = inputFC,
                             wType = wType, distanceMethod = concept,
                             numNeighs = kNeighs)

    #### Keep Track of Polygons w/o Neighbors ####
    islandPolys = []
    
    #### Write Polygon Contiguity to SWM File ####
    for row in xrange(N):
        rowInfo = gaTable[row]
        oid = rowInfo[0]
        masterID = rowInfo[2]
        neighs = polyNeighborDict[masterID]
        nn = len(neighs)
        if forceNeighbor:
            if nn < kNeighs:
                #### Only Force KNN If Specified & Contiguity is Less ####
                islandPolys.append(oid)
                flag = True
                knnNeighs, knnWeights = neighWeights[row]
                c = 0
                while flag:
                    try:
                        neighID = gaTable[knnNeighs[c]][2]
                        if neighID not in neighs:
                            neighs.append(neighID)
                            nn += 1
                            if nn == kNeighs:
                                flag = False
                        c += 1
                    except:
                        flag = False

        weights = NUM.ones(nn)

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

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

    #### Report on Features with No Neighbors ####
    countIslands = len(islandPolys)
    if countIslands:
        islandPolys.sort()
        if countIslands > 30:
            islandPolys = islandPolys[0:30]
        
        ERROR.warningNoNeighbors(N, countIslands, islandPolys, ssdo.oidName, 
                                 forceNeighbor = forceNeighbor, 
                                 contiguity = True)

    #### Clean Up ####
    swmWriter.close()
    del gaTable

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

    #### Report SWM File is Large ####
    swmWriter.reportLargeSWM()

    del polyNeighborDict
예제 #2
0
def polygon2SWM(inputFC, swmFile, masterField, 
                concept = "EUCLIDEAN", kNeighs = 0,
                rowStandard = True, contiguityType = "ROOK"):
    """Creates a sparse spatial weights matrix (SWM) based on polygon
    contiguity. 

    INPUTS: 
    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
    kNeighs {int, 0}: number of neighbors to return (1)
    rowStandard {bool, True}: row standardize weights?
    contiguityType {str, Rook}: {Rook = Edges Only, Queen = Edges/Vertices}

    NOTES:
    (1) kNeighs is used if polygon is not contiguous. E.g. Islands
    """

    #### Set Default Progressor for Neigborhood Structure ####
    ARCPY.SetProgressor("default", ARCPY.GetIDMessage(84143))

    #### Create SSDataObject ####
    ssdo = SSDO.SSDataObject(inputFC, templateFC = inputFC,
                             useChordal = True)
    cnt = UTILS.getCount(inputFC)
    ERROR.errorNumberOfObs(cnt, minNumObs = 2)

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

    #### Create GA Data Structure ####
    gaTable, gaInfo = WU.gaTable(ssdo.catPath, [masterField],
                                 spatRef = ssdo.spatialRefString)

    #### Assure Enough Observations ####
    N = gaInfo[0]
    ERROR.errorNumberOfObs(N, minNumObs = 2)

    #### Assure k-Nearest is Less Than Number of Features ####
    if kNeighs >= N:
        ARCPY.AddIDMessage("ERROR", 975)
        raise SystemExit()

    #### Create Nearest Neighbor Search Type For Islands ####
    gaSearch = GAPY.ga_nsearch(gaTable)
    concept, gaConcept = WU.validateDistanceMethod(concept, ssdo.spatialRef)
    gaSearch.init_nearest(0.0, kNeighs, gaConcept)
    if kNeighs > 0:
        forceNeighbor = True
        neighWeights = ARC._ss.NeighborWeights(gaTable, gaSearch, 
                                              weight_type = 1,
                                              row_standard = False)
    else:
        forceNeighbor = False
        neighSearch = None

    #### Create Polygon Neighbors ####
    polyNeighborDict = WU.polygonNeighborDict(inputFC, masterField, 
                                   contiguityType = contiguityType)

    #### Write Poly Neighbor List (Dict) ####
    #### Set Progressor for SWM Writing ####
    ARCPY.SetProgressor("step", ARCPY.GetIDMessage(84127), 0, N, 1)

    #### Initialize Spatial Weights Matrix File ####
    if contiguityType == "ROOK":
        wType = 4
    else:
        wType = 5

    swmWriter = WU.SWMWriter(swmFile, masterField, ssdo.spatialRefName, 
                             N, rowStandard, inputFC = inputFC,
                             wType = wType, distanceMethod = concept,
                             numNeighs = kNeighs)

    #### Keep Track of Polygons w/o Neighbors ####
    islandPolys = []
    
    #### Write Polygon Contiguity to SWM File ####
    for row in xrange(N):
        rowInfo = gaTable[row]
        oid = rowInfo[0]
        masterID = rowInfo[2]
        neighs = polyNeighborDict[masterID]
        if neighs:
            weights = [ 1. for nh in neighs ]
            isIsland = False
        else:
            isIsland = True
            islandPolys.append(oid)
            weights = []

        #### Get Nearest Neighbor Based On Centroid Distance ####
        if isIsland and forceNeighbor:
            neighs, weights = neighWeights[row]
            neighs = [ gaTable[nh][2] for nh in neighs ]

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

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

    #### Report on Features with No Neighbors ####
    countIslands = len(islandPolys)
    if countIslands:
        islandPolys.sort()
        if countIslands > 30:
            islandPolys = islandPolys[0:30]
        
        ERROR.warningNoNeighbors(N, countIslands, islandPolys, ssdo.oidName, 
                                 forceNeighbor = forceNeighbor, 
                                 contiguity = True)

    #### Clean Up ####
    swmWriter.close()
    del gaTable

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

    #### Report SWM File is Large ####
    swmWriter.reportLargeSWM()

    del polyNeighborDict