示例#1
0
 def test_map_data_right_legend_info(self):
     data = get_prevalence_of_undernutrition_data_map('icds-cas',
                                                      config={
                                                          'month':
                                                          (2017, 5, 1),
                                                      },
                                                      loc_level='state')
     expected = underweight_children_help_text(age_label="0 - 5 years",
                                               html=True)
     self.assertEquals(data['rightLegend']['info'], expected)
 def test_map_data_right_legend_info(self):
     data = get_prevalence_of_undernutrition_data_map(
         'icds-cas',
         config={
             'month': (2017, 5, 1),
         },
         loc_level='state'
     )
     expected = underweight_children_help_text(age_label="0 - 5 years", html=True)
     self.assertEquals(data['rightLegend']['info'], expected)
示例#3
0
 def test_sector_data_info(self):
     data = get_prevalence_of_undernutrition_sector_data(
         'icds-cas',
         config={
             'month': (2017, 5, 1),
             'state_id': 'st1',
             'district_id': 'd1',
             'block_id': 'b1',
         },
         location_id='b1',
         loc_level='supervisor')
     self.assertEquals(
         data['info'],
         underweight_children_help_text(age_label="0-5 years", html=True))
 def test_sector_data_info(self):
     data = get_prevalence_of_undernutrition_sector_data(
         'icds-cas',
         config={
             'month': (2017, 5, 1),
             'state_id': 'st1',
             'district_id': 'd1',
             'block_id': 'b1',
         },
         location_id='b1',
         loc_level='supervisor'
     )
     self.assertEquals(
         data['info'],
         underweight_children_help_text(age_label="0-5 years", html=True)
     )
示例#5
0
 def test_data_underweight_weight_for_age(self):
     self.assertDictEqual(
         get_maternal_child_data(
             'icds-cas', {
                 'month': (2017, 5, 1),
                 'prev_month': (2017, 4, 1),
                 'aggregation_level': 1
             })['records'][0][0], {
                 "redirect": "maternal_and_child/underweight_children",
                 "color": "green",
                 "all": 696,
                 "frequency": "month",
                 "format": "percent_and_div",
                 "help_text": underweight_children_help_text(),
                 "percent": -14.901477832512326,
                 "value": 150,
                 "label": "Underweight (Weight-for-Age)"
             })
示例#6
0
 def test_data_underweight_weight_for_age(self):
     self.assertDictEqual(
         get_maternal_child_data(
             'icds-cas',
             {
                 'month': (2017, 5, 1),
                 'prev_month': (2017, 4, 1),
                 'aggregation_level': 1
             }
         )['records'][0][0],
         {
             "redirect": "maternal_and_child/underweight_children",
             "color": "green",
             "all": 696,
             "frequency": "month",
             "format": "percent_and_div",
             "help_text": underweight_children_help_text(),
             "percent": -14.901477832512326,
             "value": 150,
             "label": "Underweight (Weight-for-Age)"
         }
     )
示例#7
0
def get_prevalence_of_undernutrition_sector_data(domain,
                                                 config,
                                                 loc_level,
                                                 location_id,
                                                 show_test=False,
                                                 icds_features_flag=False):
    group_by = ['%s_name' % loc_level]

    config['month'] = datetime(*config['month'])
    data = AggChildHealthMonthly.objects.filter(**config).values(
        *group_by).annotate(
            moderately_underweight=Sum(
                'nutrition_status_moderately_underweight'),
            severely_underweight=Sum('nutrition_status_severely_underweight'),
            weighed=Sum('nutrition_status_weighed'),
            normal=Sum('nutrition_status_normal'),
            total=Sum('wer_eligible'),
        ).order_by('%s_name' % loc_level)

    if not show_test:
        data = apply_exclude(domain, data)

    if 'age_tranche' not in config:
        data = data.filter(age_tranche__lt=72)

    chart_data = {'blue': []}

    tooltips_data = defaultdict(
        lambda: {
            'severely_underweight': 0,
            'moderately_underweight': 0,
            'weighed': 0,
            'normal': 0,
            'total': 0
        })
    location_launched_status = get_location_launched_status(config, loc_level)

    for row in data:
        if location_launched_status:
            launched_status = location_launched_status.get(row['%s_name' %
                                                               loc_level])
            if launched_status is None or launched_status <= 0:
                continue
        weighed = row['weighed']
        total = row['total']
        name = row['%s_name' % loc_level]

        severely_underweight = row['severely_underweight']
        moderately_underweight = row['moderately_underweight']
        normal = row['normal']

        tooltips_data[name]['severely_underweight'] += severely_underweight
        tooltips_data[name]['moderately_underweight'] += moderately_underweight
        tooltips_data[name]['weighed'] += (weighed or 0)
        tooltips_data[name]['normal'] += normal
        tooltips_data[name]['total'] += (total or 0)

        chart_data['blue'].append([
            name, ((moderately_underweight or 0) +
                   (severely_underweight or 0)) / float(weighed or 1)
        ])

    chart_data['blue'] = sorted(chart_data['blue'],
                                key=lambda loc_and_value:
                                (loc_and_value[0] is not None, loc_and_value))

    return {
        "tooltips_data":
        dict(tooltips_data),
        "info":
        underweight_children_help_text(age_label="0-5 years", html=True),
        "chart_data": [{
            "values": chart_data['blue'],
            "key": "",
            "strokeWidth": 2,
            "classed": "dashed",
            "color": MapColors.BLUE
        }]
    }
示例#8
0
def get_prevalence_of_undernutrition_data_map(domain,
                                              config,
                                              loc_level,
                                              show_test=False,
                                              icds_features_flag=False):
    config['month'] = datetime(*config['month'])

    def get_data_for(filters):
        queryset = AggChildHealthMonthly.objects.filter(**filters).values(
            '%s_name' % loc_level,
            '%s_map_location_name' % loc_level).annotate(
                moderately_underweight=Sum(
                    'nutrition_status_moderately_underweight'),
                severely_underweight=Sum(
                    'nutrition_status_severely_underweight'),
                normal=Sum('nutrition_status_normal'),
                weighed=Sum('nutrition_status_weighed'),
                total=Sum('wer_eligible'),
            ).order_by('%s_name' % loc_level,
                       '%s_map_location_name' % loc_level)
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        if 'age_tranche' not in config:
            queryset = queryset.filter(age_tranche__lt=72)
        return queryset

    data_for_map = defaultdict(
        lambda: {
            'moderately_underweight': 0,
            'severely_underweight': 0,
            'normal': 0,
            'weighed': 0,
            'total': 0,
            'original_name': []
        })

    moderately_underweight_total = 0
    severely_underweight_total = 0
    normal_total = 0
    all_total = 0
    weighed_total = 0

    values_to_calculate_average = {'numerator': 0, 'denominator': 0}

    location_launched_status = get_location_launched_status(config, loc_level)

    for row in get_data_for(config):
        if location_launched_status:
            launched_status = location_launched_status.get(row['%s_name' %
                                                               loc_level])
            if launched_status is None or launched_status <= 0:
                continue
        weighed = row['weighed'] or 0
        total = row['total'] or 0
        name = row['%s_name' % loc_level]
        on_map_name = row['%s_map_location_name' % loc_level] or name
        severely_underweight = row['severely_underweight'] or 0
        moderately_underweight = row['moderately_underweight'] or 0
        normal = row['normal'] or 0

        values_to_calculate_average[
            'numerator'] += moderately_underweight if moderately_underweight else 0
        values_to_calculate_average[
            'numerator'] += severely_underweight if severely_underweight else 0
        values_to_calculate_average['denominator'] += weighed if weighed else 0

        moderately_underweight_total += moderately_underweight
        severely_underweight_total += severely_underweight
        normal_total += normal
        all_total += total
        weighed_total += weighed

        data_for_map[on_map_name][
            'severely_underweight'] += severely_underweight
        data_for_map[on_map_name][
            'moderately_underweight'] += moderately_underweight
        data_for_map[on_map_name]['normal'] += normal
        data_for_map[on_map_name]['total'] += total
        data_for_map[on_map_name]['weighed'] += weighed
        data_for_map[on_map_name]['original_name'].append(name)

    for data_for_location in data_for_map.values():
        numerator = data_for_location[
            'moderately_underweight'] + data_for_location[
                'severely_underweight']
        value = numerator * 100 / (data_for_location['weighed'] or 1)
        if value < 20:
            data_for_location.update({'fillKey': '0%-20%'})
        elif 20 <= value < 35:
            data_for_location.update({'fillKey': '20%-35%'})
        elif value >= 35:
            data_for_location.update({'fillKey': '35%-100%'})

    fills = OrderedDict()
    fills.update({'0%-20%': MapColors.PINK})
    fills.update({'20%-35%': MapColors.ORANGE})
    fills.update({'35%-100%': MapColors.RED})
    fills.update({'Not Launched': MapColors.GREY})
    fills.update({'defaultFill': MapColors.GREY})

    average = ((values_to_calculate_average['numerator'] * 100) /
               float(values_to_calculate_average['denominator'] or 1))

    gender_label, age_label, chosen_filters = chosen_filters_to_labels(
        config, default_interval='0 - 5 years')

    return {
        "slug":
        "moderately_underweight",
        "label":
        "Percent of Children{gender} Underweight ({age})".format(
            gender=gender_label, age=age_label),
        "fills":
        fills,
        "rightLegend": {
            "average":
            format_decimal(average),
            "info":
            underweight_children_help_text(age_label=age_label, html=True),
            "extended_info": [{
                'indicator':
                'Total Children{} weighed in given month:'.format(
                    chosen_filters),
                'value':
                indian_formatted_number(weighed_total)
            }, {
                'indicator':
                'Number of children unweighed{}:'.format(chosen_filters),
                'value':
                indian_formatted_number(all_total - weighed_total)
            }, {
                'indicator':
                '% Severely Underweight{}:'.format(chosen_filters),
                'value':
                '%.2f%%' %
                (severely_underweight_total * 100 / float(weighed_total or 1))
            }, {
                'indicator':
                '% Moderately Underweight{}:'.format(chosen_filters),
                'value':
                '%.2f%%' % (moderately_underweight_total * 100 /
                            float(weighed_total or 1))
            }, {
                'indicator':
                '% Normal{}:'.format(chosen_filters),
                'value':
                '%.2f%%' % (normal_total * 100 / float(weighed_total or 1))
            }]
        },
        "data":
        dict(data_for_map)
    }
示例#9
0
def get_maternal_child_data(domain,
                            config,
                            show_test=False,
                            icds_feature_flag=False):
    def get_data_for_child_health_monthly(date, filters):

        age_filters = {
            'age_tranche': 72
        } if icds_feature_flag else {
            'age_tranche__in': [0, 6, 72]
        }

        moderately_underweight = exclude_records_by_age_for_column(
            {'age_tranche': 72}, 'nutrition_status_moderately_underweight')
        severely_underweight = exclude_records_by_age_for_column(
            {'age_tranche': 72}, 'nutrition_status_severely_underweight')
        wasting_moderate = exclude_records_by_age_for_column(
            age_filters, wasting_moderate_column(icds_feature_flag))
        wasting_severe = exclude_records_by_age_for_column(
            age_filters, wasting_severe_column(icds_feature_flag))
        stunting_moderate = exclude_records_by_age_for_column(
            age_filters, stunting_moderate_column(icds_feature_flag))
        stunting_severe = exclude_records_by_age_for_column(
            age_filters, stunting_severe_column(icds_feature_flag))
        nutrition_status_weighed = exclude_records_by_age_for_column(
            {'age_tranche': 72}, 'nutrition_status_weighed')
        height_measured_in_month = exclude_records_by_age_for_column(
            age_filters, hfa_recorded_in_month_column(icds_feature_flag))
        weighed_and_height_measured_in_month = exclude_records_by_age_for_column(
            age_filters, wfh_recorded_in_month_column(icds_feature_flag))

        queryset = AggChildHealthMonthly.objects.filter(
            month=date, **filters).values('aggregation_level').annotate(
                underweight=(Sum(moderately_underweight) +
                             Sum(severely_underweight)),
                valid=Sum(nutrition_status_weighed),
                wasting=Sum(wasting_moderate) + Sum(wasting_severe),
                stunting=Sum(stunting_moderate) + Sum(stunting_severe),
                height_measured_in_month=Sum(height_measured_in_month),
                weighed_and_height_measured_in_month=Sum(
                    weighed_and_height_measured_in_month),
                low_birth_weight=Sum('low_birth_weight_in_month'),
                bf_birth=Sum('bf_at_birth'),
                born=Sum('born_in_month'),
                weighed_and_born_in_month=Sum('weighed_and_born_in_month'),
                ebf=Sum('ebf_in_month'),
                ebf_eli=Sum('ebf_eligible'),
                cf_initiation=Sum('cf_initiation_in_month'),
                cf_initiation_eli=Sum('cf_initiation_eligible'))
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    def get_data_for_deliveries(date, filters):
        queryset = AggCcsRecordMonthly.objects.filter(
            month=date, **filters).values('aggregation_level').annotate(
                institutional_delivery=Sum('institutional_delivery_in_month'),
                delivered=Sum('delivered_in_month'))
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    current_month = datetime(*config['month'])
    previous_month = datetime(*config['prev_month'])
    del config['month']
    del config['prev_month']

    this_month_data = get_data_for_child_health_monthly(current_month, config)
    prev_month_data = get_data_for_child_health_monthly(previous_month, config)

    deliveries_this_month = get_data_for_deliveries(current_month, config)
    deliveries_prev_month = get_data_for_deliveries(previous_month, config)

    gender_label, age_label, chosen_filters = chosen_filters_to_labels(
        config, default_interval=default_age_interval(icds_feature_flag))

    return {
        'records':
        [[{
            'label':
            _('Underweight (Weight-for-Age)'),
            'help_text':
            underweight_children_help_text(),
            'percent':
            percent_diff('underweight', this_month_data, prev_month_data,
                         'valid'),
            'color':
            'red' if percent_diff('underweight', this_month_data,
                                  prev_month_data, 'valid') > 0 else 'green',
            'value':
            get_value(this_month_data, 'underweight'),
            'all':
            get_value(this_month_data, 'valid'),
            'format':
            'percent_and_div',
            'frequency':
            'month',
            'redirect':
            'maternal_and_child/underweight_children'
        }, {
            'label':
            _('Wasting (Weight-for-Height)'),
            'help_text':
            _(wasting_help_text(age_label)),
            'percent':
            percent_diff('wasting', this_month_data, prev_month_data,
                         'weighed_and_height_measured_in_month'),
            'color':
            'red' if percent_diff('wasting', this_month_data, prev_month_data,
                                  'weighed_and_height_measured_in_month') > 0
            else 'green',
            'value':
            get_value(this_month_data, 'wasting'),
            'all':
            get_value(this_month_data, 'weighed_and_height_measured_in_month'),
            'format':
            'percent_and_div',
            'frequency':
            'month',
            'redirect':
            'maternal_and_child/wasting'
        }],
         [{
             'label':
             _('Stunting (Height-for-Age)'),
             'help_text':
             _(stunting_help_text(age_label)),
             'percent':
             percent_diff('stunting', this_month_data, prev_month_data,
                          'height_measured_in_month'),
             'color':
             'red'
             if percent_diff('stunting', this_month_data, prev_month_data,
                             'height_measured_in_month') > 0 else 'green',
             'value':
             get_value(this_month_data, 'stunting'),
             'all':
             get_value(this_month_data, 'height_measured_in_month'),
             'format':
             'percent_and_div',
             'frequency':
             'month',
             'redirect':
             'maternal_and_child/stunting'
         }, {
             'label':
             _('Newborns with Low Birth Weight'),
             'help_text':
             _((new_born_with_low_weight_help_text(html=False))),
             'percent':
             percent_diff('low_birth_weight', this_month_data, prev_month_data,
                          'weighed_and_born_in_month'),
             'color':
             get_color_with_red_positive(
                 percent_diff('low_birth_weight', this_month_data,
                              prev_month_data, 'weighed_and_born_in_month')),
             'value':
             get_value(this_month_data, 'low_birth_weight'),
             'all':
             get_value(this_month_data, 'weighed_and_born_in_month'),
             'format':
             'percent_and_div',
             'frequency':
             'month',
             'redirect':
             'maternal_and_child/low_birth'
         }],
         [{
             'label':
             _('Early Initiation of Breastfeeding'),
             'help_text':
             early_initiation_breastfeeding_help_text(),
             'percent':
             percent_diff('bf_birth', this_month_data, prev_month_data,
                          'born'),
             'color':
             get_color_with_green_positive(
                 percent_diff('bf_birth', this_month_data, prev_month_data,
                              'born')),
             'value':
             get_value(this_month_data, 'bf_birth'),
             'all':
             get_value(this_month_data, 'born'),
             'format':
             'percent_and_div',
             'frequency':
             'month',
             'redirect':
             'maternal_and_child/early_initiation'
         }, {
             'label':
             _('Exclusive Breastfeeding'),
             'help_text':
             exclusive_breastfeeding_help_text(),
             'percent':
             percent_diff('ebf', this_month_data, prev_month_data, 'ebf_eli'),
             'color':
             get_color_with_green_positive(
                 percent_diff('ebf', this_month_data, prev_month_data,
                              'ebf_eli')),
             'value':
             get_value(this_month_data, 'ebf'),
             'all':
             get_value(this_month_data, 'ebf_eli'),
             'format':
             'percent_and_div',
             'frequency':
             'month',
             'redirect':
             'maternal_and_child/exclusive_breastfeeding'
         }],
         [{
             'label':
             _('Children initiated appropriate Complementary Feeding'),
             'help_text':
             children_initiated_appropriate_complementary_feeding_help_text(),
             'percent':
             percent_diff('cf_initiation', this_month_data, prev_month_data,
                          'cf_initiation_eli'),
             'color':
             get_color_with_green_positive(
                 percent_diff('cf_initiation', this_month_data,
                              prev_month_data, 'cf_initiation_eli')),
             'value':
             get_value(this_month_data, 'cf_initiation'),
             'all':
             get_value(this_month_data, 'cf_initiation_eli'),
             'format':
             'percent_and_div',
             'frequency':
             'month',
             'redirect':
             'maternal_and_child/children_initiated'
         }, {
             'label':
             _('Institutional Deliveries'),
             'help_text':
             institutional_deliveries_help_text(),
             'percent':
             percent_diff('institutional_delivery', deliveries_this_month,
                          deliveries_prev_month, 'delivered'),
             'color':
             get_color_with_green_positive(
                 percent_diff('institutional_delivery', deliveries_this_month,
                              deliveries_prev_month, 'delivered')),
             'value':
             get_value(deliveries_this_month, 'institutional_delivery'),
             'all':
             get_value(deliveries_this_month, 'delivered'),
             'format':
             'percent_and_div',
             'frequency':
             'month',
             'redirect':
             'maternal_and_child/institutional_deliveries'
         }]]
    }
示例#10
0
def get_prevalence_of_undernutrition_sector_data(domain,
                                                 config,
                                                 loc_level,
                                                 location_id,
                                                 show_test=False):
    group_by = ['%s_name' % loc_level]

    config['month'] = datetime(*config['month'])
    data = AggChildHealthMonthly.objects.filter(**config).values(
        *group_by).annotate(
            moderately_underweight=Sum(
                'nutrition_status_moderately_underweight'),
            severely_underweight=Sum('nutrition_status_severely_underweight'),
            weighed=Sum('nutrition_status_weighed'),
            normal=Sum('nutrition_status_normal'),
            total=Sum('wer_eligible'),
        ).order_by('%s_name' % loc_level)

    if not show_test:
        data = apply_exclude(domain, data)

    if 'age_tranche' not in config:
        data = data.exclude(age_tranche=72)

    chart_data = {'blue': []}

    tooltips_data = defaultdict(
        lambda: {
            'severely_underweight': 0,
            'moderately_underweight': 0,
            'weighed': 0,
            'normal': 0,
            'total': 0
        })

    loc_children = get_child_locations(domain, location_id, show_test)
    result_set = set()

    for row in data:
        weighed = row['weighed']
        total = row['total']
        name = row['%s_name' % loc_level]
        result_set.add(name)

        severely_underweight = row['severely_underweight']
        moderately_underweight = row['moderately_underweight']
        normal = row['normal']

        tooltips_data[name]['severely_underweight'] += severely_underweight
        tooltips_data[name]['moderately_underweight'] += moderately_underweight
        tooltips_data[name]['weighed'] += (weighed or 0)
        tooltips_data[name]['normal'] += normal
        tooltips_data[name]['total'] += (total or 0)

        chart_data['blue'].append([
            name, ((moderately_underweight or 0) +
                   (severely_underweight or 0)) / float(weighed or 1)
        ])

    for sql_location in loc_children:
        if sql_location.name not in result_set:
            chart_data['blue'].append([sql_location.name, 0])

    chart_data['blue'] = sorted(chart_data['blue'])

    return {
        "tooltips_data":
        dict(tooltips_data),
        "info":
        underweight_children_help_text(age_label="0-5 years", html=True),
        "chart_data": [{
            "values": chart_data['blue'],
            "key": "",
            "strokeWidth": 2,
            "classed": "dashed",
            "color": MapColors.BLUE
        }]
    }
示例#11
0
def get_maternal_child_data(domain, config, show_test=False, icds_feature_flag=False):

    def get_data_for_child_health_monthly(date, filters):

        age_filters = {'age_tranche': 72} if icds_feature_flag else {'age_tranche__in': [0, 6, 72]}

        moderately_underweight = exclude_records_by_age_for_column(
            {'age_tranche': 72},
            'nutrition_status_moderately_underweight'
        )
        severely_underweight = exclude_records_by_age_for_column(
            {'age_tranche': 72},
            'nutrition_status_severely_underweight'
        )
        wasting_moderate = exclude_records_by_age_for_column(
            age_filters,
            wasting_moderate_column(icds_feature_flag)
        )
        wasting_severe = exclude_records_by_age_for_column(
            age_filters,
            wasting_severe_column(icds_feature_flag)
        )
        stunting_moderate = exclude_records_by_age_for_column(
            age_filters,
            stunting_moderate_column(icds_feature_flag)
        )
        stunting_severe = exclude_records_by_age_for_column(
            age_filters,
            stunting_severe_column(icds_feature_flag)
        )
        nutrition_status_weighed = exclude_records_by_age_for_column(
            {'age_tranche': 72},
            'nutrition_status_weighed'
        )
        height_measured_in_month = exclude_records_by_age_for_column(
            age_filters,
            hfa_recorded_in_month_column(icds_feature_flag)
        )
        weighed_and_height_measured_in_month = exclude_records_by_age_for_column(
            age_filters,
            wfh_recorded_in_month_column(icds_feature_flag)
        )

        queryset = AggChildHealthMonthly.objects.filter(
            month=date, **filters
        ).values(
            'aggregation_level'
        ).annotate(
            underweight=(
                Sum(moderately_underweight) + Sum(severely_underweight)
            ),
            valid=Sum(nutrition_status_weighed),
            wasting=Sum(wasting_moderate) + Sum(wasting_severe),
            stunting=Sum(stunting_moderate) + Sum(stunting_severe),
            height_measured_in_month=Sum(height_measured_in_month),
            weighed_and_height_measured_in_month=Sum(weighed_and_height_measured_in_month),
            low_birth_weight=Sum('low_birth_weight_in_month'),
            bf_birth=Sum('bf_at_birth'),
            born=Sum('born_in_month'),
            weighed_and_born_in_month=Sum('weighed_and_born_in_month'),
            ebf=Sum('ebf_in_month'),
            ebf_eli=Sum('ebf_eligible'),
            cf_initiation=Sum('cf_initiation_in_month'),
            cf_initiation_eli=Sum('cf_initiation_eligible')
        )
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    def get_data_for_deliveries(date, filters):
        queryset = AggCcsRecordMonthly.objects.filter(
            month=date, **filters
        ).values(
            'aggregation_level'
        ).annotate(
            institutional_delivery=Sum('institutional_delivery_in_month'),
            delivered=Sum('delivered_in_month')
        )
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    current_month = datetime(*config['month'])
    previous_month = datetime(*config['prev_month'])
    del config['month']
    del config['prev_month']

    this_month_data = get_data_for_child_health_monthly(current_month, config)
    prev_month_data = get_data_for_child_health_monthly(previous_month, config)

    deliveries_this_month = get_data_for_deliveries(current_month, config)
    deliveries_prev_month = get_data_for_deliveries(previous_month, config)

    gender_label, age_label, chosen_filters = chosen_filters_to_labels(
        config,
        default_interval=default_age_interval(icds_feature_flag)
    )

    return {
        'records': [
            [
                {
                    'label': _('Underweight (Weight-for-Age)'),
                    'help_text': underweight_children_help_text(),
                    'percent': percent_diff(
                        'underweight',
                        this_month_data,
                        prev_month_data,
                        'valid'
                    ),
                    'color': 'red' if percent_diff(
                        'underweight',
                        this_month_data,
                        prev_month_data,
                        'valid'
                    ) > 0 else 'green',
                    'value': get_value(this_month_data, 'underweight'),
                    'all': get_value(this_month_data, 'valid'),
                    'format': 'percent_and_div',
                    'frequency': 'month',
                    'redirect': 'maternal_and_child/underweight_children'
                },
                {
                    'label': _('Wasting (Weight-for-Height)'),
                    'help_text': _(wasting_help_text(age_label)),
                    'percent': percent_diff(
                        'wasting',
                        this_month_data,
                        prev_month_data,
                        'weighed_and_height_measured_in_month'
                    ),
                    'color': 'red' if percent_diff(
                        'wasting',
                        this_month_data,
                        prev_month_data,
                        'weighed_and_height_measured_in_month'
                    ) > 0 else 'green',
                    'value': get_value(this_month_data, 'wasting'),
                    'all': get_value(this_month_data, 'weighed_and_height_measured_in_month'),
                    'format': 'percent_and_div',
                    'frequency': 'month',
                    'redirect': 'maternal_and_child/wasting'
                }
            ],
            [
                {
                    'label': _('Stunting (Height-for-Age)'),
                    'help_text': _(stunting_help_text(age_label)),
                    'percent': percent_diff(
                        'stunting',
                        this_month_data,
                        prev_month_data,
                        'height_measured_in_month'
                    ),
                    'color': 'red' if percent_diff(
                        'stunting',
                        this_month_data,
                        prev_month_data,
                        'height_measured_in_month'
                    ) > 0 else 'green',
                    'value': get_value(this_month_data, 'stunting'),
                    'all': get_value(this_month_data, 'height_measured_in_month'),
                    'format': 'percent_and_div',
                    'frequency': 'month',
                    'redirect': 'maternal_and_child/stunting'
                },
                {
                    'label': _('Newborns with Low Birth Weight'),
                    'help_text': _((
                        new_born_with_low_weight_help_text(html=False)
                    )),
                    'percent': percent_diff(
                        'low_birth_weight',
                        this_month_data,
                        prev_month_data,
                        'weighed_and_born_in_month'
                    ),
                    'color': 'red' if percent_diff(
                        'low_birth_weight',
                        this_month_data,
                        prev_month_data,
                        'weighed_and_born_in_month'
                    ) > 0 else 'green',
                    'value': get_value(this_month_data, 'low_birth_weight'),
                    'all': get_value(this_month_data, 'weighed_and_born_in_month'),
                    'format': 'percent_and_div',
                    'frequency': 'month',
                    'redirect': 'maternal_and_child/low_birth'
                }
            ],
            [
                {
                    'label': _('Early Initiation of Breastfeeding'),
                    'help_text': early_initiation_breastfeeding_help_text(),
                    'percent': percent_diff(
                        'bf_birth',
                        this_month_data,
                        prev_month_data,
                        'born'
                    ),
                    'color': 'green' if percent_diff(
                        'bf_birth',
                        this_month_data,
                        prev_month_data,
                        'born'
                    ) > 0 else 'red',
                    'value': get_value(this_month_data, 'bf_birth'),
                    'all': get_value(this_month_data, 'born'),
                    'format': 'percent_and_div',
                    'frequency': 'month',
                    'redirect': 'maternal_and_child/early_initiation'
                },
                {
                    'label': _('Exclusive Breastfeeding'),
                    'help_text': exclusive_breastfeeding_help_text(),
                    'percent': percent_diff(
                        'ebf',
                        this_month_data,
                        prev_month_data,
                        'ebf_eli'
                    ),
                    'color': 'green' if percent_diff(
                        'ebf',
                        this_month_data,
                        prev_month_data,
                        'ebf_eli'
                    ) > 0 else 'red',
                    'value': get_value(this_month_data, 'ebf'),
                    'all': get_value(this_month_data, 'ebf_eli'),
                    'format': 'percent_and_div',
                    'frequency': 'month',
                    'redirect': 'maternal_and_child/exclusive_breastfeeding'
                }
            ],
            [
                {
                    'label': _('Children initiated appropriate Complementary Feeding'),
                    'help_text': children_initiated_appropriate_complementary_feeding_help_text(),
                    'percent': percent_diff(
                        'cf_initiation',
                        this_month_data,
                        prev_month_data,
                        'cf_initiation_eli'
                    ),
                    'color': 'green' if percent_diff(
                        'cf_initiation',
                        this_month_data,
                        prev_month_data,
                        'cf_initiation_eli'
                    ) > 0 else 'red',
                    'value': get_value(this_month_data, 'cf_initiation'),
                    'all': get_value(this_month_data, 'cf_initiation_eli'),
                    'format': 'percent_and_div',
                    'frequency': 'month',
                    'redirect': 'maternal_and_child/children_initiated'
                },
                {
                    'label': _('Institutional Deliveries'),
                    'help_text': institutional_deliveries_help_text(),
                    'percent': percent_diff(
                        'institutional_delivery',
                        deliveries_this_month,
                        deliveries_prev_month,
                        'delivered'
                    ),
                    'color': 'green' if percent_diff(
                        'institutional_delivery',
                        deliveries_this_month,
                        deliveries_prev_month,
                        'delivered'
                    ) > 0 else 'red',
                    'value': get_value(deliveries_this_month, 'institutional_delivery'),
                    'all': get_value(deliveries_this_month, 'delivered'),
                    'format': 'percent_and_div',
                    'frequency': 'month',
                    'redirect': 'maternal_and_child/institutional_deliveries'
                }
            ]
        ]
    }
def get_prevalence_of_undernutrition_sector_data(domain, config, loc_level, location_id, show_test=False):
    group_by = ['%s_name' % loc_level]

    config['month'] = datetime(*config['month'])
    data = AggChildHealthMonthly.objects.filter(
        **config
    ).values(
        *group_by
    ).annotate(
        moderately_underweight=Sum('nutrition_status_moderately_underweight'),
        severely_underweight=Sum('nutrition_status_severely_underweight'),
        weighed=Sum('nutrition_status_weighed'),
        normal=Sum('nutrition_status_normal'),
        total=Sum('wer_eligible'),
    ).order_by('%s_name' % loc_level)

    if not show_test:
        data = apply_exclude(domain, data)

    if 'age_tranche' not in config:
        data = data.exclude(age_tranche=72)

    chart_data = {
        'blue': []
    }

    tooltips_data = defaultdict(lambda: {
        'severely_underweight': 0,
        'moderately_underweight': 0,
        'weighed': 0,
        'normal': 0,
        'total': 0
    })

    loc_children = get_child_locations(domain, location_id, show_test)
    result_set = set()

    for row in data:
        weighed = row['weighed']
        total = row['total']
        name = row['%s_name' % loc_level]
        result_set.add(name)

        severely_underweight = row['severely_underweight']
        moderately_underweight = row['moderately_underweight']
        normal = row['normal']

        tooltips_data[name]['severely_underweight'] += severely_underweight
        tooltips_data[name]['moderately_underweight'] += moderately_underweight
        tooltips_data[name]['weighed'] += (weighed or 0)
        tooltips_data[name]['normal'] += normal
        tooltips_data[name]['total'] += (total or 0)

        chart_data['blue'].append([
            name,
            ((moderately_underweight or 0) + (severely_underweight or 0)) / float(weighed or 1)
        ])

    for sql_location in loc_children:
        if sql_location.name not in result_set:
            chart_data['blue'].append([sql_location.name, 0])

    chart_data['blue'] = sorted(chart_data['blue'])

    return {
        "tooltips_data": dict(tooltips_data),
        "info": underweight_children_help_text(age_label="0-5 years", html=True),
        "chart_data": [
            {
                "values": chart_data['blue'],
                "key": "",
                "strokeWidth": 2,
                "classed": "dashed",
                "color": MapColors.BLUE
            }
        ]
    }
def get_prevalence_of_undernutrition_data_map(domain, config, loc_level, show_test=False):

    def get_data_for(filters):
        filters['month'] = datetime(*filters['month'])
        queryset = AggChildHealthMonthly.objects.filter(
            **filters
        ).values(
            '%s_name' % loc_level, '%s_map_location_name' % loc_level
        ).annotate(
            moderately_underweight=Sum('nutrition_status_moderately_underweight'),
            severely_underweight=Sum('nutrition_status_severely_underweight'),
            normal=Sum('nutrition_status_normal'),
            weighed=Sum('nutrition_status_weighed'),
            total=Sum('wer_eligible'),
        ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level)
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        if 'age_tranche' not in config:
            queryset = queryset.exclude(age_tranche=72)
        return queryset

    data_for_map = defaultdict(lambda: {
        'moderately_underweight': 0,
        'severely_underweight': 0,
        'normal': 0,
        'weighed': 0,
        'total': 0,
        'original_name': []
    })

    moderately_underweight_total = 0
    severely_underweight_total = 0
    normal_total = 0
    all_total = 0
    weighed_total = 0

    values_to_calculate_average = {'numerator': 0, 'denominator': 0}
    for row in get_data_for(config):
        weighed = row['weighed'] or 0
        total = row['total'] or 0
        name = row['%s_name' % loc_level]
        on_map_name = row['%s_map_location_name' % loc_level] or name
        severely_underweight = row['severely_underweight'] or 0
        moderately_underweight = row['moderately_underweight'] or 0
        normal = row['normal'] or 0

        values_to_calculate_average['numerator'] += moderately_underweight if moderately_underweight else 0
        values_to_calculate_average['numerator'] += severely_underweight if severely_underweight else 0
        values_to_calculate_average['denominator'] += weighed if weighed else 0

        moderately_underweight_total += moderately_underweight
        severely_underweight_total += severely_underweight
        normal_total += normal
        all_total += total
        weighed_total += weighed

        data_for_map[on_map_name]['severely_underweight'] += severely_underweight
        data_for_map[on_map_name]['moderately_underweight'] += moderately_underweight
        data_for_map[on_map_name]['normal'] += normal
        data_for_map[on_map_name]['total'] += total
        data_for_map[on_map_name]['weighed'] += weighed
        data_for_map[on_map_name]['original_name'].append(name)

    for data_for_location in six.itervalues(data_for_map):
        numerator = data_for_location['moderately_underweight'] + data_for_location['severely_underweight']
        value = numerator * 100 / (data_for_location['weighed'] or 1)
        if value < 20:
            data_for_location.update({'fillKey': '0%-20%'})
        elif 20 <= value < 35:
            data_for_location.update({'fillKey': '20%-35%'})
        elif value >= 35:
            data_for_location.update({'fillKey': '35%-100%'})

    fills = OrderedDict()
    fills.update({'0%-20%': MapColors.PINK})
    fills.update({'20%-35%': MapColors.ORANGE})
    fills.update({'35%-100%': MapColors.RED})
    fills.update({'defaultFill': MapColors.GREY})

    average = (
        (values_to_calculate_average['numerator'] * 100) /
        float(values_to_calculate_average['denominator'] or 1)
    )

    gender_label, age_label, chosen_filters = chosen_filters_to_labels(config, default_interval='0 - 5 years')

    return {
        "slug": "moderately_underweight",
        "label": "Percent of Children{gender} Underweight ({age})".format(
            gender=gender_label,
            age=age_label
        ),
        "fills": fills,
        "rightLegend": {
            "average": format_decimal(average),
            "info": underweight_children_help_text(age_label=age_label, html=True),
            "extended_info": [
                {
                    'indicator': 'Total Children{} weighed in given month:'.format(chosen_filters),
                    'value': indian_formatted_number(weighed_total)
                },
                {
                    'indicator': 'Number of children unweighed{}:'.format(chosen_filters),
                    'value': indian_formatted_number(all_total - weighed_total)
                },
                {
                    'indicator': '% Severely Underweight{}:'.format(chosen_filters),
                    'value': '%.2f%%' % (severely_underweight_total * 100 / float(weighed_total or 1))
                },
                {
                    'indicator': '% Moderately Underweight{}:'.format(chosen_filters),
                    'value': '%.2f%%' % (moderately_underweight_total * 100 / float(weighed_total or 1))
                },
                {
                    'indicator': '% Normal{}:'.format(chosen_filters),
                    'value': '%.2f%%' % (normal_total * 100 / float(weighed_total or 1))
                }
            ]
        },
        "data": dict(data_for_map)
    }