def fill_mapping_with_closest_locations(augmented_datasource_model):
    for extra_graph_line in (
        augmented_datasource_model.extragraphline_set.all()):
        if not extra_graph_line.identifier_mapping:
            # Skip
            continue

        datasource_to = datasource.get_datasource_by_layer(
            extra_graph_line.layer_to_add_line_to)
        datasource_from = datasource.get_datasource_by_layer(
            extra_graph_line.layer_to_get_line_from)

        location_dict_to = dict(
            (l.identifier,
             coordinates.wgs84_to_rd(l.latitude, l.longitude))
            for l in datasource_to.locations())

        location_dict_from = dict(
            (l.identifier,
             coordinates.wgs84_to_rd(l.latitude, l.longitude))
            for l in datasource_from.locations())

        # To add data FROM layer X to another layer Y, we need to be
        # able to translate identifiers FROM layer Y TO layer X. So
        # it's right that from and to are reversed.
        extra_graph_line.identifier_mapping.create_proximity_map(
            identifiers_from=location_dict_to,
            identifiers_to=location_dict_from,
            max_distance=extra_graph_line.max_distance_for_mapping)
    def percentiles(self, location_id, start_datetime=None, end_datetime=None):
        percentiles = {}
        for percentile_layer in models.PercentileLayer.objects.filter(
            layer_to_add_percentile_to=self.datasource_layer):
            source = datasource.get_datasource_by_layer(
                percentile_layer.layer_to_get_percentile_from)

            percentiles[percentile_layer.percentile] = source.timeseries(
                location_id, start_datetime, end_datetime).data()

        return percentiles
    def timeseries(self, location_id, start_datetime=None, end_datetime=None):
        timeseries = self.original_datasource.timeseries(
            location_id, start_datetime, end_datetime)

        for extra_graph_line in models.ExtraGraphLine.objects.filter(
            layer_to_add_line_to=self.datasource_layer):

            extra_identifier = extra_graph_line.map_identifier(location_id)
            if not extra_identifier:
                # There is a mapping, but this ID isn't found in it -- skip
                continue

            # Get datasource to get the extra timeseries from
            layer_from = extra_graph_line.layer_to_get_line_from
            source = datasource.get_datasource_by_layer(layer_from)
            extra_timeseries = source.timeseries(
                extra_identifier,
                start_datetime, end_datetime)
            if extra_timeseries:
                timeseries.add(extra_timeseries)

        return timeseries