Example #1
0
def compute_gwr(cityid):
    input_path = path.join(LATLNGS_SHP_DIR, '%s_age.shp' % cityid)
    output_path = path.join(CACHE_DIR, 'gwr', '%s.shp' % cityid)
    rasters_path = path.join(CACHE_DIR, 'gwr_rasters')
    print 'Computing gwr for city %s' % cityid
    arcpy.GeographicallyWeightedRegression_stats(input_path, 'income', 'price', output_path, 
                                                 'ADAPTIVE', 'BANDWIDTH PARAMETER',
                                                 '#', '25', '#', rasters_path,)
    print 'DONE!'
Example #2
0
def gwr_shape(SJfile):

    print "Creating GWR layer..."

    GWRfile = "gwr_final.shp"
    GWRdbf = "gwr_final_supp.dbf"
    if os.path.isfile(GWRdbf) == True:
        os.remove(GWRdbf)
    if arcpy.Exists(GWRfile):
        arcpy.Delete_management(GWRfile)

    arcpy.GeographicallyWeightedRegression_stats(SJfile, "canrate",
                                                 "grid_code", GWRfile, "FIXED",
                                                 "AICc")

    print "Finished GWR!\n"

    bar['value'] = 100
    bar.update()

    idwbtn.config(state=NORMAL)
    tractsbtn.config(state=NORMAL)
    # If an error occurred, print line number and error message
    import traceback, sys
    tb = sys.exc_info()[2]
    print "Line %i" % tb.tb_lineno
    print e.message

#############################
# Run Regression on the new joined censusjoin shapefile

arcpy.env.overwriteOutput = True

workspace = "C:\project1"

try:
    # Set the current workspace (to avoid having to specify the full path to the feature classes each time)
    arcpy.env.workspace = workspace

    # 911 Calls as a function of {number of businesses, number of rental units,
    # number of adults who didn't finish high school}
    # Process: Geographically Weighted Regression...
    gwr = arcpy.GeographicallyWeightedRegression_stats("censusjoin.shp",
                                                       "canrate", "MEAN",
                                                       "CancerGWR.shp",
                                                       "ADAPTIVE",
                                                       "BANDWIDTH PARAMETER")

except:
    # If an error occurred when running the tool, print out the error message.
    print(arcpy.GetMessages())
print "OLS Complete. PDF Exported."
        arcpy.RasterToPoint_conversion(inraster3, rasterPoint3, "VALUE")
        arcpy.RasterToPoint_conversion(inraster4, rasterPoint4, "VALUE")
        arcpy.RasterToPoint_conversion(inraster5, rasterPoint5, "VALUE")
        arcpy.RasterToPoint_conversion(inraster6, rasterPoint6, "VALUE")

        # spatial join points to fishnet and get the average values
        spatialJoin_result = root + "spaResult_ESI.shp"
        SpatialJoinESI(inboundary, rasterPoint1, rasterPoint2, rasterPoint3,
                       rasterPoint4, rasterPoint5, rasterPoint6,
                       spatialJoin_result)

        # run GWR
        GWR_result = root + "GWR_resultESI.shp"
        predictor = "pre1;pre2;pre3;pre4;pre5"
        arcpy.GeographicallyWeightedRegression_stats(
            spatialJoin_result, "DV", predictor, GWR_result, "ADAPTIVE",
            "BANDWIDTH PARAMETER", "#", "50", "#", "#", "#", "#", "#", "#")

        # reclassify GWR predicted value and get the FUI classification
        # Replicate the GWR result
        GWR_reclassify = output
        arcpy.Copy_management(GWR_result, GWR_reclassify)
        arcpy.AddField_management(GWR_reclassify, "ESI", "DOUBLE", 20, 5)

        # get the min and max predicted values
        GWR_min = GWR_reclassify[:-4] + "_min.shp"
        GWR_max = GWR_reclassify[:-4] + "_max.shp"

        arcpy.Sort_management(GWR_reclassify, GWR_min,
                              [["Predicted", "ASCENDING"]])
        arcpy.Sort_management(GWR_reclassify, GWR_max,
def GWRFunction(
    LocPts, TempPts, RLoc, TTimes, coutdir, ctempdir, InputDir, TempStation,
    Datadict, HVal, LVal, TempDir, mth, var, PreName, minstr, Spref, Conv,
    ConvEq, ConvUnits, ConvFolder, ConvName
):  ######Function to execute GWR, Rasters for English Standar Metrics and converstion to internation metrics if requested

    opdt = dt.datetime.utcnow()
    arcpy.CopyFeatures_management(LocPts, TempPts)
    ptdt("CopyStationsAndPredPoints")

    ourFields = arcpy.ListFields(TempPts)
    print "in memory points location field names"
    for afield in ourFields:
        print afield.name

    ###FIDToXYLocation = {}
    ####rows = arcpy.da.SearchCursor(LocPts, ["FID", "X", "Y"])

    ###for row in rows:
    #####FIDToXYLocation[row[0]] = [row[1], row[2]]

    RasterLst = []
    ConvRasterLst = []
    KMLLst = []
    ConvKMLLst = []
    for num, targetTime in enumerate(TTimes):
        thisIndex = targetTime[2]
        print thisIndex
        outputdirectory = coutdir + "\\o" + minstr + "_" + str(num)
        if not os.path.exists(outputdirectory):
            os.makedirs(outputdirectory)
        intermediatedirectory = ctempdir + "\\o" + minstr + "_" + str(num)
        if not os.path.exists(intermediatedirectory):
            os.makedirs(intermediatedirectory)
        print num, targetTime
        starttime = targetTime[0]
        print starttime
        endtime = targetTime[1]
        print endtime
        modelrunstarttime = dt.datetime.now()
        opdt = dt.datetime.utcnow()
        arcpy.AddField_management(TempStation, "VALUE" + str(num), "FLOAT")
        ptdt("Add VALUE FIELD")

        StationsWithInvalidValues = []

        opdt = dt.datetime.utcnow()
        with arcpy.da.UpdateCursor(TempStation,
                                   ["STATION_CO", "VALUE" + str(num)]) as rows:
            for row in rows:
                if mth == "Sum":
                    stationvalues = [
                        Datadict[row[0]][atime]
                        for atime in Datadict[row[0]].keys()
                        if atime <= endtime
                    ]
                    if all(((avalue > LVal and avalue < HVal)
                            and avalue is not None)
                           for avalue in stationvalues):
                        val = sum([
                            Datadict[row[0]][atime]
                            for atime in Datadict[row[0]].keys()
                            if atime <= endtime
                        ])
                        row[1] = val
                        rows.updateRow(row)
                elif mth == "Max":
                    stationvalues = [
                        Datadict[row[0]][atime]
                        for atime in Datadict[row[0]].keys()
                        if atime <= endtime
                    ]
                    if all(((avalue > LVal and avalue < HVal)
                            and avalue is not None)
                           for avalue in stationvalues):
                        val = ([
                            Datadict[row[0]][atime]
                            for atime in Datadict[row[0]].keys()
                            if atime <= endtime
                        ])
                        Mval = max(val)
                        row[1] = Mval
                        rows.updateRow(row)
                elif mth == "Min":
                    stationvalues = [
                        Datadict[row[0]][atime]
                        for atime in Datadict[row[0]].keys()
                        if atime <= endtime
                    ]
                    if all(((avalue > LVal and avalue < HVal)
                            and avalue is not None)
                           for avalue in stationvalues):
                        val = ([
                            Datadict[row[0]][atime]
                            for atime in Datadict[row[0]].keys()
                            if atime <= endtime
                        ])
                        Mval = min(val)
                        row[1] = Mval
                        rows.updateRow(row)
                else:
                    print stationvalues
                    print "row contents ", str(row[1])
                    StationsWithInvalidValues.append(row[0])
        del row

        ptdt("Add parameter values.")

        print "Invalid Value Stations: ", str(len(StationsWithInvalidValues))

        cellsize = "0.05"
        explanatory_field = "RASTERVALU"
        kerneltype = "ADAPTIVE"
        bandwidth = "BANDWIDTH_PARAMETER"
        dependent = "VALUE" + str(num)
        distance = ""
        numberofneighbors = 23

        out_featureclass = "in_memory\\out" + str(num)
        out_featureclass = TempDir + "\\outf" + str(num) + ".shp"
        out_prediction_featureclass = "in_memory\\outpp" + str(num)
        out_prediction_featureclass = TempDir + "\\outfc" + str(num) + ".shp"
        out_prediciton_raster = "in_memory\\outpr" + str(num)

        opdt = dt.datetime.utcnow()

        arcpy.GeographicallyWeightedRegression_stats(
            in_features=TempStation,
            dependent_field=dependent,
            explanatory_field=explanatory_field,
            out_featureclass=out_featureclass,
            kernel_type=kerneltype,
            bandwidth_method=bandwidth,
            distance=distance,
            number_of_neighbors=numberofneighbors,
            weight_field="",
            coefficient_raster_workspace="",
            cell_size="",
            in_prediction_locations=TempPts,
            prediction_explanatory_field=explanatory_field,
            out_prediction_featureclass=out_prediction_featureclass)

        ptdt("GWR done.")
        ptdt(out_prediction_featureclass)
        print "shape 1"
        ptdt(LocPts)
        ptdt(RLoc)
        ptdt(intermediatedirectory)
        ptdt(outputdirectory)
        ptdt(InputDir)
        ptdt(thisIndex)
        ptdt(var)
        ptdt(PreName)
        ptdt(minstr)
        RasterRes, CRasterRes, KMLRes, CKMRes = CreateRasters(
            LocPts, RLoc, num, out_prediction_featureclass,
            intermediatedirectory, outputdirectory, InputDir, thisIndex, var,
            PreName, minstr, Spref, Conv, ConvEq, ConvUnits, ConvFolder,
            ConvName)

        RasterLst.append(RasterRes)
        ConvRasterLst.append(CRasterRes)
        KMLLst.append(KMLRes)
        ConvKMLLst.append(CKMRes)

    return RasterLst, ConvRasterLst, KMLLst, ConvKMLLst