def make_rand_road_pts():
    """
    makes the 'rd_far_fld.shp' file which is points on roads that are spaced at least 300 ft from
    each other and at least 200 ft from any flood points
    :return: 
    """
    road_shapefile = "nor_roads_centerlines.shp"
    arcpy.Densify_edit(road_shapefile, densification_method='DISTANCE', distance=30)
    road_pts_file = 'rd_pts_all_1.shp'
    arcpy.FeatureVerticesToPoints_management(road_shapefile, road_pts_file)
    rand_rd_pts_file = 'rand_road.shp'
    rand_rd_pts_lyr = 'rand_road_lyr'
    arcpy.CreateRandomPoints_management(gis_proj_dir, rand_rd_pts_file, road_pts_file,
                                        number_of_points_or_field=50000,
                                        minimum_allowed_distance='200 Feet')
    print "rand_rd_points_file"
    fld_pts_file = 'flooded_points.shp'
    fld_pts_buf = 'fld_pt_buf.shp'
    arcpy.Buffer_analysis(fld_pts_file, fld_pts_buf, buffer_distance_or_field="200 Feet",
                          dissolve_option='ALL')
    print "buffer"
    arcpy.MakeFeatureLayer_management(rand_rd_pts_file, rand_rd_pts_lyr)
    arcpy.SelectLayerByLocation_management(rand_rd_pts_lyr, overlap_type='WITHIN',
                                           select_features=fld_pts_buf,
                                           invert_spatial_relationship='INVERT')
    rd_pts_outside_buf = 'rd_far_fld.shp'
    arcpy.CopyFeatures_management(rand_rd_pts_lyr, rd_pts_outside_buf)
    arcpy.JoinField_management(rd_pts_outside_buf, in_field='CID', join_table=road_pts_file,
                               join_field='FID')
    print "rd_points_outside_buf"
def Question_2():
    """
    Psuedocode for question 2.2:
    1. Import system modules

    2. Create random points in the features of a constraining feature class
    Number of points for each feature determined by the value in the field
    specified

    3. Set workspace

    4. Create fields for random values

    5. Calculate random values between 1-100 in the new fields
    """
    import arcpy

    out_path = ("C:\Users\pps7\Desktop\Lab6\Lab6a_FeatureClass")

    arcpy.env.workspace = ("C:\Users\pps7\Desktop\Lab6\Lab6a_FeatureClass")
    arcpy.env.overwriteOutput = True

    #Spatial_Reference = arcpy.Describe("C:\Users\pps7\Desktop\Lab6\Lab6a_FeatureClass\Schools").SpatialReference

    Output_Name = "School_Random_pts"
    Concise_FC = "C:\Users\pps7\Desktop\Lab6\Lab6a_FeatureClass\Schools.shp"
    Number_of_Points = 100
    arcpy.CreateRandomPoints_management(out_path, Output_Name, Concise_FC, "",
                                        100)
Exemple #3
0
def make_p(buffer_erased_final,point_count,outFC,point_layer):
	#all_points = getlocations(buffer_erased_final,point_count = point_count)
	outPath, outName = os.path.split(outFC)

	#minDistance = "600 Meters"
	minDistance = ""
	arcpy.CreateRandomPoints_management(outPath, outName, buffer_erased_final, "", point_count, minDistance) 
Exemple #4
0
def _create_random_points(area, buffer_val, points, messages):
    # Process: Buffer
    buffer_name = arcpy.CreateScratchName("temp", data_type="Shapefile", workspace=arcpy.env.scratchFolder)
    arcpy.Buffer_analysis(points, buffer_name, buffer_val, "FULL", "ROUND", "ALL", "", "PLANAR")

    # Process: Erase
    erase_name = arcpy.CreateScratchName("temp", data_type="Shapefile", workspace=arcpy.env.scratchFolder)
    arcpy.Erase_analysis(area, buffer_name, erase_name, "")

    # Process: Create Random Points
    random_name = arcpy.CreateScratchName("temp", data_type="FeatureClass", workspace=arcpy.env.scratchFolder)
    num_points = int(arcpy.GetCount_management(points))
    arcpy.CreateRandomPoints_management(arcpy.env.scratchFolder, random_name, erase_name, "0 0 250 250", num_points,
                                        "1 Meters", "POINT", "0")

    messages.AddMessage(str(arcpy.GetCount_management(random_name)) + " Random points created")

    # array = arcpy.da.FeatureClassToNumPyArray(random_name, "SHAPE@XY")

    # arcpy.Delete_management(buffer_name)
    # arcpy.Delete_management(erase_name)
    # arcpy.Delete_management(random_name)

    # return array
    return random_name
Exemple #5
0
def createRandomPoint(path):
    ap.CheckOutExtension("Spatial")
    outFolder = path
    numPoints = 40
    outName = "random_point.shp"
    conFC = path+"/out_final.img"

    ap.AddMessage("Creating Random Point")
    ap.CreateRandomPoints_management(outFolder, outName, "", conFC, numPoints) 
    ap.AddMessage("Finished creat random point")
def onRectangle(self, rectangle_geometry):
    extent = rectangle_geometry
    arcpy.env.workspace = r'c:\ArcpyBook\Ch10'
    if arcpy.Exists('randompts.shp'):
        arcpy.Delete_management('randompts.shp')
    randompts = arcpy.CreateRandomPoints_management(arcpy.env.workspace,
                                                    'randompts.shp', "",
                                                    rectangle_geometry)
    arcpy.RefreshActiveView()
    return randompts
Exemple #7
0
 def test_gpresult_dummy(self):
     arcpy.env.workspace = "in_memory"
     arcpy.env.overwriteOutput = True
     r = arcpy.CreateRandomPoints_management(out_path="in_memory", out_name="Guwu2",
                                             constraining_feature_class="#", constraining_extent="0 0 250 250",
                                             number_of_points_or_field="100", minimum_allowed_distance="0 Unknown",
                                             create_multipoint_output="POINT", multipoint_size="0")
     g = dump_gpresult(r)
     R = Result(g)
     self.assertEqual(r.outputCount, R.outputCount)
     self.assertEqual(r.inputCount, R.inputCount)
     # The output is the most important thing to ensure equality.
     self.assertListEqual([r.getOutput(i) for i in range(r.outputCount)],
                          [R.getOutput(i) for i in range(r.outputCount)])
Exemple #8
0
 def Create_random_points(self):
     '''
     Creating random points from the range of constraining feature.
     :param outpath: The geo-database to output.
     :param outname: The output feature name.
     :param constrainingfeatureclass: The range of generating random points.
     :param numberofpoints: The numbers for creating random points.
     :return:
     '''
     arcpy.AddMessage("Creating random points")
     # env.outputCoordinateSystem = arcpy.SpatialReference("Xian 1980 3 Degree GK Zone 43")
     arcpy.CreateRandomPoints_management(self.OutputFeaturePath, self.OutputFeatureName, self.InputConstraingFeature,'',self.Numbersofpoints)
     # arcpy.CreateFishnet_management(self.OutputFeature,'1397827.035600 4660075.233999999', '1397827.035599999 4660085.233999999 ', 1000,1000, 600, 700, '1694007.492800001 4940949.5798', "LABELS", '#', "POLYGON")
     arcpy.AddMessage("Finishing creating random points from %s"%str(self.OutputFeaturePath+'\\'+self.OutputFeatureName))
Exemple #9
0
def rnd_points(rndPntShp, NPoints, whereShp, distTolerance=None):
    """
    Create NRandom Points inside some area
    and save the result in one file
    """

    import os
    from gasp.oss import get_filename

    distT = "" if not distTolerance else "{} Meters".format(distTolerance)

    arcpy.CreateRandomPoints_management(os.path.dirname(rndPntShp),
                                        get_filename(rndPntShp), whereShp, "",
                                        NPoints, distT, "POINT", "0")

    return rndPntShp
Exemple #10
0
 def assign_pond_locations(self):
     """
     This method assigns random locations for each pond that fall within the bounds of
     suitable habitat.
     :return:
     """
     num_points = int(s.DENSITY * self.upland_area) - self.pond_count
     logging.info('num points: {}'.format(num_points))
     # constraint is the area of all suitable locations for new_ponds
     # num_points is the maximum number of new_ponds that should be assigned
     arcpy.CreateRandomPoints_management(
         out_path=s.TEMP_DIR,
         out_name=self._pond_point_file,
         constraining_feature_class=self.suitability_points,
         number_of_points_or_field=num_points,
         minimum_allowed_distance=s.MINIMUM_DISTANCE)
Exemple #11
0
def plot_regression(workspace, explan_var, depend_var, model, sample_num):
    arcpy.env.overwriteOutput = True
    arcpy.env.workspace = workspace
    workspace = arcpy.env.workspace
    arcpy.CheckOutExtension("Spatial")
    exp_var = explan_var
    dep_var = depend_var
    input_sample = sample_num
    arcpy.CreateRandomPoints_management(workspace, "samplepoints", "", exp_var,
                                        input_sample, "", "POINT")
    ExtractValuesToPoints("samplepoints", exp_var, "exp_points" "", "")
    ExtractValuesToPoints("samplepoints", dep_var, "dep_points" "", "")
    exp_array = arcpy.da.FeatureClassToNumPyArray("exp_points", "RASTERVALU")
    dep_array = arcpy.da.FeatureClassToNumPyArray("dep_points", "RASTERVALU")
    pyplot.scatter(exp_array, dep_array)
    pyplot.show()
    return
Exemple #12
0
def GenerateTransects(workspace, Map_Units, field_name, out_name):
    """
    Creates random transect locations
    :param workspace: the project's unique geodatabase
    :param Map_Units: the Map_Units_Dissolve feature class with number of
    transects identified in the attribute table
    :param field_name: the field in the attribute table with transect
    requirements defined
    :param out_name: a name to save the output as
    :return: the name of the output as a string
    """
    arcpy.AddMessage("Generating random transect locations within each map "
                     "unit")
    # Create random points in buffered map units
    transects = arcpy.CreateRandomPoints_management(workspace, out_name,
                                                    Map_Units,
                                                    "#", field_name, 25)
    return transects
Exemple #13
0
def plot_regression(workspace, explanatory, dependent, model_coeffs, samples):
    #print "starting plotting regression"
    arcpy.CheckOutExtension("Spatial")
    arcpy.env.workspace = workspace  #Get the workspace path
    arcpy.env.overwriteOutput = True  #setup overwrite protection status

    #convert input strings into rasters
    #print "converting input data to rasters"
    Exp_raster = arcpy.sa.Raster(explanatory)
    Dep_raster = arcpy.sa.Raster(dependent)
    outGDB = workspace
    outName = "RandomPoints"
    conFC = Exp_raster
    numField = samples
    #print "generating random points"
    RandomPoints = arcpy.CreateRandomPoints_management(outGDB, outName, "",
                                                       conFC, numField)
    Exp_rastrer_Extract2Points = arcpy.sa.ExtractValuesToPoints(
        RandomPoints, Exp_raster, "Exp_raster_FCPnts")
    Dep_rastrer_Extract2Points = arcpy.sa.ExtractValuesToPoints(
        RandomPoints, Dep_raster, "Dep_raster_FCPnts")
    arcpy.CheckInExtension("Spatial")

    Exp_numpy_array = arcpy.da.FeatureClassToNumPyArray(
        Exp_rastrer_Extract2Points, "RASTERVALU")
    Dep_numpy_array = arcpy.da.FeatureClassToNumPyArray(
        Dep_rastrer_Extract2Points, "RASTERVALU")
    X = Exp_numpy_array
    X_sorted = np.sort(X)
    #print X[0][0]
    #print X[-1][0]
    Y = Dep_numpy_array
    plt.scatter(X, Y)
    #source: https://www.kite.com/python/answers/how-to-plot-a-polynomial-fit-from-an-array-of-points-using-numpy-and-matplotlib-in-python
    x_predict = np.linspace(
        X_sorted[0][0], X_sorted[-1][0])  #/samples #not workiing frome kite
    #x_predict = np.array(range(35)) #/ this gives me a line 35 units length
    #val_range = np.amax(X,axis=1)
    #x_predict = np.array(range(val_range)) #/
    predict = np.poly1d(model_coeffs)
    y_predict = predict(x_predict)
    plt.plot(x_predict, y_predict, c='r')
    plt.show()
def generate_point(shape_file):
    merge = []
    for row in arcpy.da.SearchCursor(shape_file, ['FID', 'SampleSize']):
        sql = """{0} = {1}""".format('FID', row[0])
        out_name = 'FID' + str(row[0])
        constrain_feat = arcpy.Select_analysis(in_features=shape_file,
                                               out_feature_class=out_name,
                                               where_clause=sql)
        if CheckBox_pointfile == 'false':
            arcpy.AddMessage('Creating random points for features...')
            out_name += '_testpoints'
            arcpy.CreateRandomPoints_management(
                out_path=Workspace,
                out_name=out_name,
                constraining_feature_class=constrain_feat,
                number_of_points_or_field=row[1],
                minimum_allowed_distance='1 Meter',
                create_multipoint_output='POINT')
            merge.append(out_name + '.shp')
        else:
            #select points within the polygon
            arcpy.AddMessage('Selecting random points for features...')
            in_feat = arcpy.SelectLayerByLocation_management(
                in_layer=Point_file,
                overlap_type='INTERSECT',
                select_features=out_name + '.shp',
                selection_type='NEW_SELECTION')
            out_name += '_testpoints'
            #print(in_feat)
            arcpy.SubsetFeatures_ga(in_features=in_feat,
                                    out_training_feature_class=out_name,
                                    size_of_training_dataset=row[1],
                                    subset_size_units='ABSOLUTE_VALUE')
            merge.append(out_name + '.shp')
    #print(merge)
    arcpy.AddMessage('Merging files...')
    arcpy.Merge_management(merge, Save_file)

    arcpy.AddMessage('Points generated')
    def DemNoise(self, inDEM, outDEM, mean, stdev, mask, noise_order):
        arcpy.env.overwriteOutput = True
        arcpy.env.extent = inDEM
        # Process: Create Random Raster
        tempPath = tempfile.gettempdir()
        print(tempPath)
        rMetadata = arcpy.Raster(inDEM)
        # Process: Create Random Points
        arcpy.CreateRandomPoints_management(tempPath, "randomPoints.shp", None, mask, "1000", "10 Meters", "POINT", "0")
        arcpy.CreateRandomRaster_management(tempPath, "noise.tif", "NORMAL {} {}".format(mean, stdev), inDEM, rMetadata.meanCellHeight)
        # Process: Extract Values to Points
        arcpy.sa.ExtractValuesToPoints(os.path.join(tempPath, "randomPoints.shp"), os.path.join(tempPath, "noise.tif"), os.path.join(tempPath, "PointsInterpolation.shp"), "INTERPOLATE", "VALUE_ONLY")
        # Process: Trend
        noise = arcpy.sa.Trend(in_point_features=os.path.join(tempPath, "PointsInterpolation.shp"), z_field="RASTERVALU", cell_size=rMetadata.meanCellWidth, order=noise_order, regression_type="LINEAR", out_rms_file=None)
        # Process: Raster Calculator
        outRaster = (noise + arcpy.sa.Raster(inDEM)) * arcpy.Raster(mask)

        # arcpy.Clip_management(outRaster, in_template_dataset=mask, out_raster=outDEM, clipping_geometry="ClippingGeometry", maintain_clipping_extent="MAINTAIN_EXTENT")
        outRaster.save(outDEM)
        arcpy.Delete_management(os.path.join(tempPath, "PointsInterpolation.shp"))
        arcpy.Delete_management(os.path.join(tempPath, "randomPoints.shp"))
        # arcpy.Delete_management(noise)
        del noise
        return outDEM
Exemple #16
0
def randomPoints(interimName, boundary, numPoints, iterVal, pointType):
    """

    Function to add random points within a boundary and append to the burglaries shape file.
    Note the interim file must be separately deleted before it can be reused.
    This is because it may be required again in a later step.

    Args:
        interimName (str): The name of the interim shapefile to be created to hold the random points.
        boundary (str): The name of the boundary shapefile to create the points within.
        numPoints (int): The number of points to be created.
        iterVal (int): The number of the current iteration to be added to the attribute table for the points created.
        pointType (str): The type of point being created (INITIAL, SECONDARY, BACKGROUND) to be added to the attribute table for the points created.
        
    """

    global prevPoint

    # Creates the random points
    arcpy.CreateRandomPoints_management(path, interimName, boundary, "",
                                        numPoints)
    arcpy.AddField_management(interimName, "ITER", "SHORT")
    arcpy.AddField_management(interimName, "TYPE", "TEXT")

    # Updates the fields in the table
    with arcpy.da.UpdateCursor(interimName,
                               ["ITER", "TYPE", "SHAPE@XY"]) as cursor:
        for row in cursor:
            row[0] = iterVal
            row[1] = pointType
            if pointType == "INITIAL":
                prevPoint = (row[2][0], row[2][1])
            cursor.updateRow(row)

    # Adds the subsequent points into the burglaries.shp class that will contain all burglaries
    arcpy.Append_management(interimName, "burglaries.shp", "NO_TEST")
Exemple #17
0
    numGrass = max(10, numGrassFromRatio)
    numCover = totalPoints - numGrass
    print "%s 1948: Grass - %d (%d), Cover - %d" % (
        site, numGrass, numGrassFromRatio, numCover)

    ## select by class for grass only polygons
    cov48lyr = arcpy.MakeFeatureLayer_management(cov48analysisArea, "cov48lyr")
    cov48lyr = arcpy.SelectLayerByAttribute_management(
        "cov48lyr", "NEW_SELECTION", " Class_name = 'Grass' ")
    ## create a feature class for grass only
    cov48lyr_Grass = arcpy.CopyFeatures_management("cov48lyr",
                                                   "cov48lyr_Grass")
    ## generate random points within grass
    cov48_Grass_RandPoints = arcpy.CreateRandomPoints_management(
        out_path=env.workspace,
        out_name="cov48_Grass_RandPts.shp",
        constraining_feature_class=cov48lyr_Grass,
        number_of_points_or_field=numGrass,
        minimum_allowed_distance="5 meters")

    ## do the same for cover
    cov48lyr = arcpy.SelectLayerByAttribute_management(
        "cov48lyr", "NEW_SELECTION", " Class_name = 'Cover' ")
    cov48lyr_Cover = arcpy.CopyFeatures_management("cov48lyr",
                                                   "cov48lyr_Cover")
    cov48_Cover_RandPoints = arcpy.CreateRandomPoints_management(
        out_path=env.workspace,
        out_name="cov48_Cover_RandPts.shp",
        constraining_feature_class=cov48lyr_Cover,
        number_of_points_or_field=numCover,
        minimum_allowed_distance="5 meters")
def createSegments(contour_at_mean_high_water, contour_at_surge):
    # Start a timer  
    time1 = time.clock()
    arcpy.AddMessage("\nSegmentation of the coastline started at "+str(datetime.now()))

    # Specify a tolerance distance or minimum length of a seawall
    # Users are not yet given control of this
    th = 150

    # Create random points along the lines (mean high water and the surge of choice)
    # The numbers used are just my choice based on iterative observations
    random0 = arcpy.CreateRandomPoints_management(out_path= arcpy.env.workspace, \
                                                out_name= "random0", \
                                                constraining_feature_class= contour_at_mean_high_water, \
                                                number_of_points_or_field= long(1600), \
                                                  minimum_allowed_distance = "{0} Feet".format(th))

    random1 = arcpy.CreateRandomPoints_management(out_path= arcpy.env.workspace, \
                                                    out_name= "random1", \
                                                    constraining_feature_class= contour_at_surge, \
                                                    number_of_points_or_field= long(1600), \
                                                  minimum_allowed_distance = "{0} Feet".format(th))

    # Perform a proximity analysis with the NEAR tool 
    arcpy.Near_analysis(random0, random1)
    # Give each point a fixed unique ID
    # Create the ID field
    arcpy.AddField_management (random0, "UniqueID", "SHORT")
    arcpy.AddField_management (random1, "UniqueID", "SHORT")
    # Add Unique IDs 
    arcpy.CalculateField_management(random0, "UniqueID", "[FID]")
    arcpy.CalculateField_management(random1, "UniqueID", "[FID]")

    # Categorize/Separate each feature based on their near feature
    # Crate a table view of random0
    table0 = arcpy.MakeTableView_management(random0, "random0_table")
    #table1 = arcpy.MakeTableView_management(random1, "random1_table")
    # Sort the near feature for each points in random0 
    random0_sorted = arcpy.Sort_management(table0, "random0_sorte.dbf", [["NEAR_FID", "ASCENDING"]])


    # Create "long enough" lists for each of the field of interests: ID, NEAR_ID, and NEAR_DIST
    # (distance to closest point). I added [99999] here to extend the list length and avoid IndexError
    list_fid = [r.getValue("UniqueID") for r in arcpy.SearchCursor(random0_sorted, ["UniqueID"])] +[99999]
    list_nearid = [r.getValue("NEAR_FID") for r in arcpy.SearchCursor(random0_sorted, ["NEAR_FID"])]\
                  +[99999]
    list_neardist = [r.getValue("NEAR_DIST") for r in arcpy.SearchCursor(random0_sorted, ["NEAR_DIST"])]\
                    +[99999]

    del r

    # Only take points with near feature within the specified threshold. If it's too far, it's not better
    # than the others for a segment point
    list_fid_filtered = [i for i in list_neardist if i < th]
    # Then initiate a list o contain their Unique ID and Near ID
    first_unique_id = [] 
    first_near_id = []
    # Get NEAR_ID and Unique ID for each of these points
    for i in list_fid_filtered:
        first_unique_id.append(list_fid[list_neardist.index(i)])
        first_near_id.append(list_nearid[list_neardist.index(i)])

    # Only take the unique values in case there are duplicates. This shoudn't happen. Just to make sure.
    first_unique_id = [i for i in set(first_unique_id)]
    first_near_id = [i for i in set(first_near_id)]


    # Now create a new feature out of these points
    # Frist let's create a Feature Layer
    arcpy.MakeFeatureLayer_management("random0.shp", "random0_lyr")
    # Let's select all points and export them into a new feature
    random0_points = arcpy.SearchCursor(random0, ["UniqueID"])
    point0 = random0_points.next()

    for point0 in random0_points:
        for i in range(len(first_unique_id)):
            if point0.getValue("UniqueID") == first_unique_id[i]:
                selector0 = arcpy.SelectLayerByAttribute_management(\
                     "random0_lyr", "ADD_TO_SELECTION", '"UniqueID" = {0}'.format(first_unique_id[i]))

    del point0, random0_points
     
    new_random0 = arcpy.CopyFeatures_management(selector0, "new_random0")
    arcpy.Delete_management('random0_lyr')
    

    # Now for the new point feature, remove clusters of points around them and take only the ones
    # with minimum NEAR_DIST
    # First, get the geometry attributes of the new points
    arcpy.AddGeometryAttributes_management(new_random0, "POINT_X_Y_Z_M", "", "", "")

    # Create long enough list of the field of interest (same as the previous) 
    pointx = [r.getValue("POINT_X") for r in arcpy.SearchCursor(new_random0, ["POINT_X"])] +[99999]
    pointy = [r.getValue("POINT_Y") for r in arcpy.SearchCursor(new_random0, ["POINT_Y"])] +[99999]
    new_list_fid = [r.getValue("UniqueID") for r in arcpy.SearchCursor(new_random0, ["UniqueID"])]\
                   +[99999]
    new_list_nearid = [r.getValue("NEAR_FID") for r in arcpy.SearchCursor(new_random0, ["NEAR_FID"])]\
                      +[99999]
    new_list_neardist = [r.getValue("NEAR_DIST") for r in arcpy.SearchCursor(new_random0, ["NEAR_DIST"])]\
                        +[99999]

    del r


    # Initiate a list of every points that has already been compared to the near points
    garbage = []
    # Also initiate a list for the new Unique ID and NEAR ID
    new_unique_ID = []
    new_near_ID = []
    # Then, check if the points are right next to them. If so, add them to a temporary list
    # and find the one with closest near ID (or find minimum of their NEAR_DIST)
    for i in range(len(pointx)):
        if i+1 < len(pointx):
             
            # If not within the th range 
            if not calculateDistance(pointx[i], pointy[i], pointx[i+1], pointy[i+1]) < float(th)*1.5:
                # Skip if it's in garbage 
                if new_list_nearid[i] in garbage:
                    continue
                else:
                    new_unique_ID.append(new_list_fid[i])
                    new_near_ID.append(new_list_nearid[i])

            # If within the range        
            else:
                # Skip if it's in garbage 
                if new_list_nearid[i] in garbage:
                    continue
                else:
                    temp_ID = []
                    temp_NEAR = []
                    temp_DIST = []
                    while True:
                        temp_ID.append(new_list_fid[i])
                        temp_NEAR.append(new_list_nearid[i])
                        temp_DIST.append(new_list_neardist[i])
                        garbage.append(new_list_nearid[i])
                        i = i+1
                        # Stop when within the range again. And add the last point within the range
                        if not calculateDistance(pointx[i], pointy[i], pointx[i+1], pointy[i+1]) < 200:
                            temp_ID.append(new_list_fid[i])
                            temp_NEAR.append(new_list_nearid[i])
                            temp_DIST.append(new_list_neardist[i])
                            garbage.append(new_list_nearid[i])

                            # Calculate the minimum and get the Unique ID and Near ID  
                            minD = min(temp_DIST)
                            new_unique_ID.append(new_list_fid[new_list_neardist.index(minD)])
                            new_near_ID.append(new_list_nearid[new_list_neardist.index(minD)])

                            del temp_ID, temp_NEAR, temp_DIST
                            break


    # Now select these final points export them into new feature.
    # These are the end points for the segments to be created
    # First, make a layer out of all the random points
    arcpy.MakeFeatureLayer_management("random0.shp", "random0_lyr") 
    arcpy.MakeFeatureLayer_management("random1.shp", "random1_lyr") 

    # Then select and export the end points into feature0 and feature1
    # Based on new_unique_ID for random0
    random0_points = arcpy.SearchCursor(random0, ["UniqueID"])
    point0 = random0_points.next()
    for point0 in random0_points:
        for i in range(len(new_unique_ID)):
            if point0.getValue("UniqueID") == new_unique_ID[i]:
                selected0 = arcpy.SelectLayerByAttribute_management(\
                     "random0_lyr", "ADD_TO_SELECTION", '"UniqueID" = {0}'.format(new_unique_ID[i]))

    feature0 = arcpy.CopyFeatures_management(selected0, "feature0")

    # Based on new_near_ID for random1
    random1_points = arcpy.SearchCursor(random1, ["UniqueID"])
    point1 = random1_points.next()
    for point1 in random1_points:
        for k in range(len(new_near_ID)):
            if point1.getValue("UniqueID") == new_near_ID[k]:
                selected1 = arcpy.SelectLayerByAttribute_management(\
                     "random1_lyr", "ADD_TO_SELECTION", '"UniqueID" = {0}'.format(new_near_ID[k]))

    feature1 = arcpy.CopyFeatures_management(selected1, "feature1")

    del point0, point1, random0_points, random1_points 
    arcpy.Delete_management('random0_lyr')
    arcpy.Delete_management('random1_lyr')


    # Now for the actual create of the coastal segments
    # Which include creation of polygon and splitting the contours as the corresponding points
    # STEPS NECESSARY FOR POLYGON CREATION
    # Let's first add geometry attributes to these points
    arcpy.AddGeometryAttributes_management(feature0, "POINT_X_Y_Z_M", "", "", "")
    arcpy.AddGeometryAttributes_management(feature1, "POINT_X_Y_Z_M", "", "", "")

    # Let's create lines that connects points from feature0 to feature1 
    # Initiate a POLYLINE feature class for these lines
    arcpy.CreateFeatureclass_management (arcpy.env.workspace, "connector_lines.shp", "POLYLINE")

    # Then for each of the points in feature0, get the correspondingin feature1
    # And create a line for each of the two points
    with arcpy.da.SearchCursor(feature0, ["NEAR_FID", "POINT_X", "POINT_Y"]) as features0:
        for feat0 in features0:
                    
            with arcpy.da.SearchCursor(feature1, ["UniqueID", "POINT_X", "POINT_Y"]) as features1:
                x=0
                for feat1 in features1:
                    x = x+1
                    theseTwoPoints = []

                    if feat0[0] == feat1[0]:
                        # Get coordinates 
                        X0, Y0 = feat0[1], feat0[2]
                        X1, Y1 = feat1[1], feat1[2]
                        # Append coordinates
                        theseTwoPoints.append(arcpy.PointGeometry(arcpy.Point(X0, Y0)))
                        theseTwoPoints.append(arcpy.PointGeometry(arcpy.Point(X1, Y1)))
                        # Create line from the coordinates
                        subline = arcpy.PointsToLine_management(theseTwoPoints, "subline"+str(x)+".shp")
                        # Append all lines into one feature
                        lines = arcpy.Append_management(["subline"+str(x)+".shp"], "connector_lines.shp")
                        # Then delete subline as it's now unnecessary
                        arcpy.Delete_management(subline)

                        continue

    
    del feat0, feat1, features0, features1

    # Now that the connectors are created, let's split the segments 
    # Before splitting contours into segments, let's integrate the points and the segments
    # Just in case, there are misalignment
    arcpy.Integrate_management([contour_at_mean_high_water, feature0])
    arcpy.Integrate_management([contour_at_surge, feature1])
    segments0 = arcpy.SplitLineAtPoint_management(contour_at_mean_high_water, feature0, "segments0.shp", "10 Feet")
    segments1 = arcpy.SplitLineAtPoint_management(contour_at_surge, feature1, "segments1.shp", "10 Feet")
    # And let's give fixed unique ID for each segment
    arcpy.CalculateField_management(segments0, "Id", "[FID]")
    arcpy.CalculateField_management(segments1, "Id", "[FID]")

    # Now with the split segments and connector lines, let's make segment polygon of the segments
    almost_segment_polygons = arcpy.FeatureToPolygon_management([segments0, segments1, lines],\
                                                                "almost_segment_polygons.shp")
    # Adding unique ID to the segment polygons
    arcpy.CalculateField_management(almost_segment_polygons, "Id", "[FID]")
    
    # The Feature to Polygon process also created polygons that are surrounded by polygons
    # These are because these areas are surrounded by flooded areas at surge.
    # They are above the surge and technically safe. So, let's remove them.
    arcpy.MakeFeatureLayer_management(almost_segment_polygons, 'almost_segment_polygons_lyr')
    arcpy.MakeFeatureLayer_management(segments0, 'segments0_lyr')
    # Only the polygons within the mean_high_water segments are at risk
    arcpy.SelectLayerByLocation_management('almost_segment_polygons_lyr', 'INTERSECT', 'segments0_lyr')
    final_without_length = arcpy.CopyFeatures_management('almost_segment_polygons_lyr', 'final.shp')
    
    arcpy.Delete_management('segments0_lyr')
    arcpy.Delete_management('almost_segment_polygons_lyr')

    # For the new polygons, let's add the corresponding seawall length
    # Let's add Length field to both first
    arcpy.AddField_management(final_without_length, "Length", "SHORT")
    arcpy.AddField_management(segments0, "Length", "SHORT")
    # Calculation of the length
    with arcpy.da.UpdateCursor(segments0, ["SHAPE@LENGTH", "Length"]) as segments_0:  
         for segment_0 in segments_0:
              length = segment_0[0]
              segment_0[1] = length
              segments_0.updateRow(segment_0)
    del segment_0, segments_0

    # With spatial join, let's add these results to the segment polygons 
    final = spatialJoin(final_without_length, segments0, "Length", "Length", "max", "joined_segment.shp")

    # Delete the created but now unnecessary files 
    arcpy.Delete_management(random0)
    arcpy.Delete_management(random1)

    # Stop the timer 
    time2 = time.clock()

    arcpy.AddMessage("Seawall segments and regions successfully created. It took "\
                     +str(time2-time1)+" seconds")
    
    return final
citrus_only = arcpy.MakeRasterLayer_management(out_raster,
                                               merged_raster_name + "_O")
citrus_only1 = citrus_only.getOutput(0)
arcpy.mapping.AddLayer(df, citrus_only1, "AUTO_ARRANGE")

# Create 40 random polygons on citrus polygon layer

# dissolve IR_3
arcpy.Dissolve_management(citrus, path + r"\citrus_dissolved")

# create random points
outName = "random_points"
conFC = path + r"\citrus_dissolved.shp"
numPoints = 40

arcpy.CreateRandomPoints_management(path, outName, conFC, "", numPoints,
                                    "100 Meters", "", "")

# draw a circle around points using buffer tool
arcpy.Buffer_analysis(path + r"\random_points.shp", path + r"\random_circles",
                      "20 Meters")

# draw polygons around the circles
arcpy.FeatureEnvelopeToPolygon_management(path + r"\random_circles.shp",
                                          path + r"\random_polygons")

# add random polygons layer to map document

# create a new layer
randomPoly = arcpy.mapping.Layer(path + r"\random_polygons.shp")

# add layers to the map
Exemple #20
0
#Change date to current date
date = "2July2018"
import arcpy
from arcpy import env
#Set a workspace
workspace = r"C:\GIS_Work\Cphd_Locations\Locations.gdb"
env.workspace = workspace
env.overwriteOutput = True

#1)Generate Random Point in the feature of Overton Park
out_path = workspace
out_name = "randomPts_" + date
con_feat = "C:\GIS_Work\Overton_Park_Features.gdb\Forestboundary_PCS"
#Will automatically be generated as the same projection as Overton Park.
arcpy.CreateRandomPoints_management(out_path, out_name, con_feat, "", 30)

print "Random points were successfully generated"

#2) CHANGE PROJECTION TO WGS 1984 OR STEP 4 WON'T WORK
in_data = out_name
out_data = in_data + "_Project"
spat_ref = arcpy.SpatialReference(4326)
trans_meth = "NAD_1983_NSRS2007_To_WGS_1984_1"

print "Projection successfully changed"

arcpy.Project_management(in_data, out_data, spat_ref, trans_meth)
#3)Add XY coordinates to table.
in_feat = out_data
Exemple #21
0
def execute(self, parameters, messages):
    """
        Create random points tool 
            Create a set of random points constrained to a specific area, maintaining a minimum maximum distance to a 
                set of points and remaining in areas with full information 
        :param parameters: parameters object with all the parameters from the python-tool. It contains:
            output: Name of the file where the points will be stored 
            n_points: number of random points to be created 
            constrain_area: Original constraining area used as baseline for further constraints
            rasters: Information rasters that will be used to restrict to areas with full information 
            buffer_points: The random points will maintain a minimal/maximal distance to these points
            buffer_distance: Distance away buffer points
            min_distance: Minimal distance along created points 
            select_inside: Boolean to  create the points inside the area (True) or outside the area (False) 
        :param messages: messages object to print in the console, must implement AddMessage
         
        :return: None
    """

    global MESSAGES
    MESSAGES = messages

    # Print parameters for debugging purposes
    print_parameters(parameters)
    parameter_dic = {par.name: par for par in parameters}

    output = parameter_dic["output_points"].valueAsText.strip("'")
    n_points = parameter_dic["number_points"].value
    constrain_area = parameter_dic["constraining_area"].valueAsText.strip("'")
    rasters = parameter_dic["constraining_rasters"].valueAsText
    buffer_points = parameter_dic["buffer_points"].valueAsText
    buffer_distance = parameter_dic["buffer_distance"].valueAsText
    min_distance = parameter_dic["minimum_distance"].valueAsText
    select_inside = parameter_dic["select_inside"].value

    # Split the path of the output file in file and database, necesarry for
    out_ws, out_f = os.path.split(output)

    scratch_files = []
    try:
        # constrain area to avoid modifications to the original
        constrain_scratch = arcpy.CreateScratchName(
            "const_sct.shp", workspace=arcpy.env.scratchWorkspace)
        arcpy.CopyFeatures_management(
            arcpy.Describe(constrain_area).catalogPath, constrain_scratch)
        scratch_files.append(constrain_scratch)
        _verbose_print(
            "Scratch file created (constrain): {}".format(constrain_scratch))
        # Constrain to the points only if they exist, otherwise is not constrained
        if buffer_points is None or buffer_distance is None:
            _verbose_print("Exclude from points omitted")
            points_scratch = constrain_scratch
        else:
            points_scratch = _constrain_from_points(constrain_scratch,
                                                    buffer_points,
                                                    buffer_distance,
                                                    select_inside)
            scratch_files.append(points_scratch)
        # Constrain to the information raster only if is specified, otherwise do not constrain
        if rasters is None:
            _verbose_print("Exclude from rasters omitted")
            rasters_scratch = points_scratch
        else:
            rasters_scratch = _constrain_from_raster(points_scratch, rasters)
            scratch_files.append(rasters_scratch)
        # Dissolve the polygon into a single object to make the selection
        dissolve_scratch = arcpy.CreateScratchName(
            "diss_sct.shp", workspace=arcpy.env.scratchWorkspace)
        arcpy.Dissolve_management(in_features=rasters_scratch,
                                  out_feature_class=dissolve_scratch,
                                  multi_part="MULTI_PART")
        scratch_files.append(dissolve_scratch)

        # Select the random points
        # TODO: Sometimes, random points fall right in the border of the rasters and therefore they show null information, an erosion needs to be added to avoid this
        result = arcpy.CreateRandomPoints_management(
            out_ws,
            out_f,
            dissolve_scratch,
            number_of_points_or_field=n_points,
            minimum_allowed_distance=min_distance)
        arcpy.DefineProjection_management(
            result,
            arcpy.Describe(constrain_area).spatialReference)
        MESSAGES.AddMessage("Random points saved in {}".format(result))
    except:
        raise
    finally:
        # Delete intermediate files
        for s_file in scratch_files:
            arcpy.Delete_management(s_file)
            _verbose_print("Scratch file deleted: {}".format(s_file))

    return
# raster convert to polygon and simplify
arcpy.RasterToPolygon_conversion(r, shpfile, 'SIMPLIFY', 'VALUE')
arcpy.Dissolve_management(shpfile, shpfile_sv, 'GRIDCODE', '#', 'MULTI_PART',
                          'DISSOLVE_LINES')

# rm water (IGBP == 0)
with arcpy.da.UpdateCursor(shpfile_sv, "GRIDCODE") as cursor:
    for row in cursor:
        if row[0] == 0.0:
            # print row
            cursor.deleteRow()

arcpy.RefreshActiveView()

# sample representative points
arcpy.CreateRandomPoints_management(indir, file_st, shpfile_sv, '0 0 250 250',
                                    number, '4 Kilometers', 'POINT', '0')

# https://pro.arcgis.com/zh-cn/pro-app/help/data/geodatabases/overview/arcgis-field-data-types.htm
arcpy.AddField_management(file_st, "site", "SHORT", 5)
arcpy.AddField_management(file_st, "IGBPcode", "SHORT", 2)

# add fields site and IGBPcode (CID + 1)
codeblock = (r'rec = 0 \n' + 'def autoIncrement(): \n' + '    global rec \n' +
             '    pStart = 1 \n' + '    pInterval = 1 \n' +
             '    if (rec == 0): \n' + '        rec = pStart \n' +
             '    else: \n' + '        rec += pInterval \n' +
             '    return rec \n')
arcpy.CalculateField_management(file_st, 'site', 'autoIncrement()',
                                'PYTHON_9.3', codeblock)
arcpy.CalculateField_management(file_st, 'IGBPcode', '[CID]+1', 'VB', '#')
Exemple #23
0
    exportrastab(predznpop, out_table=os.path.join(predgdb, 'predznpop10000_tab'))
    exportrastab(predcupop, out_table=os.path.join(predgdb, 'predcupop10000_tab'))
    exportrastab(predznexcessdipop, out_table=os.path.join(predgdb, 'predcudiratio10000_tab'))
    exportrastab(predcuexcessdipop, out_table=os.path.join(predgdb, 'predzndiratio10000_tab'))


if not all(arcpy.Exists(os.path.join(predgdb, t)) for t in
           ['EJWApixelpop10000subhighway_tab', 'EJWApixeldipop10000subhighway_tab',
            'predznpop10000highway_tab', 'predcupop10000highway_tab',
            'predcudiratio10000highway_tab', 'predzndiratio10000highway_tab']):
    exportrastab(ExtractByMask(Raster(EJWApixelpopras_sub), Raster(hpms_ps_uhighbufras)),
                               out_table=os.path.join(predgdb, 'EJWApixelpop10000subhighway_tab'))
    exportrastab(ExtractByMask(Raster(EJWApixeldipopras_sub), Raster(hpms_ps_uhighbufras)),
                               out_table=os.path.join(predgdb, 'EJWApixeldipop10000subhighway_tab'))
    exportrastab(ExtractByMask(Raster(predznpop), Raster(hpms_ps_uhighbufras)),
                               out_table=os.path.join(predgdb, 'predznpop10000highway_tab'))
    exportrastab(ExtractByMask(Raster(predcupop), Raster(hpms_ps_uhighbufras)),
                               out_table=os.path.join(predgdb, 'predcupop10000highway_tab'))
    exportrastab(ExtractByMask(Raster(predznexcessdipop), Raster(hpms_ps_uhighbufras)),
                               out_table=os.path.join(predgdb, 'predcudiratio10000highway_tab'))
    exportrastab(ExtractByMask(Raster(predcuexcessdipop), Raster(hpms_ps_uhighbufras)),
                               out_table=os.path.join(predgdb, 'predzndiratio10000highway_tab'))

#Create random sample to extract values for EJWA, predz, predcu, and highway masks
if not arcpy.Exists(samplepoints):
    arcpy.CreateRandomPoints_management(predgdb, os.path.split(samplepoints)[1],
                                        constraining_extent=arcpy.Describe(EJWApixeldipopras_sub).extent,
                                        number_of_points_or_field=1000000,
                                        minimum_allowed_distance=5)
    ExtractMultiValuesToPoints(samplepoints, [EJWApixeldipopras_sub, predzn36land, predcu19land, hpms_ps_uhighbufras],
                               bilinear_interpolate_values='NONE')
for j in range(n_rsc - 2):
    n_pts_set[j] = int((n_pts - n_mkts) * (float(n_pts_set[j]) / randint_sum))
    n_pts_last = n_pts_last - n_pts_set[j]
n_pts_set[-1] = n_pts_last
print(n_pts_set)

##########################################################################
# generate points
##########################################################################
n_mkts_set = [n_mkts]
n_set = n_mkts_set + n_pts_set
print(n_set)
for i in range(len(n_set)):
    points_shp = random_pts + str(i)
    arcpy.CreateRandomPoints_management(path, points_shp, boundary, "",
                                        str(n_set[i]), "0 Feet", "POINT", "0")
    arcpy.CalculateField_management(path + points_shp + '.shp', "CID", str(i),
                                    "PYTHON_9.3")

##########################################################################
# Process: Create Thiessen Polygons based on layers of resouce points (except markets)
##########################################################################
start2 = time.time()
for i in range(1, n_rsc):
    points_shp = random_pts + str(i)
    voronoi_shp = path + resouce_vor + str(i) + ".shp"
    arcpy.CreateThiessenPolygons_analysis(path + points_shp + ".shp",
                                          voronoi_shp, "ONLY_FID")
    inFeatures.append(voronoi_shp)
end2 = time.time() - start2
print end2
    #Select random number of activities
    activities = np.random.randint(min_activities, max_activities)
    print "Number of activities:", activities

    #Adjust numbers for saving activity file
    if len(str(count)) == 1:
        number = "00" + str(count)
    elif len(str(count)) == 2:
        number = "0" + str(count)
    elif len(str(count)) == 3:
        number = str(count)

    #Select random coordinates for activities
    arcpy.CreateRandomPoints_management(save, "AC_" + str(number) + ".shp",
                                        study_area, "", activities,
                                        "100 Meters")

    #Access random coordinates file
    random_coord = os.path.join(save, "AC_" + str(number) + ".shp")

    #Add field for Name
    if not FieldExist(random_coord, "NAME"):
        arcpy.AddField_management(random_coord, "NAME", "TEXT")

    #Set counter activity names
    ac_number = 0

    #Calculate field values activity names
    with arcpy.da.UpdateCursor(random_coord, "NAME") as cursor:
        for row in cursor:
def SplitLinksAnalysis(inStreetfile, Outfile):
    """This function first removes all freeways and ramps, then splits all roadway
    segments to less than 530 feet to prepare the street link and nodes file."""
    global start_time
    global workspace

    # Remove Highways and Ramps
    try:
        whereclause1 = '''NOT "CLASS" = 'H' AND NOT "CLASS" = 'RAMP' '''  # Note Centerline file did not have HWY
        arcpy.AddMessage(
            "Create All Streets Network: Remove Highways and Ramps")
        arcpy.AddMessage("Where Clause: " + whereclause1)
        allstreetlyr = arcpy.MakeFeatureLayer_management(
            inStreetfile, "allstreetlyr", whereclause1)

        # Cleanup incase thier is any hanging files...
        if arcpy.Exists("SplitLine"):
            arcpy.Delete_management("SplitLine")

        # Split Lines until all roadway segments are less than 530 feet.
        count = 1
        i = 0
        RndptD = 250  # Used to split segments, halved every iteration to adjust random point splits.

        SptLn_start_time = time.time()
        arcpy.AddMessage("Start Split Line Process at: %s minutes ---" %
                         (round((time.time() - start_time) / 60, 1)))
        while count > 0:
            i += 1
            # Get Count of Features Greater than 530 feet
            arcpy.AddMessage(str(i) + " : Split segments >= 530 feet")
            whereclause2 = "shape_length >= 530"
            if not arcpy.Exists("SplitLine"):
                street2_lyr = arcpy.MakeFeatureLayer_management(
                    allstreetlyr, "street2_lyr", whereclause2)
                allstreetlyr2 = allstreetlyr
                RndPtsSplt = str(RndptD) + " Feet"

                Cntresult = arcpy.GetCount_management(street2_lyr)
                count = int(Cntresult.getOutput(0))
                arcpy.AddMessage("records to split:" + str(count))
                if count < 1:
                    break

                # Find Endpoints to remove slivers
                Ends1_lyr = arcpy.FeatureVerticesToPoints_management(
                    allstreetlyr, "Ends1_lyr", "BOTH_ENDS")
                buffer = "50 Feet"
                Int4_buf_lyr = arcpy.Buffer_analysis(Ends1_lyr, "Int4_buf_lyr",
                                                     buffer)

                # Split Lines at Random points based on "RndptsD", should splits 99% of points to required length.
                Rndptsft = arcpy.CreateRandomPoints_management(
                    workspace, "Rndptsft", street2_lyr, "", 10000, RndPtsSplt)
                Rndptsft2_lyr = arcpy.MakeFeatureLayer_management(
                    Rndptsft, "Rndptsft2_lyr")
                SplitptsLayer = arcpy.SelectLayerByLocation_management(
                    in_layer=Rndptsft2_lyr,
                    overlap_type="INTERSECT",
                    select_features=Int4_buf_lyr,
                    search_distance=".001 Feet",
                    selection_type="NEW_SELECTION",
                    invert_spatial_relationship="INVERT")

            else:
                street2_lyr = arcpy.MakeFeatureLayer_management(
                    SplitLine, "street2_lyr" + str(i), whereclause2)
                allstreetlyr2 = arcpy.CopyFeatures_management(
                    SplitLine, "in_memory/SplitLine" + str(i))

                arcpy.AddMessage("Check for any remaining long segments")

                Cntresult = arcpy.GetCount_management(street2_lyr)
                count = int(Cntresult.getOutput(0))
                arcpy.AddMessage("records to split:" + str(count))
                if count < 1:
                    break

                # Split Remaining Long Lines at Midpoints points to avoid slivers.
                SplitptsLayer = arcpy.FeatureVerticesToPoints_management(
                    street2_lyr, "MidptsSplt", "MID")

            # Split Line
            ArcpySptLn_start_time = time.time()
            arcpy.AddMessage(
                "      Start Splitting Lines Process at: %s minutes ---" %
                (round((time.time() - start_time) / 60, 1)))
            SplitLine = arcpy.SplitLineAtPoint_management(
                allstreetlyr2, SplitptsLayer, "SplitLine", "1 Feet")
            arcpy.AddMessage(
                "      Complete Splitting Lines Processing Time: %s minutes ---"
                % (round((time.time() - ArcpySptLn_start_time) / 60, 1)))
            arcpy.AddMessage(
                str(i) +
                " :Split Line Process Complete            %s minutes ---" %
                (round((time.time() - start_time) / 60, 1)))
            arcpy.AddMessage("Finish Process Iteration:  " + str(i))
            arcpy.AddMessage("------------------------------")

        arcpy.AddMessage("Complete Split Line Process at: %s minutes ---" %
                         (round((time.time() - start_time) / 60, 1)))

        # Copy Final Feature Layers
        arcpy.AddMessage("Creating Outputs")

        # arcpy.CopyFeatures_management(Int3_lyr,outStreet + "_Ints")
        arcpy.CopyFeatures_management(SplitLine, Outfile)
        arcpy.AddMessage("Total Process Time:         %s minutes ---" % (round(
            (time.time() - SptLn_start_time) / 60, 1)))
        arcpy.AddMessage("----------------------------------------------")

        # Cleanup
        arcpy.Delete_management(street2_lyr)
        arcpy.Delete_management(Int4_buf_lyr)
        arcpy.Delete_management(Rndptsft)
        arcpy.Delete_management(Rndptsft2_lyr)
        for x in range(i):
            try:
                ItsSplitLine = "in_memory/SplitLine" + str(x)
                arcpy.Delete_management(ItsSplitLine)
            except:
                pass

    except arcpy.ExecuteError:
        arcpy.AddMessage(arcpy.GetMessages(2))
    except Exception as e:
        arcpy.AddMessage(e.args[0])
        # If an error occurred, print line number and error message
        tb = sys.exc_info()[2]
        arcpy.AddMessage("An error occured on line %i" % tb.tb_lineno)
        arcpy.AddMessage(str(e))
        arcpy.AddWarning(
            "Check feature class has CLASS field and H and RAMP values")
        print("--- %s minutes ---" % (round(
            (time.time() - start_time) / 60, 1)))
Exemple #27
0
# Import system modules
import arcpy, os, sys
import arcpy.mapping
from arcpy import env

# Set workspace
arcpy.env.workspace = workspace
arcpy.env.overwriteOutput = True

# Random perturbation
arcpy.SpatialJoin_analysis(
    "areas", "o_points", "areas_new", "JOIN_ONE_TO_MANY", "KEEP_ALL",
    "RORI RORI true true false 4 Long 0 0 ,First,#,areas,RORI,-1,-1;origX origX true true false 4 Float 0 0 ,First,#,o_points,origX,-1,-1;origY origY true true false 4 Float 0 0 ,First,#,o_points,origY,-1,-1",
    "CONTAINS", "#", "#")
arcpy.CreateRandomPoints_management(workspace, "m_rand_points", "areas_new",
                                    "areas_new", "Join_Count", "", "POINT", "")
arcpy.JoinField_management("m_rand_points", "CID", "areas_new", "OBJECTID",
                           "origX;origY")
arcpy.DeleteField_management("m_rand_points", "CID")
arcpy.AddXY_management("m_rand_points")
arcpy.AddField_management("m_rand_points", "m_randomX", "FLOAT", "#", "#", "#",
                          "#", "NULLABLE", "NON_REQUIRED", "#")
arcpy.AddField_management("m_rand_points", "m_randomY", "FLOAT", "#", "#", "#",
                          "#", "NULLABLE", "NON_REQUIRED", "#")
arcpy.CalculateField_management("m_rand_points", "m_randomX", "[POINT_X]",
                                "VB", "#")
arcpy.CalculateField_management("m_rand_points", "m_randomY", "[POINT_Y]",
                                "VB", "#")
arcpy.DeleteField_management("m_rand_points", "POINT_X;POINT_Y")

# Finish Process
Exemple #28
0
#Name: RandomPointsRandomValues.py
#Purpose: create random points with random values

# Import system modules
import arcpy, os, random
from arcpy import env

# Create random points in the features of a constraining feature class
# Number of points for each feature determined by the value in the field specified
outGDB = "C:/data/county.gdb"
outName = "randpeople"
conFC = "C:/data/county.gdb/blocks"
numField = "POP2000"
arcpy.CreateRandomPoints_management(outGDB, outName, conFC, "", numField)

# set workspace
env.workspace = "C:/data/county.gdb"

# Create fields for random values
fieldInt = "fieldInt"
fieldFlt = "fieldFlt"
arcpy.AddField_management(outName, fieldInt, "LONG")  # add long integer field
arcpy.AddField_management(outName, fieldFlt, "FLOAT")  # add float field

# Calculate random values between 1-100 in the new fields
arcpy.CalculateField_management(outName, fieldInt, "random.randint(1,100)",
                                "PYTHON", "import random")
arcpy.CalculateField_management(outName, fieldFlt, "random.uniform(1,100)",
                                "PYTHON", "import random")

#Step 2
Exemple #29
0
#Step Two: Copy Features in SDE to new FC

print("\nCopying features class to: \n {0}...".format(FileGDB))
FCInput = "GIO.Building_A"
FCName = "Building_A_Copy"
FCSave = str(FileGDB) + "/" + str(FCName)
buildingFC = arcpy.CopyFeatures_management(FCInput, FCSave)

#Step Three: Generate Random Points for the DSM and DEM

print("\nGenerating Random Points on: \n {0} for the DSM".format(buildingFC))
RandomPointsDSM = "PointsDSM"
DistanceApart1 = "1 FEET"
DSMPoints = arcpy.CreateRandomPoints_management(FileGDB, RandomPointsDSM,
                                                buildingFC, "", 200,
                                                DistanceApart1, "MULTIPOINT")
print("\nRandom points generated for DSM...")

print("\nGenerating Random Points on: \n {0} for the DEM".format(buildingFC))
RandomPointsDEM = "PointsDEM"
DistanceApart2 = "1 FEET"
DEMPoints = arcpy.CreateRandomPoints_management(FileGDB, RandomPointsDEM,
                                                buildingFC, "", 200,
                                                DistanceApart2, "MULTIPOINT")
print("\nRandom points generated for DEM...")

#Step 4: Adding Surface Information to both Point Feature Classes

print("\nAdding Surface information to DSM points...")
PointsDSM = DSMPoints
Exemple #30
0
                          RemapRange([[-1000, 0.49, 0], [0.5, 1000, 1]]),
                          "NODATA")
ONESANDZEROS.save(os.path.join(env.workspace, naming + "Shaded_vs_Unshaded"))

#convert segmented polygons to layer
seg = arcpy.MakeFeatureLayer_management(segmented_AC, "seg.lyr")

cell_size = float(
    arcpy.GetRasterProperties_management(VEG_HEIGHT, 'CELLSIZEX').getOutput(0))

#Get Statistics for each segement USING ONES AND ZEROS TO GET TOTAL CELLS SHADED
zonalraster = ZonalStatistics(seg, "OBJECTID", ONESANDZEROS, "SUM", "DATA")
zonalraster.save(os.path.join(env.workspace, naming + "_zonalraster"))

###put centroids in segmented polys
centroids = arcpy.CreateRandomPoints_management(
    in_mem, naming + "centroids" + str(randint(0, 99)), seg, "#", 15)

#extract value to centroids
ExtractValuesToPoints(centroids, zonalraster, centroidswithvalues, "NONE",
                      "VALUE_ONLY")

#add necessary feilds
arcpy.AddField_management(seg, "PERCENT_SHADED", "FLOAT")
arcpy.AddField_management(seg, "SHADED_CELL_COUNT", "FLOAT")

#put point values into corresponding polygons
search_fields = ["OID@", "RASTERVALU", "CID"]
update_fields = ["OID@", "SHAPE@AREA", "PERCENT_SHADED", "SHADED_CELL_COUNT"]

modelist = []