@staticmethod
    def disease_stats_update_location_aggregates(location_id,
                                                 children,
                                                 parameter_id,
                                                 dates,
                                                 ):
        """
            Calculates the disease_stats_aggregate for a specific parameter at a
            specific location over the range of dates.

            @param location_id: location to aggregate at
            @param children: locations to aggregate from
            @param parameter_id: arameter to aggregate
            @param dates: dates to aggregate for (as JSON string)
        """

        db = current.db
        atable = current.s3db.disease_stats_aggregate
        ifield = atable.id
        lfield = atable.location_id
        pfield = atable.parameter_id
        dfield = atable.date

        children = json.loads(children)

        # Get the most recent disease_stats_aggregate record for all child locations
        # - doesn't matter whether this is a time or location aggregate
        query = (pfield == parameter_id) & \
                (atable.deleted != True) & \
                (lfield.belongs(children))
        rows = db(query).select(atable.sum,
                                dfield,
                                lfield,
                                orderby=(lfield, ~dfield),
                                # groupby avoids duplicate records for the same
                                # location, but is slightly slower than just
                                # skipping the duplicates in the loop below
                                #groupby=(lfield)
                                )

        if not rows:
            return

        # Lookup which records already exist
        query = (lfield == location_id) & \
                (pfield == parameter_id)
        existing = db(query).select(ifield,
                                    dfield,
                                    )
        exists = {}
        for e in existing:
            exists[e.date] = e.id

        from dateutil.parser import parse
        dates = json.loads(dates)
        insert = atable.insert

        for date in dates:
            # Collect the values, skip duplicate records for the
            # same location => use the most recent one, which is
            # the first row for each location as per the orderby
            # in the query above
            date = parse(date) # produces a datetime
            date = date.date()
            last_location = None
            values = []
            vappend = values.append
            for row in rows:
                if date < row.date:
                    # Skip
                    continue
                new_location_id = row.location_id
                if new_location_id != last_location:
                    last_location = new_location_id
                    vappend(row.sum)

            if values:
                # Aggregate the values
                values_sum = sum(values)
            else:
                values_sum = 0

            # Add or update the aggregated values in the database

            attr = dict(agg_type = 2, # Location
                        sum = values_sum,
                        )

            # Do we already have a record?
            if date in exists:
                db(ifield == exists[date]).update(**attr)
            else:
                # Insert new
                insert(parameter_id = parameter_id,
                       location_id = location_id,
                       date = date,
                       **attr
                       )

# =============================================================================
dataset/ETHPy150Open sahana/eden/modules/s3db/disease.py/DiseaseStatsModel.disease_stats_update_location_aggregates/original