Пример #1
0
def complex_fc_to_fset(fc_or_flyr, temp_dir = r'P:/temp'):
    '''converts a featureclass or feature layer to an AGOL-friendly FeatureSet object.
    This is good for complex geometry, as SDF-from_featureclass simplifies geometry.
    requires arcpy.
    
    inputs:
        fc_or_flyr:  feature class or feature layer.  Can be a selection.
        temp_dir:    local folder for saving a temporary json file
    '''
    from os import makedirs
    from os.path import join, exists
    from json import load
    from arcpy import FeaturesToJSON_conversion, Delete_management
    from arcgis.features import FeatureSet
    
    if not exists(temp_dir):
        makedirs(temp_dir)
    temp_json_file = FeaturesToJSON_conversion(fc_or_flyr,join(temp_dir,'temp_features.json'))[0]
    with open(temp_json_file) as jsonfile:
        data = load(jsonfile)
    Delete_management(temp_json_file)
    return FeatureSet.from_dict(data)
def create_buffers(
    input_layer,
    distance = 1,
    distance_unit = "Miles",
    field = None,
    method = """Planar""",
    dissolve_option = """None""",
    dissolve_fields = None,
    summary_fields = None,
    multipart = False,
    output_name = None,
    context = None,
    gis = None):
    """

    A buffer is an area that covers a given distance from a point, line, or polygon feature.

    Buffers are typically used to create areas that can be further analyzed using other tools. For example, if the question is What buildings are within 1 mile of the school?, the answer can be found by creating a 1-mile buffer around the school and overlaying the buffer with the layer containing building footprints. The end result is a layer of those buildings within 1 mile of the school.

    For example

    * Using linear river features, buffer each river by 50 times the width of the river to determine a proposed riparian boundary.

    * Given areas representing countries, buffer each country by 200 nautical miles to determine the maritime boundary.



Parameters:

   input_layer: Input Features (_FeatureSet). Required parameter.

   distance: Buffer Distance (float). Optional parameter.

   distance_unit: Buffer Distance Unit (str). Optional parameter.
      Choice list:['Feet', 'Yards', 'Miles', 'Meters', 'Kilometers', 'NauticalMiles']

   field: Buffer Distance Field (str). Optional parameter.

   method: Method (str). Required parameter.
      Choice list:['Geodesic', 'Planar']

   dissolve_option: Dissolve Option (str). Optional parameter.
      Choice list:['All', 'List', 'None']

   dissolve_fields: Dissolve Fields (str). Optional parameter.

   summary_fields: Summary Statistics (str). Optional parameter.

   multipart: Allow Multipart Geometries (bool). Optional parameter.

   output_name: Output Features Name (str). Required parameter.


   gis: Optional, the GIS on which this tool runs. If not specified, the active GIS is used.


Returns:
   output - Output Features as a feature layer collection item


    """
    kwargs = locals()


    gis = _arcgis.env.active_gis if gis is None else gis
    url = gis.properties.helperServices.geoanalytics.url

    if isinstance(input_layer, FeatureCollection) and \
       'layers' in input_layer.properties and \
       len(input_layer.properties.layers) > 0:
        input_layer = _FeatureSet.from_dict(
            featureset_dict=input_layer._lazy_properties.layers[0].featureSet)

    params = {}
    for key, value in kwargs.items():
        if value is not None:
            params[key] = value

    if output_name is None:
        output_service_name = 'Create Buffers Analysis_' + _id_generator()
        output_name = output_service_name.replace(' ', '_')
    else:
        output_service_name = output_name.replace(' ', '_')

    output_service = _create_output_service(gis, output_name, output_service_name, 'Create Buffers')

    params['output_name'] = _json.dumps({
        "serviceProperties": {"name" : output_name, "serviceUrl" : output_service.url},
        "itemProperties": {"itemId" : output_service.itemid}})

    _set_context(params)
    param_db = {
        "input_layer": (_FeatureSet, "inputLayer"),
        "distance": (float, "distance"),
        "distance_unit": (str, "distanceUnit"),
        "field": (str, "field"),
        "method": (str, "method"),
        "dissolve_option": (str, "dissolveOption"),
        "dissolve_fields": (str, "dissolveFields"),
        "summary_fields": (str, "summaryFields"),
        "multipart": (bool, "multipart"),
        "output_name": (str, "outputName"),
        "context": (str, "context"),
        "output": (_FeatureSet, "Output Features"),
    }
    return_values = [
        {"name": "output", "display_name": "Output Features", "type": _FeatureSet},
    ]

    try:
        _execute_gp_tool(gis, "CreateBuffers", params, param_db, return_values, _use_async, url, True)
        return output_service
    except:
        output_service.delete()
        raise
Пример #3
0
 def to_featureset(self):
     return FeatureSet.from_dict(self.__feature_set__())
Пример #4
0
def to_featureset(df):
    """converts a pd.DataFrame to a FeatureSet Object"""
    if hasattr(df, 'spatial'):
        fs = df.spatial.__feature_set__
        return FeatureSet.from_dict(fs)
    return None
Пример #5
0
def _get_nearest_gis(origin_dataframe: pd.DataFrame,
                     destination_dataframe: pd.DataFrame,
                     source: [str, Country, GIS],
                     origin_id_column: str = 'LOCNUM',
                     destination_id_column: str = 'LOCNUM',
                     destination_count: int = 4) -> pd.DataFrame:
    """Web GIS implementation of get nearest solution."""

    # TODO: backport these to be optional input parameters
    return_geometry = True
    output_spatial_reference = 4326

    # build the spatial reference dict
    out_sr = {'wkid': output_spatial_reference}

    # if a country instance, get the GIS object from it
    if isinstance(source, Country):
        assert isinstance(Country.source, GIS), 'The source Country must be reference an ArcGIS Web GIS object ' \
                                                'instance to solve using a GIS.'
        source = Country.source

    # run a couple of checks to make sure we do not encounter strange errors later
    assert isinstance(source, GIS), 'The source must be a GIS object instance.'
    assert utils.has_networkanalysis_gis(source.users.me), 'You must have the correct permissions in the Web GIS to ' \
                                                           'perform routing solves. It appears you do not.'

    # prep the datasets for routing
    origin_fs = _prep_sdf_for_nearest(
        origin_dataframe, origin_id_column).spatial.to_featureset().to_dict()
    dest_fs = _prep_sdf_for_nearest(
        destination_dataframe,
        destination_id_column).spatial.to_featureset().to_dict()

    # create the url for doing routing
    route_url = source.properties.helperServices.route.url
    solve_url = '/'.join(
        route_url.split('/')[:-1]) + '/ClosestFacility/solveClosestFacility'

    # construct the payload for the routing solve
    params = {
        'incidents': origin_fs,
        'facilities': dest_fs,
        'returnCFRoutes': True,
        'f': 'json',
        'defaultTargetFacilityCount': destination_count,
        'outputLines': 'esriNAOutputLineTrueShape'
        if return_geometry else 'esriNAOutputLineNone',
        'outSR': out_sr
    }

    # call the server for the solve
    res = source._con.post(solve_url, params)

    # unpack the results from the response
    route_df = FeatureSet.from_dict(res['routes']).sdf

    # clean up any empty columns
    notna_srs = route_df.isna().all()
    drop_cols = notna_srs[notna_srs].index.values
    route_df.drop(columns=drop_cols, inplace=True)

    # populate the origin and destination id columns so the output will be as expected
    id_srs = route_df['Name'].str.split(' - ')
    route_df['IncidentID'] = id_srs.apply(lambda val: val[0])
    route_df['FacilityID'] = id_srs.apply(lambda val: val[1])

    return route_df
def create_buffers(input_layer,
                   distance=1,
                   distance_unit="Miles",
                   field=None,
                   method="Planar",
                   dissolve_option="None",
                   dissolve_fields=None,
                   summary_fields=None,
                   multipart=False,
                   output_name=None,
                   context=None,
                   gis=None,
                   future=False):
    """

    .. image:: _static/images/create_buffers_geo/create_buffers_geo.png

    Buffers are typically used to create areas that can be further analyzed
    using other tools such as ``aggregate_points``. For example, ask the question,
    "What buildings are within one mile of the school?" The answer can be found
    by creating a one-mile buffer around the school and overlaying the buffer
    with the layer containing building footprints. The end result is a layer
    of those buildings within one mile of the school.

    ================================================    =========================================================
    **Parameter**                                       **Description**
    ------------------------------------------------    ---------------------------------------------------------
    input_layer                                         Required layer. The point, line, or polygon features to be buffered.
                                                        See :ref:`Feature Input<gaxFeatureInput>`.
    ------------------------------------------------    ---------------------------------------------------------
    distance (Required if field is not provided)        Optional float. A float value used to buffer the input features.
                                                        You must supply a value for either the distance or field parameter.
                                                        You can only enter a single distance value. The units of the
                                                        distance value are supplied by the ``distance_unit`` parameter.

                                                        The default value is 1.
    ------------------------------------------------    ---------------------------------------------------------
    distance_unit (Required if distance is used)        Optional string. The linear unit to be used with the value specified in distance.

                                                        Choice list:['Feet', 'Yards', 'Miles', 'Meters', 'Kilometers', 'NauticalMiles']

                                                        The default value is "Miles"
    ------------------------------------------------    ---------------------------------------------------------
    field (Required if distance not provided)           Optional string. A field on the ``input_layer`` containing a buffer distance or a field expression.
                                                        A buffer expression must begin with an equal sign (=). To learn more about buffer expressions
                                                        see: `Buffer Expressions <https://developers.arcgis.com/rest/services-reference/bufferexpressions.htm>`_
    ------------------------------------------------    ---------------------------------------------------------
    method                                              Optional string. The method used to apply the buffer with. There are two methods to choose from:

                                                        Choice list:['Geodesic', 'Planar']

                                                        * ``Planar`` - This method applies a Euclidean buffers and is appropriate for local analysis on projected data. This is the default.
                                                        * ``Geodesic`` - This method is appropriate for large areas and any geographic coordinate system.
    ------------------------------------------------    ---------------------------------------------------------
    dissolve_option                                     Optional string. Determines how output polygon attributes are processed.

                                                        Choice list:['All', 'List', 'None']

                                                        +----------------------------------+---------------------------------------------------------------------------------------------------+
                                                        |Value                             | Description                                                                                       |
                                                        +----------------------------------+---------------------------------------------------------------------------------------------------+
                                                        | All - All features are dissolved | You can calculate summary statistics and determine if you want multipart or single part features. |
                                                        | into one feature.                |                                                                                                   |
                                                        +----------------------------------+---------------------------------------------------------------------------------------------------+
                                                        | List - Features with the same    | You can calculate summary statistics and determine if you want multipart or single part features. |
                                                        | value in the specified field     |                                                                                                   |
                                                        | will be dissolve together.       |                                                                                                   |
                                                        +----------------------------------+---------------------------------------------------------------------------------------------------+
                                                        | None - No features are dissolved.| There are no additional dissolve options.                                                         |
                                                        +----------------------------------+---------------------------------------------------------------------------------------------------+
    ------------------------------------------------    ---------------------------------------------------------
    dissolve_fields                                     Specifies the fields to dissolve on. Multiple fields may be provided.
    ------------------------------------------------    ---------------------------------------------------------
    summary_fields                                      Optional string. A list of field names and statistical summary types
                                                        that you want to calculate for resulting polygons. Summary statistics
                                                        are only available if dissolveOption = List or All. By default, all
                                                        statistics are returned.

                                                        Example: [{"statisticType": "statistic type", "onStatisticField": "field name"}, ..}]

                                                        fieldName is the name of the fields in the input point layer.

                                                        statisticType is one of the following for numeric fields:

                                                            * ``Count`` - Totals the number of values of all the points in each polygon.
                                                            * ``Sum`` - Adds the total value of all the points in each polygon.
                                                            * ``Mean`` - Calculates the average of all the points in each polygon.
                                                            * ``Min`` - Finds the smallest value of all the points in each polygon.
                                                            * ``Max`` - Finds the largest value of all the points in each polygon.
                                                            * ``Range`` - Finds the difference between the Min and Max values.
                                                            * ``Stddev`` - Finds the standard deviation of all the points in each polygon.
                                                            * ``Var`` - Finds the variance of all the points in each polygon.

                                                        statisticType is the following for string fields:

                                                            * ``Count`` - Totals the number of strings for all the points in each polygon.
                                                            * ``Any`` - Returns a sample string of a point in each polygon.

    ------------------------------------------------    ---------------------------------------------------------
    multipart                                           Optional boolean. Determines if output features are multipart or single part.
                                                        This option is only available if a ``dissolve_option`` is applied.
    ------------------------------------------------    ---------------------------------------------------------
    output_name                                         Optional string. The task will create a feature service of the results. You define the name of the service.
    ------------------------------------------------    ---------------------------------------------------------
    gis                                                 Optional, the GIS on which this tool runs. If not specified, the active GIS is used.
    ------------------------------------------------    ---------------------------------------------------------
    context                                             Optional dict. The context parameter contains additional settings that affect task execution. For this task, there are four settings:

                                                        #. Extent (``extent``) - A bounding box that defines the analysis area. Only those features that intersect the bounding box will be analyzed.
                                                        #. Processing spatial reference (``processSR``) - The features will be projected into this coordinate system for analysis.
                                                        #. Output spatial reference (``outSR``) - The features will be projected into this coordinate system after the analysis to be saved. The output spatial reference for the spatiotemporal big data store is always WGS84.
                                                        #. Data store (``dataStore``) - Results will be saved to the specified data store. The default is the spatiotemporal big data store.
    ------------------------------------------------    ---------------------------------------------------------
    future                                              Optional boolean. If 'True', the value is returned as a GPJob.

                                                        The default value is 'False'
    ================================================    =========================================================

    :returns: Output Features as a feature layer collection item

    .. code-block:: python

            # Usage Example: To create buffer based on distance field.

            buffer = create_buffers(input_layer=lyr,
                                    field='dist',
                                    method='Geodesic',
                                    dissolve_option='All',
                                    dissolve_fields='Date')
    """
    kwargs = locals()


    gis = _arcgis.env.active_gis if gis is None else gis
    url = gis.properties.helperServices.geoanalytics.url

    if isinstance(input_layer, FeatureCollection) and \
       'layers' in input_layer.properties and \
       len(input_layer.properties.layers) > 0:
        input_layer = _FeatureSet.from_dict(
            featureset_dict=input_layer._lazy_properties.layers[0].featureSet)

    params = {}
    for key, value in kwargs.items():
        if key != 'field':
            if value is not None:
                params[key] = value
        else:
            params['distance'] = None
            params['distance_unit'] = None

    if output_name is None:
        output_service_name = 'Create Buffers Analysis_' + _id_generator()
        output_name = output_service_name.replace(' ', '_')
    else:
        output_service_name = output_name.replace(' ', '_')

    output_service = _create_output_service(gis, output_name, output_service_name, 'Create Buffers')

    params['output_name'] = _json.dumps({
        "serviceProperties": {"name" : output_name, "serviceUrl" : output_service.url},
        "itemProperties": {"itemId" : output_service.itemid}})

    if context is not None:
        params["context"] = context
    else:
        _set_context(params)

    param_db = {
        "input_layer": (_FeatureSet, "inputLayer"),
        "distance": (float, "distance"),
        "distance_unit": (str, "distanceUnit"),
        "field": (str, "field"),
        "method": (str, "method"),
        "dissolve_option": (str, "dissolveOption"),
        "dissolve_fields": (str, "dissolveFields"),
        "summary_fields": (str, "summaryFields"),
        "multipart": (bool, "multipart"),
        "output_name": (str, "outputName"),
        "context": (str, "context"),
        "output": (_FeatureSet, "Output Features"),
    }
    return_values = [
        {"name": "output", "display_name": "Output Features", "type": _FeatureSet},
    ]

    try:
        if future:
            gpjob = _execute_gp_tool(gis, "CreateBuffers", params, param_db, return_values, _use_async, url, True, future=future)
            return GAJob(gpjob=gpjob, return_service=output_service)
        _execute_gp_tool(gis, "CreateBuffers", params, param_db, return_values, _use_async, url, True, future=future)
        return output_service
    except:
        output_service.delete()
        raise