Python arcpy.Point() Examples

The following are 24 code examples of arcpy.Point(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module arcpy , or try the search function .
Example #1
Source File: section_cpu.py    From HiSpatialCluster with Apache License 2.0 10 votes vote down vote up
def generate_cls_boundary(cls_input,cntr_id_field,boundary_output,cpu_core):
    arcpy.env.parallelProcessingFactor=cpu_core
    arcpy.SetProgressorLabel('Generating Delaunay Triangle...')
    arrays=arcpy.da.FeatureClassToNumPyArray(cls_input,['SHAPE@XY',cntr_id_field])
   
    cid_field_type=[f.type for f in arcpy.Describe(cls_input).fields if f.name==cntr_id_field][0]
    delaunay=Delaunay(arrays['SHAPE@XY']).simplices.copy()
    arcpy.CreateFeatureclass_management('in_memory','boundary_temp','POLYGON',spatial_reference=arcpy.Describe(cls_input).spatialReference)
    fc=r'in_memory\boundary_temp'
    arcpy.AddField_management(fc,cntr_id_field,cid_field_type)
    cursor = arcpy.da.InsertCursor(fc, [cntr_id_field,"SHAPE@"])
    arcpy.SetProgressor("step", "Copying Delaunay Triangle to Temp Layer...",0, delaunay.shape[0], 1)
    for tri in delaunay:
        arcpy.SetProgressorPosition()
        cid=arrays[cntr_id_field][tri[0]]
        if cid == arrays[cntr_id_field][tri[1]] and cid == arrays[cntr_id_field][tri[2]]:
            cursor.insertRow([cid,arcpy.Polygon(arcpy.Array([arcpy.Point(*arrays['SHAPE@XY'][i]) for i in tri]))])
    arcpy.SetProgressor('default','Merging Delaunay Triangle...')
    if '64 bit' in sys.version:
        arcpy.PairwiseDissolve_analysis(fc,boundary_output,cntr_id_field)
    else:
        arcpy.Dissolve_management(fc,boundary_output,cntr_id_field)
    arcpy.Delete_management(fc)
    
    return 
Example #2
Source File: prism.py    From ArcPy with GNU General Public License v2.0 6 votes vote down vote up
def save_to_esri_grid(self, out_grid, conversion_factor=None, proj=None):
        import arcpy
        arcpy.env.overwriteOutput = True
        arcpy.env.workspace = os.getcwd()
        arcpy.CheckOutExtension('Spatial')
        arcpy.env.outputCoordinateSystem = prismProj
        if proj is not None:
            arcpy.env.outputCoordinateSystem = proj
        df = np.ma.filled(self.data, self.nodatavalue)
        llx = self.originX
        lly = self.originY - (self.nrow * -1 * self.pixelHeight)
        point = arcpy.Point(llx, lly)
        r = arcpy.NumPyArrayToRaster(df, lower_left_corner=point, x_cell_size=self.pixelWidth,
                                     y_cell_size=-1*self.pixelHeight, value_to_nodata=self.nodatavalue)
        if conversion_factor is not None:
            r *= conversion_factor
        r.save(out_grid) 
Example #3
Source File: CreateCustomGrid.py    From ArcPy with GNU General Public License v2.0 6 votes vote down vote up
def horizontal(TLX, TRX, TLY, TRY, BLX, BRX, BLY, BRY, divisions):

    count = 1.0
    while count < divisions:
        a         = float(TLX*((divisions-count)/divisions) + BLX*(count/divisions)) - float(overflow)
        b         = float(TLY*((divisions-count)/divisions) + BLY*(count/divisions)) - float(overflow)

        c         = float(TRX*((divisions-count)/divisions) + BRX*(count/divisions)) + float(overflow)
        d         = float(TRY*((divisions-count)/divisions) + BRY*(count/divisions)) + float(overflow)

        L2R       = arcpy.Array([arcpy.Point(a, b), arcpy.Point(c, d)])
        L2R_line  = arcpy.Polyline(L2R)

        insert_cursor.insertRow((L2R_line,))

        count += 1.0 
Example #4
Source File: CreateCustomGrid.py    From ArcPy with GNU General Public License v2.0 6 votes vote down vote up
def vertical(TLX, TRX, TLY, TRY, BLX, BRX, BLY, BRY, divisions):

    count = 1.0
    while count < divisions:
        a         = float(TLX*((divisions-count)/divisions) + TRX*(count/divisions)) + float(overflow)
        b         = float(TLY*((divisions-count)/divisions) + TRY*(count/divisions)) + float(overflow)

        c         = float(BLX*((divisions-count)/divisions) + BRX*(count/divisions)) - float(overflow)
        d         = float(BLY*((divisions-count)/divisions) + BRY*(count/divisions)) - float(overflow)

        T2B       = arcpy.Array([arcpy.Point(a, b), arcpy.Point(c, d)])
        T2B_line  = arcpy.Polyline(T2B)

        insert_cursor.insertRow((T2B_line,))

        count += 1.0 
Example #5
Source File: geometry.py    From ArcREST with Apache License 2.0 6 votes vote down vote up
def asDictionary(self):
        """ returns the object as a python dictionary """
        value = self._dict
        if value is None:
            template = {
                "hasM" : self._hasM,
                "hasZ" : self._hasZ,
                "rings" : [],
                "spatialReference" : self.spatialReference
            }
            for part in self._rings:
                lpart = []
                for pt in part:
                    if isinstance(pt, list):
                        lpart.append(pt)
                    elif isinstance(pt, Point):
                        lpart.append(pt.asList)
                template['rings'].append(lpart)
                del lpart
            self._dict = template
        return self._dict
######################################################################## 
Example #6
Source File: arc_restapi.py    From restapi with GNU General Public License v2.0 5 votes vote down vote up
def formattedResults(self):
        """Returns a generator with formated results as tuple."""
        for res in self.results:
            pt = arcpy.PointGeometry(arcpy.Point(res.location[X],
                                                 res.location[Y]),
                                                 self.spatialReference)

            yield (pt,) + tuple(res.attributes[f.name] for f in self.fields) 
Example #7
Source File: arc_restapi.py    From restapi with GNU General Public License v2.0 5 votes vote down vote up
def asShape(self):
        """Returns JSON as arcpy.Geometry() object."""
        if self.geometryType != ESRI_ENVELOPE:
            return arcpy.AsShape(self.json, True)
        else:
            ar = arcpy.Array([
                arcpy.Point(self.json[XMIN], self.json[YMAX]),
                arcpy.Point(self.json[XMAX], self.json[YMAX]),
                arcpy.Point(self.json[XMAX], self.json[YMIN]),
                arcpy.Point(self.json[XMIN], self.json[YMIN])
            ])
            return arcpy.Polygon(ar, arcpy.SpatialReference(self.spatialReference)) 
Example #8
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def project_coordinates(xys, in_sr, out_sr, datum_transformation=None):
    """Project list of coordinate pairs (or triplets).
        xys -- list of coordinate pairs or triplets to project one by one
        in_sr -- input spatial reference, wkid, prj file, etc.
        out_sr -- output spatial reference, wkid, prj file, etc.
        datum_transformation=None -- datum transformation to use
            if in_sr and out_sr are defined on different datums,
            defining appropriate datum_transformation is necessary
            in order to obtain correct results!
            (hint: use arcpy.ListTransformations to list valid transformations)

    Example:
    >>> dtt = 'TM65_To_WGS_1984_2 + OSGB_1936_To_WGS_1984_NGA_7PAR'
    >>> coordinates = [(240600.0, 375800.0), (245900.0, 372200.0)]
    >>> project_coordinates(coordinates, 29902, 27700, dtt)
    """

    if not type(in_sr) is arcpy.SpatialReference:
        in_sr = arcpy.SpatialReference(in_sr)
    if not type(out_sr) is arcpy.SpatialReference:
        out_sr = arcpy.SpatialReference(out_sr)

    xyspr = []
    for xy in xys:
        pt = arcpy.Point(*xy)
        hasz = True if pt.Z is not None else False
        ptgeo = arcpy.PointGeometry(pt, in_sr)
        ptgeopr = ptgeo.projectAs(out_sr, datum_transformation)
        ptpr = ptgeopr.firstPoint
        if hasz:
            xypr = (ptpr.X, ptpr.Y, ptpr.Z)
        else:
            xypr = (ptpr.X, ptpr.Y)
        xyspr.append(xypr)

    return xyspr 
Example #9
Source File: CreateQSections.py    From ArcPy with GNU General Public License v2.0 5 votes vote down vote up
def q(TLX, TRX, TLY, TRY, BLX, BRX, BLY, BRY, divisions):

    count = 1.0
    while count < divisions:
        a         = float(TLX*((divisions-count)/divisions) + TRX*(count/divisions)) + float(overflow)
        b         = float(TLY*((divisions-count)/divisions) + TRY*(count/divisions)) + float(overflow)

        c         = float(BLX*((divisions-count)/divisions) + BRX*(count/divisions)) - float(overflow)
        d         = float(BLY*((divisions-count)/divisions) + BRY*(count/divisions)) - float(overflow)

        e         = float(TLX*((divisions-count)/divisions) + BLX*(count/divisions)) - float(overflow)
        f         = float(TLY*((divisions-count)/divisions) + BLY*(count/divisions)) - float(overflow)

        g         = float(TRX*((divisions-count)/divisions) + BRX*(count/divisions)) + float(overflow)
        h         = float(TRY*((divisions-count)/divisions) + BRY*(count/divisions)) + float(overflow)

        T2B       = arcpy.Array([arcpy.Point(a, b), arcpy.Point(c, d)])
        L2R       = arcpy.Array([arcpy.Point(e, f), arcpy.Point(g, h)])

        T2B_line  = arcpy.Polyline(T2B)
        L2R_line  = arcpy.Polyline(L2R)

        insert_cursor.insertRow((T2B_line,))
        insert_cursor.insertRow((L2R_line,))

        count += 1.0 
Example #10
Source File: CreateQQSections.py    From ArcPy with GNU General Public License v2.0 5 votes vote down vote up
def qq(TLX, TRX, TLY, TRY, BLX, BRX, BLY, BRY, divisions):

    count = 1.0
    while count < divisions:
        a         = float(TLX*((divisions-count)/divisions) + TRX*(count/divisions)) + float(overflow)
        b         = float(TLY*((divisions-count)/divisions) + TRY*(count/divisions)) + float(overflow)

        c         = float(BLX*((divisions-count)/divisions) + BRX*(count/divisions)) - float(overflow)
        d         = float(BLY*((divisions-count)/divisions) + BRY*(count/divisions)) - float(overflow)

        e         = float(TLX*((divisions-count)/divisions) + BLX*(count/divisions)) - float(overflow)
        f         = float(TLY*((divisions-count)/divisions) + BLY*(count/divisions)) - float(overflow)

        g         = float(TRX*((divisions-count)/divisions) + BRX*(count/divisions)) + float(overflow)
        h         = float(TRY*((divisions-count)/divisions) + BRY*(count/divisions)) + float(overflow)

        T2B       = arcpy.Array([arcpy.Point(a, b), arcpy.Point(c, d)])
        L2R       = arcpy.Array([arcpy.Point(e, f), arcpy.Point(g, h)])

        T2B_line  = arcpy.Polyline(T2B)
        L2R_line  = arcpy.Polyline(L2R)

        insert_cursor.insertRow((T2B_line,))
        insert_cursor.insertRow((L2R_line,))

        count += 1.0 
Example #11
Source File: datasetExtentToFeatures.py    From sample-gp-tools with Apache License 2.0 5 votes vote down vote up
def execute(in_datasets, out_fc):
    # use gcs as output sr since all extents will fit in it
    out_sr = arcpy.SpatialReference("WGS 1984")

    in_datasets = in_datasets.split(";")

    arcpy.CreateFeatureclass_management(os.path.dirname(out_fc),
                                        os.path.basename(out_fc),
                                        "POLYGON",
                                        spatial_reference=out_sr)

    arcpy.AddField_management(out_fc, "dataset", "TEXT", 400)

    # add each dataset's extent & the dataset's name to the output
    with arcpy.da.InsertCursor(out_fc, ("SHAPE@", "dataset")) as cur:

        for i in in_datasets:
            d = arcpy.Describe(i)
            ex = d.Extent
            pts = arcpy.Array([arcpy.Point(ex.XMin, ex.YMin),
                              arcpy.Point(ex.XMin, ex.YMax),
                              arcpy.Point(ex.XMax, ex.YMax),
                              arcpy.Point(ex.XMax, ex.YMin),
                              arcpy.Point(ex.XMin, ex.YMin),])

            geom = arcpy.Polygon(pts,  d.SpatialReference)

            if d.SpatialReference != out_sr:
                geom = geom.projectAs(out_sr)
            cur.insertRow([geom, d.CatalogPath]) 
Example #12
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def asArcPyObject(self):
        """ returns the Envelope as an ESRI arcpy.Polygon object """
        env = self.asDictionary
        ring = [[
            Point(env['xmin'], env['ymin'], self._wkid),
            Point(env['xmax'], env['ymin'], self._wkid),
            Point(env['xmax'], env['ymax'], self._wkid),
            Point(env['xmin'], env['ymax'], self._wkid)
            ]]
        return Polygon(rings=ring,
                       wkid=self._wkid,
                       wkt=self._wkid,
                       hasZ=False,
                       hasM=False).asArcPyObject 
Example #13
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def __geomToPointList(self, geom):
        """ converts a geometry object to a common.Geometry object """
        sr = geom.spatialReference
        wkid = None
        wkt = None
        if sr is None:
            if self._wkid is None and self._wkt is not None:
                wkt = self._wkt
            else:
                wkid = self._wkid
        else:
            wkid = sr.factoryCode
        g = json.loads(geom.JSON)
        top = []
        for gring in g['rings']:
            ring = []
            for g in gring:
                ring.append(Point(coord=g, wkid=wkid, wkt=wkt, z=None, m=None))
            top.append(ring)
        return top
        #if isinstance(geom, arcpy.Polygon):
            #feature_geom = []
            #fPart = []
            #for part in geom:
                #fPart = []
                #for pnt in part:
                    #if geom.spatialReference is None:
                        #wkid = self._wkid
                    #else:
                        #wkid = geom.spatialReference.factoryCode
                    #fPart.append(Point(coord=[pnt.X, pnt.Y],
                          #wkid=wkid,
                          #z=pnt.Z, m=pnt.M))
                #feature_geom.append(fPart)
            #return feature_geom
    #---------------------------------------------------------------------- 
Example #14
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def asArcPyObject(self):
        """ returns the Point as an ESRI arcpy.MultiPoint object """
        if arcpyFound == False:
            raise Exception("ArcPy is required to use this function")
        return arcpy.AsShape(self.asDictionary, True)
    #---------------------------------------------------------------------- 
Example #15
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def __geomToPointList(self, geom):
        """ converts a geometry object to a common.Geometry object """
        if arcpyFound and isinstance(geom, arcpy.Multipoint):
            feature_geom = []
            fPart = []
            for part in geom:
                fPart = []
                for pnt in part:
                    fPart.append(Point(coord=[pnt.X, pnt.Y],
                          wkid=geom.spatialReference.factoryCode,
                          z=pnt.Z, m=pnt.M))
                feature_geom.append(fPart)
            return feature_geom
    #---------------------------------------------------------------------- 
Example #16
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def asList(self):
        """ returns a Point value as a list of [x,y,<z>,<m>] """
        base = [self._x, self._y]
        if not self._z is None:
            base.append(self._z)
        elif not self._m is None:
            base.append(self._m)
        return base
    #---------------------------------------------------------------------- 
Example #17
Source File: geometry.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def asArcPyObject(self):
        """ returns the Point as an ESRI arcpy.Point object """
        if arcpyFound == False:
            raise Exception("ArcPy is required to use this function")
        return arcpy.AsShape(self.asDictionary, True)
    #---------------------------------------------------------------------- 
Example #18
Source File: filters.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def geometry(self, geometry):
        """ sets the geometry value """
     
        if isinstance(geometry, AbstractGeometry):
            self._geomObject = geometry
            self._geomType = geometry.type
        elif arcpyFound :
            wkid = None
            wkt = None
            if (hasattr(geometry, 'spatialReference') and \
                       geometry.spatialReference is not None):
                if (hasattr(geometry.spatialReference, 'factoryCode') and \
                            geometry.spatialReference.factoryCode is not None):
                    wkid = geometry.spatialReference.factoryCode
                else:
                    wkt = geometry.spatialReference.exportToString()
                    
            if isinstance(geometry, arcpy.Polygon):
                
                self._geomObject = Polygon(geometry, wkid=wkid, wkt=wkt)
                self._geomType = "esriGeometryPolygon"
            elif isinstance(geometry, arcpy.Point):
                self._geomObject = Point(geometry, wkid=wkid, wkt=wkt)
                self._geomType = "esriGeometryPoint"
            elif isinstance(geometry, arcpy.Polyline):
                self._geomObject = Polyline(geometry, wkid=wkid, wkt=wkt)
                self._geomType = "esriGeometryPolyline"
            elif isinstance(geometry, arcpy.Multipoint):
                self._geomObject = MultiPoint(geometry, wkid=wkid, wkt=wkt)
                self._geomType = "esriGeometryMultipoint"
            else:
                raise AttributeError("geometry must be a common.Geometry or arcpy.Geometry type.")
        else:
            raise AttributeError("geometry must be a common.Geometry or arcpy.Geometry type.")        
    #---------------------------------------------------------------------- 
Example #19
Source File: Step1_MakeShapesFC.py    From public-transit-tools with Apache License 2.0 5 votes vote down vote up
def get_stop_geom():
    '''Populate a dictionary of {stop_id: stop point geometry object}'''
    
    global stopgeom_dict
    stopgeom_dict = {}
    
    for stop in stoplatlon_dict:
        lat = stoplatlon_dict[stop][0]
        lon = stoplatlon_dict[stop][1]
        point = arcpy.Point(lon, lat)
        ptGeometry = arcpy.PointGeometry(point, WGSCoords)
        stopgeom_dict[stop] = ptGeometry 
Example #20
Source File: Step2_GenerateNewGTFStxtFiles.py    From public-transit-tools with Apache License 2.0 5 votes vote down vote up
def WriteShapesFile(f):
            wr = csv.writer(f)
            # Write the headers
            if not update_existing:
                wr.writerow(["shape_id", "shape_pt_lat", "shape_pt_lon", "shape_pt_sequence", "shape_dist_traveled"])

            # Use a Search Cursor and explode to points to get vertex info
            shape_pt_seq = 1
            shape_dist_traveled = 0
            current_shape_id = None
            previous_point = None
            for row in arcpy.da.SearchCursor(inShapes, ["shape_id", "SHAPE@Y", "SHAPE@X"], explode_to_points=True):
                shape_id, shape_pt_lat, shape_pt_lon = row
                current_point = arcpy.Point(shape_pt_lon, shape_pt_lat)
                if shape_id != current_shape_id:
                    # Starting a new shape
                    current_shape_id = shape_id
                    shape_pt_seq = 1
                    shape_dist_traveled = 0
                else:
                    # Create a line segment between the previous vertex and this one so we can calculate geodesic length
                    line_segment = arcpy.Polyline(arcpy.Array([previous_point, current_point]), WGSCoords)
                    shape_dist_traveled += line_segment.getLength("GEODESIC", units.upper())
 
                # Write row to shapes.txt file
                if not update_existing:
                    row_to_add = [shape_id, shape_pt_lat, shape_pt_lon, shape_pt_seq, shape_dist_traveled]
                else:
                    # Do a little jiggering because the user's existing shapes.txt might contain extra fields and might not be in the same order
                    row_to_add = ["" for col in shapes_columns]
                    row_to_add[shape_id_idx] = shape_id
                    row_to_add[shape_pt_lat_idx] = shape_pt_lat
                    row_to_add[shape_pt_lon_idx] = shape_pt_lon
                    row_to_add[shape_pt_sequence_idx] = shape_pt_seq
                    row_to_add[shape_dist_traveled_idx] = shape_dist_traveled
                wr.writerow(row_to_add)
                shape_pt_seq += 1
                previous_point = current_point 
Example #21
Source File: CreateWeightTableFromECMWFRunoff.py    From python-toolbox-for-rapid with Apache License 2.0 5 votes vote down vote up
def createPolygon(self, lat, lon, extent, out_polygons, scratchWorkspace):
        """Create a Thiessen polygon feature class from numpy.ndarray lat and lon
           Each polygon represents the area described by the center point
        """
        buffer = 2 * max(abs(lat[0]-lat[1]),abs(lon[0] - lon[1]))
        # Extract the lat and lon within buffered extent (buffer with 2* interval degree)
        lat0 = lat[(lat >= (extent.YMin - buffer)) & (lat <= (extent.YMax + buffer))]
        lon0 = lon[(lon >= (extent.XMin - buffer)) & (lon <= (extent.XMax + buffer))]
        # Spatial reference: GCS_WGS_1984
        sr = arcpy.SpatialReference(4326)

        # Create a list of geographic coordinate pairs
        pointGeometryList = []
        for i in range(len(lon0)):
            for j in range(len(lat0)):
                point = arcpy.Point()
                point.X = float(lon0[i])
                point.Y = float(lat0[j])
                pointGeometry = arcpy.PointGeometry(point, sr)
                pointGeometryList.append(pointGeometry)

        # Create a point feature class with longitude in Point_X, latitude in Point_Y
        out_points = os.path.join(scratchWorkspace, 'points_subset')
        result2 = arcpy.CopyFeatures_management(pointGeometryList, out_points)
        out_points = result2.getOutput(0)
        arcpy.AddGeometryAttributes_management(out_points, 'POINT_X_Y_Z_M')

        # Create Thiessen polygon based on the point feature
        result3 = arcpy.CreateThiessenPolygons_analysis(out_points, out_polygons, 'ALL')
        out_polygons = result3.getOutput(0)

        return out_points, out_polygons 
Example #22
Source File: CreateWeightTableFromECMWFRunoff.py    From python-toolbox-for-rapid with Apache License 2.0 4 votes vote down vote up
def getParameterInfo(self):
        """Define parameter definitions"""
        param0 = arcpy.Parameter(name = "in_ECMWF_runoff_file",
                                 displayName = "Input ECMWF Runoff File",
                                 direction = "Input",
                                 parameterType = "Required",
                                 datatype = "DEFile")

        param1 = arcpy.Parameter(name = "in_network_connectivity_file",
                                 displayName = "Input Network Connecitivity File",
                                 direction = "Input",
                                 parameterType = "Required",
                                 datatype = "DEFile")

        param2 = arcpy.Parameter(name = "in_catchment_features",
                                 displayName = "Input Catchment Features",
                                 direction = "Input",
                                 parameterType = "Required",
                                 datatype = "GPFeatureLayer")

        param2.filter.list = ['Polygon']


        param3 = arcpy.Parameter(name = "stream_ID",
                                 displayName = "Stream ID",
                                 direction = "Input",
                                 parameterType = "Required",
                                 datatype = "Field"
                                 )
        param3.parameterDependencies = ["in_catchment_features"]
        param3.filter.list = ['Short', 'Long']


        param4 = arcpy.Parameter(name="out_weight_table",
                                 displayName="Output Weight Table",
                                 direction="Output",
                                 parameterType="Required",
                                 datatype="DEFile")

        param5 = arcpy.Parameter(name = "out_cg_polygon_feature_class",
                                 displayName = "Output Computational Grid Polygon Feature Class",
                                 direction = "Output",
                                 parameterType = "Optional",
                                 datatype = "DEFeatureClass")

        param6 = arcpy.Parameter(name = "out_cg_point_feature_class",
                                 displayName = "Output Computational Grid Point Feature Class",
                                 direction = "Output",
                                 parameterType = "Optional",
                                 datatype = "DEFeatureClass")


        params = [param0, param1, param2, param3, param4, param5, param6]

        return params 
Example #23
Source File: CreateWeightTableFromWRFGeogrid.py    From python-toolbox-for-rapid with Apache License 2.0 4 votes vote down vote up
def getParameterInfo(self):
        """Define parameter definitions"""
        param0 = arcpy.Parameter(name = "in_WRF_geogrid_file",
                                 displayName = "Input WRF Geogrid File",
                                 direction = "Input",
                                 parameterType = "Required",
                                 datatype = "DEFile")

        param1 = arcpy.Parameter(name = "in_network_connectivity_file",
                                 displayName = "Input Network Connecitivity File",
                                 direction = "Input",
                                 parameterType = "Required",
                                 datatype = "DEFile")

        param2 = arcpy.Parameter(name = "in_catchment_features",
                                 displayName = "Input Catchment Features",
                                 direction = "Input",
                                 parameterType = "Required",
                                 datatype = "GPFeatureLayer")
        param2.filter.list = ['Polygon']

        param3 = arcpy.Parameter(name = "stream_ID",
                                 displayName = "Stream ID",
                                 direction = "Input",
                                 parameterType = "Required",
                                 datatype = "Field"
                                 )
        param3.parameterDependencies = ["in_catchment_features"]
        param3.filter.list = ['Short', 'Long']

        param4 = arcpy.Parameter(name = "out_weight_table",
                                 displayName = "Output Weight Table",
                                 direction = "Output",
                                 parameterType = "Required",
                                 datatype = "DEFile")

        param5 = arcpy.Parameter(name = "out_cg_polygon_feature_class",
                                 displayName = "Output Computational Grid Polygon Feature Class",
                                 direction = "Output",
                                 parameterType = "Optional",
                                 datatype = "DEFeatureClass")

        param6 = arcpy.Parameter(name = "out_cg_point_feature_class",
                                 displayName = "Output Computational Grid Point Feature Class",
                                 direction = "Output",
                                 parameterType = "Optional",
                                 datatype = "DEFeatureClass")

        params = [param0, param1, param2, param3, param4, param5, param6]

        return params 
Example #24
Source File: section_cpu.py    From HiSpatialCluster with Apache License 2.0 4 votes vote down vote up
def calc_nrst_dist_cpu(gids,xs,ys,densities,cpu_core):
    n=xs.shape[0]
    
    def calc_nrst_dist_np(gidxys,result_q,gids,xs,ys,densities):
        while True:
            try:
                i=gidxys.get_nowait()
                distpow2=(xs-xs[i])**2+(ys-ys[i])**2
                distpow2[densities<=densities[i]]=1e100
                pg=distpow2.argsort()[0]
                if distpow2[pg]>1e99:
                    result_q.put((i,1e10,-1))
                else:
                    result_q.put((i,math.sqrt(distpow2[pg]),gids[pg]))
            except queue.Empty:
                break;
                
    n=xs.shape[0]
    gidxys=queue.Queue()
    result_q=queue.Queue()
    for i in range(n):
        gidxys.put(i)
    
    arcpy.SetProgressor("step", "Find Point with Higher Density on CPU...",0, n, 1)
    
    ts=[]
    for i in range(cpu_core):
        t=Process(target=calc_nrst_dist_np,args=(gidxys,result_q,gids,xs,ys,densities))
        t.start()
        ts.append(t)
    for t in ts:
        while t.is_alive():
            arcpy.SetProgressorPosition(n-gidxys.qsize())
            time.sleep(0.05)
        
    result_a=[]
    while result_q.empty()==False:
        result_a.append(result_q.get())
    result_a.sort()
    result_nd=[]
    result_pg=[]
    for v in result_a:
        result_nd.append(v[1])
        result_pg.append(v[2])
    return (np.array(result_nd),np.array(result_pg))