Exemple #1
0
    def _get_bounding_geometry(self):
        """
        ### Get bounding geometry
        For bounds mode "*polygons*" this helper function
        returns a list of all geometry that the map should
        be cropped to.
        """
        # Use the cached geometry, if available.
        if self._bounding_geometry_cache:
            return self._bounding_geometry_cache

        opts = self.options
        features = []
        data = opts['bounds']['data']
        id = data['layer']

        # Check that the layer exists.
        if id not in self.layersById:
            raise KartographError('layer not found "%s"' % id)
        layer = self.layersById[id]

        # Construct the filter function of the layer, which specifies
        # what features should be excluded from the map completely.
        if layer.options['filter'] is False:
            layerFilter = lambda a: True
        else:
            layerFilter = lambda rec: filter_record(layer.options['filter'],
                                                    rec)

        # Construct the filter function of the boundary, which specifies
        # what features should be excluded from the boundary calculation.
        # For instance, you often want to exclude Alaska and Hawaii from
        # the boundary computation of the map, although a part of Alaska
        # might be visible in the resulting map.
        if data['filter']:
            boundsFilter = lambda rec: filter_record(data['filter'], rec)
        else:
            boundsFilter = lambda a: True

        # Combine both filters to a single function.
        filter = lambda rec: layerFilter(rec) and boundsFilter(rec)
        # Load the features from the layer source (e.g. a shapefile).
        features = layer.source.get_features(filter=filter,
                                             min_area=data["min-area"],
                                             charset=layer.options['charset'])

        #if verbose:
        #print 'found %d bounding features' % len(features)

        # Omit tiny islands, if needed.
        if layer.options['filter-islands']:
            features = [
                f for f in features
                if f.geometry.area > layer.options['filter-islands']
            ]

        # Store computed boundary in cache.
        self._bounding_geometry_cache = features
        return features
    def _get_bounding_geometry(self):
        """
        ### Get bounding geometry
        For bounds mode "*polygons*" this helper function
        returns a list of all geometry that the map should
        be cropped to.
        """
        # Use the cached geometry, if available.
        if self._bounding_geometry_cache:
            return self._bounding_geometry_cache

        opts = self.options
        features = []
        data = opts['bounds']['data']
        id = data['layer']

        # Check that the layer exists.
        if id not in self.layersById:
            raise KartographError('layer not found "%s"' % id)
        layer = self.layersById[id]

        # Construct the filter function of the layer, which specifies
        # what features should be excluded from the map completely.
        if layer.options['filter'] is False:
            layerFilter = lambda a: True
        else:
            layerFilter = lambda rec: filter_record(layer.options['filter'], rec)

        # Construct the filter function of the boundary, which specifies
        # what features should be excluded from the boundary calculation.
        # For instance, you often want to exclude Alaska and Hawaii from
        # the boundary computation of the map, although a part of Alaska
        # might be visible in the resulting map.
        if data['filter']:
            boundsFilter = lambda rec: filter_record(data['filter'], rec)
        else:
            boundsFilter = lambda a: True

        # Combine both filters to a single function.
        filter = lambda rec: layerFilter(rec) and boundsFilter(rec)
        # Load the features from the layer source (e.g. a shapefile).
        features = layer.source.get_features(
            filter=filter,
            min_area=data["min-area"],
            charset=layer.options['charset']
        )

        #if verbose:
            #print 'found %d bounding features' % len(features)

        # Omit tiny islands, if needed.
        if layer.options['filter-islands']:
            features = [f for f in features
                if f.geometry.area > layer.options['filter-islands']]

        # Store computed boundary in cache.
        self._bounding_geometry_cache = features
        return features
    def get_features(self, layer, proj, view, opts, view_poly):
        """
        returns a list of projected and filtered features of a layer
        """
        id = layer['id']
        src = self.layers[id]
        is_projected = False

        if 'src' in layer:  # regular geodata layer
            if layer['filter'] is False:
                filter = None
            else:
                filter = lambda rec: filter_record(layer['filter'], rec)
            features = src.get_features(filter)

        elif 'special' in layer:  # special layers need special treatment
            if layer['special'] == "graticule":
                bbox = [-180, -90, 180, 90]
                if opts['bounds']['mode'] == "bbox":
                    bbox = opts['bounds']['data']
                lats = layer['latitudes']
                lons = layer['longitudes']
                features = src.get_features(lats, lons, proj, bbox)

            elif layer['special'] == "sea":
                features = src.get_features(proj.sea_shape())
                is_projected = True

        for feature in features:
            if not is_projected:
                feature.project(proj)
            feature.project_view(view)

        return features
    def get_features(self, layer, proj, view, opts, view_poly):
        """
        returns a list of projected and filtered features of a layer
        """
        id = layer['id']
        src = self.layers[id]
        is_projected = False

        bbox = [-180, -90, 180, 90]
        if opts['bounds']['mode'] == "bbox":
            bbox = opts['bounds']['data']
        if 'crop' in opts['bounds']:
            bbox = opts['bounds']['crop']

        if 'src' in layer:  # regular geodata layer
            if layer['filter'] is False:
                filter = None
            else:
                filter = lambda rec: filter_record(layer['filter'], rec)
            features = src.get_features(filter=filter,
                                        bbox=bbox,
                                        verbose=self._verbose)

        elif 'special' in layer:  # special layers need special treatment
            if layer['special'] == "graticule":
                lats = layer['latitudes']
                lons = layer['longitudes']
                features = src.get_features(lats, lons, proj, bbox=bbox)

            elif layer['special'] == "sea":
                features = src.get_features(proj.sea_shape())
                is_projected = True

        for feature in features:
            if not is_projected:
                feature.project(proj)
            feature.project_view(view)

        return features
Exemple #5
0
    def get_features(self, layer, proj, view, opts, view_poly):
        """
        returns a list of projected and filtered features of a layer
        """
        id = layer["id"]
        src = self.layers[id]
        is_projected = False

        bbox = [-180, -90, 180, 90]
        if opts["bounds"]["mode"] == "bbox":
            bbox = opts["bounds"]["data"]
        if "crop" in opts["bounds"]:
            bbox = opts["bounds"]["crop"]

        if "src" in layer:  # regular geodata layer
            if layer["filter"] is False:
                filter = None
            else:
                filter = lambda rec: filter_record(layer["filter"], rec)
            features = src.get_features(filter=filter, bbox=bbox)

        elif "special" in layer:  # special layers need special treatment
            if layer["special"] == "graticule":
                lats = layer["latitudes"]
                lons = layer["longitudes"]
                features = src.get_features(lats, lons, proj, bbox=bbox)

            elif layer["special"] == "sea":
                features = src.get_features(proj.sea_shape())
                is_projected = True

        for feature in features:
            if not is_projected:
                feature.project(proj)
            feature.project_view(view)

        return features
Exemple #6
0
    # Write results files headers
    write_results_files_headers()

    # Download record, calculate cost, and write to results file
    while remaining_records is True:
        request_params["offset"] = offset
        requested_records = request_records(request_params=request_params)

        remaining_records = \
            False if len(requested_records["items"]) == 0 else True

        if remaining_records is True:
            print("Processing records {}-{} of ~10,200...".format(
                offset + 1, offset + len(requested_records["items"])))
            for r in requested_records["items"]:
                if filter_record(record=r)[0]:

                    reason = filter_record(record=r)[1]
                    with open(
                            os.path.join(os.getcwd(), "results",
                                         "filtered_records.csv"),
                            "ab") as filter_results_file:
                        writer = csv.writer(filter_results_file, delimiter=",")
                        write_filter_results(record=r,
                                             csv_writer=writer,
                                             why=reason)
                else:
                    annual_charging_cost = process_record(
                        record=r,
                        db=db,
                        baseline_weekday_profile=baseline_weekday_profile,
    def get_features(layer, filter=False, min_area=0):
        """
        ### get_features()
        Returns a list of projected and filtered features of a layer.
        """
        opts = layer.map.options
        is_projected = False

        # Let's see if theres a better bounding box than this..
        bbox = [-180, -90, 180, 90]

        # Use the clipping mode defined in the map configuration
        if opts['bounds']['mode'] == "bbox":
            bbox = opts['bounds']['data']
        # The 'crop' property overrides the clipping settings
        if 'crop' in opts['bounds'] and opts['bounds']['crop']:
            # If crop is set to "auto", which is the default behaviour, Kartograph
            # will use the actual bounding geometry to compute the bounding box
            if opts['bounds']['crop'] == "auto":
                if layer.map._unprojected_bounds:
                    bbox = layer.map._unprojected_bounds
                    bbox.inflate(inflate=opts['bounds']['padding'] * 2)
                elif _verbose:
                    pass
                    #print 'could not compute bounding box for auto-cropping'
            else:
                # otherwise it will use the user defined bbox in the format
                # [minLon, minLat, maxLon, maxLat]
                bbox = opts['bounds']['crop']

        # If the layer has the "src" property, it is a **regular map layer** source, which
        # means that there's an exernal file that we load the geometry and meta data from.
        if 'src' in layer.options:
            if layer.options['filter'] is False:
                filter = None
            else:
                filter = lambda rec: filter_record(layer.options['filter'], rec)

            # Now we ask the layer source to generate the features that will be displayed
            # in the map.
            features = layer.source.get_features(
                filter=filter,
                bbox=bbox,
                ignore_holes='ignore-holes' in layer.options and layer.options['ignore-holes'],
                charset=layer.options['charset']
            )
            if _verbose:
                #print 'loaded %d features from shapefile %s' % (len(features), layer.options['src'])
                pass

        # In contrast to regular layers, the geometry for **special (or virtual) layers** is generated
        # by Kartograph itself, based on some properties defined in the layer config.
        elif 'special' in layer.options:
            # The graticule layer generates line features for longitudes and latitudes
            if layer.options['special'] == "graticule":
                lats = layer.options['latitudes']
                lons = layer.options['longitudes']
                features = layer.source.get_features(lats, lons, layer.map.proj, bbox=bbox)

            # The "sea" layer generates a MultiPolygon that represents the entire boundary
            # of the map. Especially useful for non-cylindrical map projections.
            elif layer.options['special'] == "sea":
                features = layer.source.get_features(layer.map.proj)
                is_projected = True

        for feature in features:
            # If the features are not projected yet, we project them now.
            if not is_projected:
                feature.project(layer.map.proj)
            # Transform features to view coordinates.
            feature.project_view(layer.map.view)

        # Remove features that don't intersect our clipping polygon
        if layer.map.view_poly:
            features = [feature for feature in features
            if feature.geometry and feature.geometry.intersects(layer.map.view_poly)]
        layer.features = features
Exemple #8
0
    def get_features(layer, filter=False, min_area=0, contained_geom=None):
        """
        ### get_features()
        Returns a list of projected and filtered features of a layer.
        """
        opts = layer.map.options
        #   print 'Getting features for layer.id={0}'.format(layer.id)
        #        print 'layer.map.options={0}'.format(layer.map.options)
        is_projected = False  # should this be left?
        #  print 'First Hash of layer.map._side_bounding_geometry={0}'.format(hash(str(layer.map._side_bounding_geometry)))
        bounding_geom = None
        # Let's see if theres a better bounding box than this..
        bbox = [-180, -90, 180, 90]

        #        if layer.map.proj:
        #            layer.source.proj = layer.map.proj # TODO: Remove?

        # Use the clipping mode defined in the map configuration
        if opts['bounds']['mode'] == "bbox":
            bbox = opts['bounds']['data']
        # The 'crop' property overrides the clipping settings
        if 'crop' in opts['bounds'] and opts['bounds']['crop']:
            # If crop is set to "auto", which is the default behaviour, Kartograph
            # will use the actual bounding geometry to compute the bounding box
            if opts['bounds']['crop'] == "auto":
                if layer.map._unprojected_bounds:
                    bbox = layer.map._unprojected_bounds
                    bbox.inflate(inflate=1,
                                 pad_dict=opts['bounds']['padding-dict'])
                elif _verbose:
                    pass
                    #print 'could not compute bounding box for auto-cropping'
            else:
                # otherwise it will use the user defined bbox in the format
                # [minLon, minLat, maxLon, maxLat]
                bbox = opts['bounds']['crop']
            if "sidelayer" in layer.options and opts['bounds']['data'][
                    'sidelayer'] != layer.id and layer.map._side_bounding_geometry is not None:
                # We are cropping/removing stuff based on whether it intersects the sidelayer
                bounding_geom = layer.map._side_bounding_geometry
                #print('\tSetting bounding_geom to side_bounding_geometry, hash of which is {0}'.format(hash(str(bounding_geom))))
        # If the layer has the "src" property, it is a **regular map layer** source, which
        # means that there's an exernal file that we load the geometry and meta data from.
        if 'src' in layer.options:
            if layer.options['filter'] is False:
                filter = None
            else:
                filter = lambda rec: filter_record(layer.options['filter'], rec
                                                   )

            # Now we ask the layer source to generate the features that will be displayed
            # in the map.
#            print 'layer.options["init_offset"]={0}'.format(layer.options['init_offset'])
            features = layer.source.get_features(
                filter=filter,
                bbox=bbox,
                ignore_holes='ignore-holes' in layer.options
                and layer.options['ignore-holes'],
                charset=layer.options['charset'],
                bounding_geom=bounding_geom,
                contained_geom=contained_geom)
            if _verbose:
                #print 'loaded %d features from shapefile %s' % (len(features), layer.options['src'])
                pass

        # In contrast to regular layers, the geometry for **special (or virtual) layers** is generated
        # by Kartograph itself, based on some properties defined in the layer config.
        elif 'special' in layer.options:
            # The graticule layer generates line features for longitudes and latitudes
            if layer.options['special'] == "graticule":
                lats = layer.options['latitudes']
                lons = layer.options['longitudes']
                features = layer.source.get_features(lats,
                                                     lons,
                                                     layer.map.proj,
                                                     bbox=bbox)

            # The "sea" layer generates a MultiPolygon that represents the entire boundary
            # of the map. Especially useful for non-cylindrical map projections.
            elif layer.options['special'] == "sea":
                features = layer.source.get_features(layer.map.proj)
                is_projected = True

        # If we're in the sidelayer main (e.g. countylayer for our application),
        # note that EVERY county should be specially styled

        layer.special_fips = []
        for feature in features:
            #print 'feature={0}'.format(feature)
            if 'sidelayer' in layer.options:
                #print 'projecting with side_proj'
                feature.project(layer.map.side_proj)
            elif 'COUNTYFP' in feature.props and feature.props[
                    'COUNTYFP'] in layer.proj_feat_cache:
                feature.geometry = deepcopy(
                    layer.proj_feat_cache[feature.props['COUNTYFP']])
                #print 'Found cached feature {0}'.format(feature.props['NAME'])
            else:
                feature.project(layer.map.proj)
                layer.proj_feat_cache[feature.props['COUNTYFP']] = deepcopy(
                    feature.geometry)
                #print 'Caching feature {0}'.format(feature.props['NAME'])
            curr_fp = ''
            if 'sidelayer' in layer.options and layer.options[
                    'sidelayer'] == layer.id:

                for curr_prop in feature.props:
                    temp_fp = (re.search('FP', curr_prop))
                    if temp_fp is not None and len(
                            temp_fp.group(0)) > len(curr_fp):
                        layer.special_fips.append(feature.props[curr_prop])
                        curr_fp = temp_fp.group(0)

            #It's after this point that we want to adjust the features with scaling and such

        # Remove features that don't intersect our clipping polygon
#        if layer.map.view_poly:
#            features = [feature for feature in features
#            if feature.geometry and feature.geometry.intersects(layer.map.view_poly)]
        layer.features = features