def get_early_initiation_breastfeeding_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(
            birth=Sum('bf_at_birth'),
            in_month=Sum('born_in_month'),
        ).order_by('%s_name' % loc_level)

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

    chart_data = {
        'blue': [],
    }

    tooltips_data = defaultdict(lambda: {
        'in_month': 0,
        'birth': 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
        in_month = row['in_month']
        name = row['%s_name' % loc_level]

        birth = row['birth']

        value = (birth or 0) / float(in_month or 1)

        tooltips_data[name]['birth'] += birth
        tooltips_data[name]['in_month'] += (in_month or 0)

        chart_data['blue'].append([name, value])

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

    return {
        "tooltips_data":
        dict(tooltips_data),
        "info":
        early_initiation_breastfeeding_help_text(html=True),
        "chart_data": [{
            "values": chart_data['blue'],
            "key": "",
            "strokeWidth": 2,
            "classed": "dashed",
            "color": MapColors.BLUE
        }]
    }
Ejemplo n.º 2
0
def get_enrolled_children_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(valid=Sum('valid_in_month'),
                            all=Sum('valid_all_registered_in_month')).order_by(
                                '%s_name' % loc_level)

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

    chart_data = {'blue': []}

    tooltips_data = defaultdict(lambda: {'valid': 0, 'all': 0})
    if icds_features_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    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
        valid = row['valid'] or 0
        all_children = row['all'] or 0
        name = row['%s_name' % loc_level]

        row_values = {'valid': valid, 'all': all_children}

        for prop, value in row_values.items():
            tooltips_data[name][prop] += value

        chart_data['blue'].append([name, valid])

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

    return {
        "tooltips_data":
        dict(tooltips_data),
        "format":
        "number",
        "info":
        percent_children_enrolled_help_text(),
        "chart_data": [{
            "values": chart_data['blue'],
            "key": "",
            "strokeWidth": 2,
            "classed": "dashed",
            "color": MapColors.BLUE
        }]
    }
Ejemplo n.º 3
0
def get_institutional_deliveries_data_map(domain,
                                          config,
                                          loc_level,
                                          show_test=False,
                                          icds_features_flag=False):
    config['month'] = datetime(*config['month'])

    def get_data_for(filters):

        queryset = AggCcsRecordMonthly.objects.filter(**filters).values(
            '%s_name' % loc_level,
            '%s_map_location_name' % loc_level).annotate(
                children=Sum('institutional_delivery_in_month'),
                all=Sum('delivered_in_month'),
            ).order_by('%s_name' % loc_level,
                       '%s_map_location_name' % loc_level)
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    if icds_features_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    data_for_map, valid_total, in_month_total, average, total = generate_data_for_map(
        get_data_for(config),
        loc_level,
        'children',
        'all',
        20,
        60,
        location_launched_status=location_launched_status)

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

    return {
        "slug": "institutional_deliveries",
        "label": "Percent Instituitional Deliveries",
        "fills": fills,
        "rightLegend": {
            "average":
            average,
            "info":
            institutional_deliveries_help_text(html=True),
            "extended_info": [{
                'indicator':
                'Total number of pregnant women who delivered in the current month:',
                'value': indian_formatted_number(valid_total)
            }, {
                'indicator':
                ('Total number of pregnant women who delivered in a '
                 'public/private medical facilitiy in the current month:'),
                'value':
                indian_formatted_number(in_month_total)
            }, {
                'indicator':
                ('% pregnant women who delivered in a public or private medical '
                 'facility in the current month:'),
                'value':
                '%.2f%%' % (in_month_total * 100 / float(valid_total or 1))
            }]
        },
        "data": dict(data_for_map),
    }
Ejemplo n.º 4
0
def get_early_initiation_breastfeeding_chart(domain, config, loc_level, show_test=False, icds_features_flag=False):
    month = datetime(*config['month'])
    three_before = datetime(*config['month']) - relativedelta(months=3)

    config['month__range'] = (three_before, month)
    del config['month']

    # using child health monthly while querying for sector level due to performance issues
    if icds_features_flag and config['aggregation_level'] >= AggregationLevels.SUPERVISOR:
        chm_filter = get_filters_from_config_for_chart_view(config)
        chm_queryset = ChildHealthMonthlyView.objects.filter(**chm_filter)
    else:
        chm_queryset = AggChildHealthMonthly.objects.filter(**config)
    chart_data = chm_queryset.values(
        'month', '%s_name' % loc_level
    ).annotate(
        birth=Sum('bf_at_birth'),
        in_month=Sum('born_in_month'),
    ).order_by('month')

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

    data = {
        'blue': OrderedDict()
    }

    dates = [dt for dt in rrule(MONTHLY, dtstart=three_before, until=month)]

    for date in dates:
        miliseconds = int(date.strftime("%s")) * 1000
        data['blue'][miliseconds] = {'y': 0, 'all': 0, 'birth': 0}

    best_worst = {}
    if icds_features_flag:
        if 'month' not in config:
            config['month'] = month
        location_launched_status = get_location_launched_status(config, loc_level)
    else:
        location_launched_status = None

    for row in chart_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
        date = row['month']
        in_month = row['in_month']
        location = row['%s_name' % loc_level]
        birth = row['birth']

        best_worst[location] = (birth or 0) * 100 / float(in_month or 1)

        date_in_miliseconds = int(date.strftime("%s")) * 1000
        data_for_month = data['blue'][date_in_miliseconds]

        data_for_month['all'] += in_month
        data_for_month['birth'] += birth
        data_for_month['y'] = data_for_month['birth'] / float(data_for_month['all'] or 1)

    all_locations = [
        {
            'loc_name': key,
            'percent': val
        }
        for key, val in best_worst.items()
    ]
    all_locations_sorted_by_name = sorted(all_locations, key=lambda x: x['loc_name'])
    all_locations_sorted_by_percent_and_name = sorted(
        all_locations_sorted_by_name, key=lambda x: x['percent'], reverse=True)

    return {
        "chart_data": [
            {
                "values": [
                    {
                        'x': key,
                        'y': val['y'],
                        'all': val['all'],
                        'birth': val['birth']
                    } for key, val in data['blue'].items()
                ],
                "key": "% Early Initiation of Breastfeeding",
                "strokeWidth": 2,
                "classed": "dashed",
                "color": ChartColors.BLUE
            }
        ],
        "all_locations": all_locations_sorted_by_percent_and_name,
        "top_five": all_locations_sorted_by_percent_and_name[:5],
        "bottom_five": all_locations_sorted_by_percent_and_name[-5:],
        "location_type": loc_level.title() if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
Ejemplo n.º 5
0
def get_exclusive_breastfeeding_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(
            in_month=Sum('ebf_in_month'),
            eligible=Sum('ebf_eligible'),
        ).order_by('%s_name' % loc_level)

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

    chart_data = {
        'blue': [],
    }

    tooltips_data = defaultdict(lambda: {'children': 0, 'all': 0})

    if icds_features_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    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
        valid = row['eligible']
        name = row['%s_name' % loc_level]

        in_month = row['in_month']

        row_values = {'children': in_month or 0, 'all': valid or 0}

        for prop, value in row_values.items():
            tooltips_data[name][prop] += value

        in_month = row['in_month']

        value = (in_month or 0) / float(valid or 1)
        chart_data['blue'].append([name, value])

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

    return {
        "tooltips_data":
        dict(tooltips_data),
        "info":
        exclusive_breastfeeding_help_text(html=True),
        "chart_data": [
            {
                "values": chart_data['blue'],
                "key": "",
                "strokeWidth": 2,
                "classed": "dashed",
                "color": MapColors.BLUE
            },
        ]
    }
Ejemplo n.º 6
0
def get_enrolled_children_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(
                valid=Sum('valid_in_month'),
                all=Sum('valid_all_registered_in_month')).order_by(
                    '%s_name' % loc_level, '%s_map_location_name' % loc_level)
        if not show_test:
            queryset = apply_exclude(domain, queryset)

        return queryset

    data_for_map = defaultdict(lambda: {
        'valid': 0,
        'all': 0,
        'original_name': [],
        'fillKey': 'Children'
    })
    average = []
    total_valid = 0
    total = 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
        valid = row['valid'] or 0
        name = row['%s_name' % loc_level]
        all_children = row['all'] or 0
        on_map_name = row['%s_map_location_name' % loc_level] or name

        average.append(valid)
        total_valid += valid
        total += all_children
        data_for_map[on_map_name]['valid'] += valid
        data_for_map[on_map_name]['all'] += all_children
        data_for_map[on_map_name]['original_name'].append(name)

    fills = OrderedDict()
    fills.update({'Children': MapColors.BLUE})
    fills.update({'Not Launched': MapColors.GREY})
    fills.update({'defaultFill': MapColors.GREY})

    gender_ignored, age_label, chosen_filters = chosen_filters_to_labels(
        config, default_interval='0 - 6 years')

    return {
        "slug": "enrolled_children",
        "label": "",
        "fills": fills,
        "rightLegend": {
            "average":
            '%.2f' % (total_valid * 100 / float(total or 1)),
            "info":
            percent_children_enrolled_help_text(age_label=age_label),
            "extended_info": [{
                'indicator':
                'Number of children{} who are enrolled for Anganwadi Services:'
                .format(chosen_filters),
                'value':
                indian_formatted_number(total_valid)
            }, {
                'indicator':
                ('Total number of children{} who are registered: '.format(
                    chosen_filters)),
                'value':
                indian_formatted_number(total)
            }, {
                'indicator':
                ('Percentage of registered children{} who are enrolled for Anganwadi Services:'
                 .format(chosen_filters)),
                'value':
                '%.2f%%' % (total_valid * 100 / float(total or 1))
            }]
        },
        "data": dict(data_for_map),
    }
Ejemplo n.º 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
        }]
    }
Ejemplo n.º 8
0
def get_prevalence_of_undernutrition_data_chart(domain,
                                                config,
                                                loc_level,
                                                show_test=False,
                                                icds_features_flag=False):
    month = datetime(*config['month'])
    three_before = datetime(*config['month']) - relativedelta(months=3)

    config['month__range'] = (three_before, month)
    del config['month']
    if config['aggregation_level'] >= AggregationLevels.SUPERVISOR:
        chm_filter = get_filters_from_config_for_chart_view(config)
        chm_queryset = ChildHealthMonthlyView.objects.filter(**chm_filter)
    else:
        chm_queryset = AggChildHealthMonthly.objects.filter(**config)
    chart_data = chm_queryset.values('month', '%s_name' % loc_level).annotate(
        moderately_underweight=Sum('nutrition_status_moderately_underweight'),
        normal=Sum('nutrition_status_normal'),
        severely_underweight=Sum('nutrition_status_severely_underweight'),
        weighed=Sum('nutrition_status_weighed'),
        total=Sum('wer_eligible'),
    ).order_by('month')

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

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

    data = {
        'peach': OrderedDict(),
        'orange': OrderedDict(),
        'red': OrderedDict()
    }

    dates = [dt for dt in rrule(MONTHLY, dtstart=three_before, until=month)]

    for date in dates:
        miliseconds = int(date.strftime("%s")) * 1000
        data['peach'][miliseconds] = {'y': 0, 'weighed': 0, 'unweighed': 0}
        data['orange'][miliseconds] = {'y': 0, 'weighed': 0, 'unweighed': 0}
        data['red'][miliseconds] = {'y': 0, 'weighed': 0, 'unweighed': 0}

    best_worst = {}

    if 'month' not in config:
        config['month'] = month
    location_launched_status = get_location_launched_status(config, loc_level)

    for row in chart_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
        date = row['month']
        weighed = row['weighed'] or 0
        location = row['%s_name' % loc_level]
        severely_underweight = row['severely_underweight'] or 0
        moderately_underweight = row['moderately_underweight'] or 0
        total = row['total'] or 0
        normal = row['normal'] or 0

        underweight = (moderately_underweight +
                       severely_underweight) * 100 / float(weighed or 1)

        best_worst[location] = underweight

        date_in_miliseconds = int(date.strftime("%s")) * 1000

        data['peach'][date_in_miliseconds]['y'] += normal
        data['peach'][date_in_miliseconds]['unweighed'] += (total - weighed)
        data['peach'][date_in_miliseconds]['weighed'] += weighed
        data['orange'][date_in_miliseconds]['y'] += moderately_underweight
        data['orange'][date_in_miliseconds]['unweighed'] += (total - weighed)
        data['orange'][date_in_miliseconds]['weighed'] += weighed
        data['red'][date_in_miliseconds]['y'] += severely_underweight
        data['red'][date_in_miliseconds]['unweighed'] += (total - weighed)
        data['red'][date_in_miliseconds]['weighed'] += weighed

    all_locations = [{
        'loc_name': key,
        'percent': value
    } for key, value in best_worst.items()]
    all_locations_sorted_by_name = sorted(all_locations,
                                          key=lambda x: x['loc_name'])
    all_locations_sorted_by_percent_and_name = sorted(
        all_locations_sorted_by_name, key=lambda x: x['percent'])

    return {
        "chart_data": [{
            "values": [{
                'x': key,
                'y': value['y'] / float(value['weighed'] or 1),
                'weighed': value['weighed'],
                'unweighed': value['unweighed'],
            } for key, value in data['peach'].items()],
            "key":
            "% Normal",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.PINK
        }, {
            "values": [{
                'x': key,
                'y': value['y'] / float(value['weighed'] or 1),
                'weighed': value['weighed'],
                'unweighed': value['unweighed'],
            } for key, value in data['orange'].items()],
            "key":
            "% Moderately Underweight (-2 SD)",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.ORANGE
        }, {
            "values": [{
                'x': key,
                'y': value['y'] / float(value['weighed'] or 1),
                'weighed': value['weighed'],
                'unweighed': value['unweighed'],
            } for key, value in data['red'].items()],
            "key":
            "% Severely Underweight (-3 SD) ",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.RED
        }],
        "all_locations":
        all_locations_sorted_by_percent_and_name,
        "top_five":
        all_locations_sorted_by_percent_and_name[:5],
        "bottom_five":
        all_locations_sorted_by_percent_and_name[-5:],
        "location_type":
        loc_level.title()
        if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
def get_newborn_with_low_birth_weight_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(
        low_birth=Sum('low_birth_weight_in_month'),
        in_month=Sum('weighed_and_born_in_month'),
        all=Sum('born_in_month')
    ).order_by('%s_name' % loc_level)

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

    chart_data = {
        'blue': [],
    }

    tooltips_data = defaultdict(lambda: {
        'in_month': 0,
        'low_birth': 0,
        'all': 0
    })
    if icds_features_flag:
        location_launched_status = get_location_launched_status(config, loc_level)
    else:
        location_launched_status = None
    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
        in_month = row['in_month'] or 0
        name = row['%s_name' % loc_level]

        all_records = row['all'] or 0
        low_birth = row['low_birth'] or 0

        value = low_birth / float(in_month or 1)

        tooltips_data[name]['low_birth'] += low_birth
        tooltips_data[name]['in_month'] += in_month
        tooltips_data[name]['all'] += all_records

        chart_data['blue'].append([
            name, value
        ])

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

    return {
        "tooltips_data": dict(tooltips_data),
        "info": _((
            new_born_with_low_weight_help_text(html=True)
        )),
        "chart_data": [
            {
                "values": chart_data['blue'],
                "key": "",
                "strokeWidth": 2,
                "classed": "dashed",
                "color": MapColors.BLUE
            },
        ]
    }
def get_newborn_with_low_birth_weight_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(
            low_birth=Sum('low_birth_weight_in_month'),
            in_month=Sum('weighed_and_born_in_month'),
            all=Sum('born_in_month')
        ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level)
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    if icds_features_flag:
        location_launched_status = get_location_launched_status(config, loc_level)
    else:
        location_launched_status = None
    data_for_map, in_month_total, low_birth_total, average, total = generate_data_for_map(
        get_data_for(config),
        loc_level,
        'low_birth',
        'in_month',
        20,
        60,
        'all',
        location_launched_status=location_launched_status
    )

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

    gender_ignored, age_ignored, chosen_filters = chosen_filters_to_labels(config)

    return {
        "slug": "low_birth",
        "label": "Percent Newborns with Low Birth Weight{}".format(chosen_filters),
        "fills": fills,
        "rightLegend": {
            "average": average,
            "info": _((
                new_born_with_low_weight_help_text(html=True)
            )),
            "extended_info": [
                {
                    'indicator': 'Total Number of Newborns born in given month{}:'.format(chosen_filters),
                    'value': indian_formatted_number(total)
                },
                {
                    'indicator': 'Number of Newborns with LBW in given month{}:'.format(chosen_filters),
                    'value': indian_formatted_number(low_birth_total)
                },
                {
                    'indicator': 'Total Number of children born and weight in given month{}:'.format(
                        chosen_filters
                    ),
                    'value': indian_formatted_number(in_month_total)
                },
                {
                    'indicator': '% newborns with LBW in given month{}:'.format(chosen_filters),
                    'value': '%.2f%%' % (low_birth_total * 100 / float(in_month_total or 1))
                },
                {
                    'indicator': '% of children with weight in normal{}:'.format(chosen_filters),
                    'value': '%.2f%%' % ((in_month_total - low_birth_total) * 100 / float(in_month_total or 1))
                },
                {
                    'indicator': '% Unweighted{}:'.format(chosen_filters),
                    'value': '%.2f%%' % ((total - in_month_total) * 100 / float(total or 1))
                }
            ]

        },
        "data": dict(data_for_map),
    }
Ejemplo n.º 11
0
def get_prevalence_of_severe_sector_data(domain,
                                         config,
                                         loc_level,
                                         location_id,
                                         show_test=False,
                                         icds_feature_flag=False):
    group_by = ['%s_name' % loc_level]

    config['month'] = datetime(*config['month'])
    data = AggChildHealthMonthly.objects.filter(**config).values(
        *group_by).annotate(
            moderate=Sum(wasting_moderate_column(icds_feature_flag)),
            severe=Sum(wasting_severe_column(icds_feature_flag)),
            normal=Sum(wasting_normal_column(icds_feature_flag)),
            total_height_eligible=Sum('height_eligible'),
            total_weighed=Sum('nutrition_status_weighed'),
            total_measured=Sum(
                wfh_recorded_in_month_column(icds_feature_flag)),
        ).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: {
            'severe': 0,
            'moderate': 0,
            'total_height_eligible': 0,
            'normal': 0,
            'total_weighed': 0,
            'total_measured': 0
        })
    if icds_feature_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    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
        total_weighed = row['total_weighed'] or 0
        name = row['%s_name' % loc_level]

        severe = row['severe'] or 0
        moderate = row['moderate'] or 0
        normal = row['normal'] or 0
        total_measured = row['total_measured'] or 0
        total_height_eligible = row['total_height_eligible'] or 0

        tooltips_data[name]['severe'] += severe
        tooltips_data[name]['moderate'] += moderate
        tooltips_data[name]['total_weighed'] += total_weighed
        tooltips_data[name]['normal'] += normal
        tooltips_data[name]['total_measured'] += total_measured
        tooltips_data[name]['total_height_eligible'] += total_height_eligible

        value = (moderate + severe) / float(total_weighed or 1)
        chart_data['blue'].append([name, value])

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

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

    return {
        "tooltips_data":
        dict(tooltips_data),
        "info":
        _(wasting_help_text(age_label)),
        "chart_data": [
            {
                "values": chart_data['blue'],
                "key": "",
                "strokeWidth": 2,
                "classed": "dashed",
                "color": MapColors.BLUE
            },
        ]
    }
Ejemplo n.º 12
0
def get_prevalence_of_severe_data_map(domain,
                                      config,
                                      loc_level,
                                      show_test=False,
                                      icds_feature_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(
                moderate=Sum(wasting_moderate_column(icds_feature_flag)),
                severe=Sum(wasting_severe_column(icds_feature_flag)),
                normal=Sum(wasting_normal_column(icds_feature_flag)),
                total_height_eligible=Sum('height_eligible'),
                total_weighed=Sum('nutrition_status_weighed'),
                total_measured=Sum(
                    wfh_recorded_in_month_column(icds_feature_flag)),
            ).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: {
            'moderate': 0,
            'severe': 0,
            'normal': 0,
            'total_weighed': 0,
            'total_measured': 0,
            'total_height_eligible': 0,
            'original_name': []
        })

    severe_for_all_locations = 0
    moderate_for_all_locations = 0
    normal_for_all_locations = 0
    weighed_for_all_locations = 0
    measured_for_all_locations = 0
    height_eligible_for_all_locations = 0

    values_to_calculate_average = {'numerator': 0, 'denominator': 0}
    if icds_feature_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    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
        total_weighed = row['total_weighed'] or 0
        total_height_eligible = row['total_height_eligible'] or 0
        name = row['%s_name' % loc_level]
        on_map_name = row['%s_map_location_name' % loc_level] or name
        severe = row['severe'] or 0
        moderate = row['moderate'] or 0
        normal = row['normal'] or 0
        total_measured = row['total_measured'] or 0

        values_to_calculate_average['numerator'] += moderate if moderate else 0
        values_to_calculate_average['numerator'] += severe if severe else 0
        values_to_calculate_average[
            'denominator'] += total_measured if total_measured else 0

        severe_for_all_locations += severe
        moderate_for_all_locations += moderate
        normal_for_all_locations += normal
        weighed_for_all_locations += total_weighed
        measured_for_all_locations += total_measured
        height_eligible_for_all_locations += total_height_eligible

        data_for_map[on_map_name]['severe'] += severe
        data_for_map[on_map_name]['moderate'] += moderate
        data_for_map[on_map_name]['normal'] += normal
        data_for_map[on_map_name]['total_weighed'] += total_weighed
        data_for_map[on_map_name]['total_measured'] += total_measured
        data_for_map[on_map_name][
            'total_height_eligible'] += total_height_eligible
        data_for_map[on_map_name]['original_name'].append(name)

    for data_for_location in data_for_map.values():
        numerator = data_for_location['moderate'] + data_for_location['severe']
        value = numerator * 100 / (data_for_location['total_measured'] or 1)
        if value < 5:
            data_for_location.update({'fillKey': '0%-5%'})
        elif 5 <= value <= 7:
            data_for_location.update({'fillKey': '5%-7%'})
        elif value > 7:
            data_for_location.update({'fillKey': '7%-100%'})

    fills = OrderedDict()
    fills.update({'0%-5%': MapColors.PINK})
    fills.update({'5%-7%': MapColors.ORANGE})
    fills.update({'7%-100%': MapColors.RED})
    if icds_feature_flag:
        fills.update({'Not Launched': MapColors.GREY})
    fills.update({'defaultFill': MapColors.GREY})

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

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

    return {
        "slug":
        "severe",
        "label":
        "Percent of Children{gender} Wasted ({age})".format(
            gender=gender_label, age=age_label),
        "fills":
        fills,
        "rightLegend": {
            "average":
            "%.2f" % average,
            "info":
            wasting_help_text(age_label),
            "extended_info": [{
                'indicator':
                'Total Children{} weighed in given month:'.format(
                    chosen_filters),
                'value':
                indian_formatted_number(weighed_for_all_locations)
            }, {
                'indicator':
                'Total Children{} with weight and height measured in given month:'
                .format(chosen_filters),
                'value':
                indian_formatted_number(measured_for_all_locations)
            }, {
                'indicator':
                'Number of children{} unmeasured:'.format(chosen_filters),
                'value':
                indian_formatted_number(height_eligible_for_all_locations -
                                        weighed_for_all_locations)
            }, {
                'indicator':
                '% Severely Acute Malnutrition{}:'.format(chosen_filters),
                'value':
                '%.2f%%' % (severe_for_all_locations * 100 /
                            float(measured_for_all_locations or 1))
            }, {
                'indicator':
                '% Moderately Acute Malnutrition{}:'.format(chosen_filters),
                'value':
                '%.2f%%' % (moderate_for_all_locations * 100 /
                            float(measured_for_all_locations or 1))
            }, {
                'indicator':
                '% Normal{}:'.format(chosen_filters),
                'value':
                '%.2f%%' % (normal_for_all_locations * 100 /
                            float(measured_for_all_locations or 1))
            }]
        },
        "data":
        dict(data_for_map),
    }
Ejemplo n.º 13
0
def get_enrolled_women_data_chart(domain,
                                  config,
                                  loc_level,
                                  show_test=False,
                                  icds_features_flag=False):
    month = datetime(*config['month'])
    three_before = datetime(*config['month']) - relativedelta(months=3)

    config['month__range'] = (three_before, month)
    del config['month']

    chart_data = AggCcsRecordMonthly.objects.filter(**config).values(
        'month', '%s_name' % loc_level).annotate(
            valid=Sum('pregnant'),
            all=Sum('pregnant_all'),
        ).order_by('month')

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

    data = {'blue': OrderedDict()}

    dates = [dt for dt in rrule(MONTHLY, dtstart=three_before, until=month)]

    for date in dates:
        miliseconds = int(date.strftime("%s")) * 1000
        data['blue'][miliseconds] = {'y': 0, 'all': 0}

    best_worst = {}
    if 'month' not in config:
        config['month'] = month
    location_launched_status = get_location_launched_status(config, loc_level)

    for row in chart_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

        date = row['month']
        valid = row['valid'] or 0
        all_pregnant = row['all'] or 0
        location = row['%s_name' % loc_level]

        if date.month == month.month:
            if location in best_worst:
                best_worst[location].append(valid)
            else:
                best_worst[location] = [valid]

        date_in_miliseconds = int(date.strftime("%s")) * 1000

        data['blue'][date_in_miliseconds]['y'] += valid
        data['blue'][date_in_miliseconds]['all'] += all_pregnant

    all_locations = [{
        'loc_name': key,
        'value': sum(value) / len(value)
    } for key, value in best_worst.items()]
    all_locations_sorted_by_name = sorted(all_locations,
                                          key=lambda x: x['loc_name'])
    all_locations_sorted_by_value_and_name = sorted(
        all_locations_sorted_by_name, key=lambda x: x['value'], reverse=True)

    return {
        "chart_data": [{
            "values": [{
                'x': key,
                'y': value['y'],
                'all': value['all']
            } for key, value in data['blue'].items()],
            "key":
            "Total number of pregnant women who are enrolled for Anganwadi Services",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.BLUE
        }],
        "all_locations":
        all_locations_sorted_by_value_and_name,
        "top_five":
        all_locations_sorted_by_value_and_name[:5],
        "bottom_five":
        all_locations_sorted_by_value_and_name[-5:],
        "location_type":
        loc_level.title()
        if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
Ejemplo n.º 14
0
def get_immunization_coverage_data_chart(domain,
                                         config,
                                         loc_level,
                                         show_test=False,
                                         icds_features_flag=False):
    month = datetime(*config['month'])
    three_before = datetime(*config['month']) - relativedelta(months=3)

    config['month__range'] = (three_before, month)
    # Retrieving children of age 1-2 years
    config['age_tranche__lte'] = '24'
    del config['month']
    # using child health monthly while querying for sector level due to performance issues
    if config['aggregation_level'] >= AggregationLevels.SUPERVISOR:
        chm_filter = get_filters_from_config_for_chart_view(config)
        chm_queryset = ChildHealthMonthlyView.objects.filter(**chm_filter)
    else:
        chm_queryset = AggChildHealthMonthly.objects.filter(**config)
    chart_data = chm_queryset.values('month', '%s_name' % loc_level).annotate(
        in_month=Sum('fully_immunized_on_time') + Sum('fully_immunized_late'),
        eligible=Sum('fully_immunized_eligible'),
    ).order_by('month')

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

    data = {
        'blue': OrderedDict(),
    }

    dates = [dt for dt in rrule(MONTHLY, dtstart=three_before, until=month)]

    for date in dates:
        miliseconds = int(date.strftime("%s")) * 1000
        data['blue'][miliseconds] = {'y': 0, 'all': 0, 'in_month': 0}

    best_worst = defaultdict(lambda: {'in_month': 0, 'all': 0})

    if 'month' not in config:
        config['month'] = month
    location_launched_status = get_location_launched_status(config, loc_level)

    for row in chart_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
        date = row['month']
        in_month = row['in_month']
        location = row['%s_name' % loc_level]
        valid = row['eligible']

        best_worst[location]['in_month'] = in_month
        best_worst[location]['all'] = (valid or 0)

        date_in_miliseconds = int(date.strftime("%s")) * 1000
        data_for_month = data['blue'][date_in_miliseconds]

        data_for_month['all'] += valid
        data_for_month['in_month'] += in_month
        data_for_month['y'] = data_for_month['in_month'] / float(
            data_for_month['all'] or 1)

    all_locations = [{
        'loc_name':
        key,
        'percent': (value['in_month'] * 100) / float(value['all'] or 1)
    } for key, value in best_worst.items()]
    all_locations_sorted_by_name = sorted(all_locations,
                                          key=lambda x: x['loc_name'])
    all_locations_sorted_by_percent_and_name = sorted(
        all_locations_sorted_by_name, key=lambda x: x['percent'], reverse=True)
    return {
        "chart_data": [{
            "values": [{
                'x': key,
                'y': value['y'],
                'all': value['all'],
                'in_month': value['in_month']
            } for key, value in data['blue'].items()],
            "key":
            "% Children between 1-2 years old who received complete immunizations by 1 year",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.BLUE
        }],
        "all_locations":
        all_locations_sorted_by_percent_and_name,
        "top_five":
        all_locations_sorted_by_percent_and_name[:5],
        "bottom_five":
        all_locations_sorted_by_percent_and_name[-5:],
        "location_type":
        loc_level.title()
        if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
Ejemplo n.º 15
0
def get_immunization_coverage_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(
            in_month=Sum('fully_immunized_on_time') +
            Sum('fully_immunized_late'),
            eligible=Sum('fully_immunized_eligible'),
        ).order_by('%s_name' % loc_level)

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

    chart_data = {
        'blue': [],
    }

    tooltips_data = defaultdict(lambda: {'children': 0, 'all': 0})

    if icds_features_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    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
        valid = row['eligible']
        name = row['%s_name' % loc_level]

        in_month = row['in_month']

        row_values = {'children': in_month or 0, 'all': valid or 0}
        for prop, value in row_values.items():
            tooltips_data[name][prop] += value

        value = (in_month or 0) / float(valid or 1)
        chart_data['blue'].append([name, value])

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

    return {
        "tooltips_data":
        dict(tooltips_data),
        "info":
        _(("Of the total number of children enrolled for Anganwadi Services who are over a year old, the "
           "percentage of children who have received the complete immunization as per the National Immunization "
           "Schedule of India that is required by age 1."
           "<br/><br/>"
           "This includes the following immunizations:<br/>"
           "If Pentavalent path: Penta1/2/3, OPV1/2/3, BCG, Measles, VitA1<br/>"
           "If DPT/HepB path: DPT1/2/3, HepB1/2/3, OPV1/2/3, BCG, Measles, VitA1"
           )),
        "chart_data": [{
            "values": chart_data['blue'],
            "key": "",
            "strokeWidth": 2,
            "classed": "dashed",
            "color": MapColors.BLUE
        }]
    }
Ejemplo n.º 16
0
def get_immunization_coverage_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(
                children=Sum('fully_immunized_on_time') +
                Sum('fully_immunized_late'),
                all=Sum('fully_immunized_eligible'),
            ).order_by('%s_name' % loc_level,
                       '%s_map_location_name' % loc_level)

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

        return queryset

    if icds_features_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    data_for_map, valid_total, in_month_total, average, total = generate_data_for_map(
        get_data_for(config),
        loc_level,
        'children',
        'all',
        20,
        60,
        location_launched_status=location_launched_status)

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

    gender_ignored, age_ignored, chosen_filters = chosen_filters_to_labels(
        config)

    return {
        "slug": "institutional_deliveries",
        "label":
        "Percent Immunization Coverage at 1 year{}".format(chosen_filters),
        "fills": fills,
        "rightLegend": {
            "average":
            average,
            "info":
            _(("Of the total number of children enrolled for Anganwadi Services who are over a year old, "
               "the percentage of children who have received the complete immunization as per the National "
               "Immunization Schedule of India that is required by age 1."
               "<br/><br/>"
               "This includes the following immunizations:<br/>"
               "If Pentavalent path: Penta1/2/3, OPV1/2/3, BCG, Measles, VitA1<br/>"
               "If DPT/HepB path: DPT1/2/3, HepB1/2/3, OPV1/2/3, BCG, Measles, VitA1"
               )),
            "extended_info": [{
                'indicator':
                'Total number of ICDS Child beneficiaries older than '
                '1 year{}:'.format(chosen_filters),
                'value':
                indian_formatted_number(valid_total)
            }, {
                'indicator':
                ('Total number of children who have recieved complete immunizations required '
                 'by age 1{}:'.format(chosen_filters)),
                'value':
                indian_formatted_number(in_month_total)
            }, {
                'indicator':
                ('% of children who have recieved complete immunizations required by age 1{}:'
                 .format(chosen_filters)),
                'value':
                '%.2f%%' % (in_month_total * 100 / float(valid_total or 1))
            }]
        },
        "data": dict(data_for_map),
    }
Ejemplo n.º 17
0
def get_prevalence_of_stunting_data_chart(domain,
                                          config,
                                          loc_level,
                                          show_test=False,
                                          icds_feature_flag=False):
    month = datetime(*config['month'])
    three_before = datetime(*config['month']) - relativedelta(months=3)

    config['month__range'] = (three_before, month)
    del config['month']

    chart_data = AggChildHealthMonthly.objects.filter(**config).values(
        'month', '%s_name' % loc_level).annotate(
            moderate=Sum(stunting_moderate_column(icds_feature_flag)),
            severe=Sum(stunting_severe_column(icds_feature_flag)),
            normal=Sum(stunting_normal_column(icds_feature_flag)),
            total=Sum('height_eligible'),
            measured=Sum(hfa_recorded_in_month_column(icds_feature_flag)),
        ).order_by('month')

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

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

    data = {
        'red': OrderedDict(),
        'orange': OrderedDict(),
        'peach': OrderedDict()
    }

    dates = [dt for dt in rrule(MONTHLY, dtstart=three_before, until=month)]

    for date in dates:
        miliseconds = int(date.strftime("%s")) * 1000
        data['red'][miliseconds] = {'y': 0, 'all': 0, 'measured': 0}
        data['orange'][miliseconds] = {'y': 0, 'all': 0, 'measured': 0}
        data['peach'][miliseconds] = {'y': 0, 'all': 0, 'measured': 0}

    best_worst = {}
    if icds_feature_flag:
        if 'month' not in config:
            config['month'] = month
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None

    for row in chart_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

        date = row['month']
        total = row['total'] or 0
        measured = row['measured'] or 0
        location = row['%s_name' % loc_level]
        severe = row['severe'] or 0
        moderate = row['moderate'] or 0
        normal = row['normal'] or 0

        underweight = moderate + severe

        best_worst[location] = underweight * 100 / float(measured or 1)

        date_in_miliseconds = int(date.strftime("%s")) * 1000

        data['peach'][date_in_miliseconds]['y'] += normal
        data['peach'][date_in_miliseconds]['measured'] += measured
        data['peach'][date_in_miliseconds]['all'] += total
        data['orange'][date_in_miliseconds]['y'] += moderate
        data['orange'][date_in_miliseconds]['measured'] += measured
        data['orange'][date_in_miliseconds]['all'] += total
        data['red'][date_in_miliseconds]['y'] += severe
        data['red'][date_in_miliseconds]['measured'] += measured
        data['red'][date_in_miliseconds]['all'] += total

    top_locations = sorted([
        dict(loc_name=key, percent=value) for key, value in best_worst.items()
    ],
                           key=lambda x: (x['percent'], x['loc_name']))

    return {
        "chart_data": [{
            "values": [{
                'x': key,
                'y': value['y'] / float(value['measured'] or 1),
                'all': value['all'],
                'measured': value['measured']
            } for key, value in data['peach'].items()],
            "key":
            "% normal",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.PINK
        }, {
            "values": [{
                'x': key,
                'y': value['y'] / float(value['measured'] or 1),
                'all': value['all'],
                'measured': value['measured']
            } for key, value in data['orange'].items()],
            "key":
            "% moderately stunted",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.ORANGE
        }, {
            "values": [{
                'x': key,
                'y': value['y'] / float(value['measured'] or 1),
                'all': value['all'],
                'measured': value['measured']
            } for key, value in data['red'].items()],
            "key":
            "% severely stunted",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.RED
        }],
        "all_locations":
        top_locations,
        "top_five":
        top_locations[:5],
        "bottom_five":
        top_locations[-5:],
        "location_type":
        loc_level.title()
        if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
Ejemplo n.º 18
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)
    }
Ejemplo n.º 19
0
def get_prevalence_of_stunting_data_map(domain,
                                        config,
                                        loc_level,
                                        show_test=False,
                                        icds_feature_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(
                moderate=Sum(stunting_moderate_column(icds_feature_flag)),
                severe=Sum(stunting_severe_column(icds_feature_flag)),
                normal=Sum(stunting_normal_column(icds_feature_flag)),
                total=Sum('height_eligible'),
                total_measured=Sum(
                    hfa_recorded_in_month_column(icds_feature_flag)),
            ).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: {
            'moderate': 0,
            'severe': 0,
            'normal': 0,
            'total': 0,
            'total_measured': 0,
            'original_name': []
        })

    moderate_total = 0
    severe_total = 0
    normal_total = 0
    all_total = 0
    measured_total = 0

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

    if icds_feature_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None

    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
        total = row['total'] or 0
        name = row['%s_name' % loc_level]
        on_map_name = row['%s_map_location_name' % loc_level] or name
        severe = row['severe'] or 0
        moderate = row['moderate'] or 0
        normal = row['normal'] or 0
        total_measured = row['total_measured'] or 0

        values_to_calculate_average['numerator'] += moderate if moderate else 0
        values_to_calculate_average['numerator'] += severe if severe else 0
        values_to_calculate_average[
            'denominator'] += total_measured if total_measured else 0

        severe_total += severe
        moderate_total += moderate
        normal_total += normal
        all_total += total
        measured_total += total_measured

        data_for_map[on_map_name]['severe'] += severe
        data_for_map[on_map_name]['moderate'] += moderate
        data_for_map[on_map_name]['normal'] += normal
        data_for_map[on_map_name]['total'] += total
        data_for_map[on_map_name]['total_measured'] += total_measured
        data_for_map[on_map_name]['original_name'].append(name)

    for data_for_location in data_for_map.values():
        numerator = data_for_location['moderate'] + data_for_location['severe']
        value = numerator * 100 / (data_for_location['total_measured'] or 1)
        if value < 25:
            data_for_location.update({'fillKey': '0%-25%'})
        elif 25 <= value < 38:
            data_for_location.update({'fillKey': '25%-38%'})
        elif value >= 38:
            data_for_location.update({'fillKey': '38%-100%'})

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

    gender_label, age_label, chosen_filters = chosen_filters_to_labels(
        config, default_interval=default_age_interval(icds_feature_flag))
    average = ((values_to_calculate_average['numerator'] * 100) /
               float(values_to_calculate_average['denominator'] or 1))

    return {
        "slug":
        "severe",
        "label":
        "Percent of Children{gender} Stunted ({age})".format(
            gender=gender_label, age=age_label),
        "fills":
        fills,
        "rightLegend": {
            "average":
            "%.2f" % average,
            "info":
            _(("Of the children enrolled for Anganwadi services, whose height was measured, the percentage of "
               "children between {} who were moderately/severely stunted in the current month. "
               "<br/><br/>"
               "Stunting is a sign of chronic undernutrition and has long lasting harmful consequences on "
               "the growth of a child".format(age_label))),
            "extended_info": [{
                'indicator':
                'Total Children{} eligible to have height measured:'.format(
                    chosen_filters),
                'value':
                indian_formatted_number(all_total)
            }, {
                'indicator':
                'Total Children{} with height measured in given month:'.format(
                    chosen_filters),
                'value':
                indian_formatted_number(measured_total)
            }, {
                'indicator':
                'Number of Children{} unmeasured:'.format(chosen_filters),
                'value':
                indian_formatted_number(all_total - measured_total)
            }, {
                'indicator':
                '% children{} with severely stunted growth:'.format(
                    chosen_filters),
                'value':
                '%.2f%%' % (severe_total * 100 / float(measured_total or 1))
            }, {
                'indicator':
                '% children{} with moderate stunted growth:'.format(
                    chosen_filters),
                'value':
                '%.2f%%' % (moderate_total * 100 / float(measured_total or 1))
            }, {
                'indicator':
                '% children{} with normal stunted growth:'.format(
                    chosen_filters),
                'value':
                '%.2f%%' % (normal_total * 100 / float(measured_total or 1))
            }]
        },
        "data":
        dict(data_for_map),
    }
Ejemplo n.º 20
0
def get_enrolled_children_data_chart(domain,
                                     config,
                                     loc_level,
                                     show_test=False,
                                     icds_features_flag=False):
    config['month'] = datetime(*config['month'])

    chart_data = AggChildHealthMonthly.objects.filter(**config).values(
        'month', 'age_tranche', '%s_name' % loc_level).annotate(
            valid=Sum('valid_in_month'), ).order_by('month')

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

    chart = OrderedDict()
    chart.update({'0-1 month': 0})
    chart.update({'1-6 months': 0})
    chart.update({'6-12 months': 0})
    chart.update({'1-3 years': 0})
    chart.update({'3-6 years': 0})

    all = 0
    best_worst = {}

    location_launched_status = get_location_launched_status(config, loc_level)

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

        if not row['age_tranche']:
            continue

        age = int(row['age_tranche'])
        valid = row['valid']
        all += valid
        chart[match_age(age)] += valid

        if location in best_worst:
            best_worst[location] += valid
        else:
            best_worst[location] = valid

    return {
        "chart_data": [{
            "values": [{
                'x': key,
                'y': value,
                'all': all
            } for key, value in chart.items()],
            "key":
            "Children (0-6 years) who are enrolled",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.BLUE
        }],
        "location_type":
        loc_level.title()
        if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
Ejemplo n.º 21
0
def get_prevalence_of_stunting_sector_data(domain,
                                           config,
                                           loc_level,
                                           location_id,
                                           show_test=False,
                                           icds_feature_flag=False):
    group_by = ['%s_name' % loc_level]

    config['month'] = datetime(*config['month'])
    data = AggChildHealthMonthly.objects.filter(**config).values(
        *group_by).annotate(
            moderate=Sum(stunting_moderate_column(icds_feature_flag)),
            severe=Sum(stunting_severe_column(icds_feature_flag)),
            normal=Sum(stunting_normal_column(icds_feature_flag)),
            total=Sum('height_eligible'),
            total_measured=Sum(
                hfa_recorded_in_month_column(icds_feature_flag)),
        ).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: {
        'severe': 0,
        'moderate': 0,
        'total': 0,
        'normal': 0,
        'total_measured': 0
    })
    if icds_feature_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    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
        total = row['total'] or 0
        name = row['%s_name' % loc_level]

        severe = row['severe'] or 0
        moderate = row['moderate'] or 0
        normal = row['normal'] or 0
        total_measured = row['total_measured'] or 0

        row_values = {
            'severe': severe,
            'moderate': moderate,
            'total': total,
            'normal': normal,
            'total_measured': total_measured,
        }

        for prop, value in row_values.items():
            tooltips_data[name][prop] += value

        value = (moderate + severe) / float(total_measured or 1)
        chart_data['blue'].append([name, value])

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

    __, __, chosen_filters = chosen_filters_to_labels(
        config, default_interval=default_age_interval(icds_feature_flag))

    return {
        "tooltips_data":
        dict(tooltips_data),
        "info":
        _(("Of the children enrolled for Anganwadi services, whose height was measured, the percentage "
           "of children between {} who were moderately/severely stunted in the current month. "
           "<br/><br/>"
           "Stunting is a sign of chronic undernutrition and has long lasting harmful consequences on "
           "the growth of a child".format(chosen_filters))),
        "chart_data": [
            {
                "values": chart_data['blue'],
                "key": "",
                "strokeWidth": 2,
                "classed": "dashed",
                "color": MapColors.BLUE
            },
        ]
    }
Ejemplo n.º 22
0
def get_exclusive_breastfeeding_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(
                children=Sum('ebf_in_month'),
                all=Sum('ebf_eligible'),
            ).order_by('%s_name' % loc_level,
                       '%s_map_location_name' % loc_level)
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    if icds_features_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    data_for_map, valid_total, in_month_total, average, total = generate_data_for_map(
        get_data_for(config),
        loc_level,
        'children',
        'all',
        20,
        60,
        location_launched_status=location_launched_status)

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

    gender_ignored, age_ignored, chosen_filters = chosen_filters_to_labels(
        config)

    return {
        "slug": "severe",
        "label": "Percent Exclusive Breastfeeding{}".format(chosen_filters),
        "fills": fills,
        "rightLegend": {
            "average":
            average,
            "info":
            exclusive_breastfeeding_help_text(html=True),
            "extended_info": [{
                'indicator':
                'Total number of children between ages 0 - 6 months{}:'.format(
                    chosen_filters),
                'value':
                indian_formatted_number(valid_total)
            }, {
                'indicator':
                ('Total number of children (0-6 months) exclusively breastfed in the given month{}:'
                 .format(chosen_filters)),
                'value':
                indian_formatted_number(in_month_total)
            }, {
                'indicator':
                '% children (0-6 months) exclusively breastfed in the '
                'given month{}:'.format(chosen_filters),
                'value':
                '%.2f%%' % (in_month_total * 100 / float(valid_total or 1))
            }]
        },
        "data": dict(data_for_map),
    }
Ejemplo n.º 23
0
def get_early_initiation_breastfeeding_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(
            birth=Sum('bf_at_birth'),
            in_month=Sum('born_in_month'),
        ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level)

        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    if icds_features_flag:
        location_launched_status = get_location_launched_status(config, loc_level)
    else:
        location_launched_status = None
    data_for_map, in_month_total, birth_total, average, total = generate_data_for_map(
        get_data_for(config),
        loc_level,
        'birth',
        'in_month',
        20,
        60,
        location_launched_status=location_launched_status
    )

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

    gender_ignored, age_ignored, chosen_filters = chosen_filters_to_labels(config)

    return {
        "slug": "early_initiation",
        "label": "Percent Early Initiation of Breastfeeding{}".format(chosen_filters),
        "fills": fills,
        "rightLegend": {
            "average": average,
            "info": early_initiation_breastfeeding_help_text(html=True),
            "extended_info": [
                {
                    'indicator': 'Total Number of Children born in the current month{}:'.format(chosen_filters),
                    'value': indian_formatted_number(in_month_total)
                },
                {
                    'indicator': (
                        'Total Number of Children who were put to the breast within one hour of birth{}:'
                        .format(chosen_filters)
                    ),
                    'value': indian_formatted_number(birth_total)
                },
                {
                    'indicator': '% children who were put to the breast within one hour of '
                                 'birth{}:'.format(chosen_filters),
                    'value': '%.2f%%' % (birth_total * 100 / float(in_month_total or 1))
                }
            ]
        },
        "data": dict(data_for_map),
    }
Ejemplo n.º 24
0
def get_exclusive_breastfeeding_data_chart(domain,
                                           config,
                                           loc_level,
                                           show_test=False,
                                           icds_features_flag=None):
    month = datetime(*config['month'])
    three_before = datetime(*config['month']) - relativedelta(months=3)

    config['month__range'] = (three_before, month)
    del config['month']

    chart_data = AggChildHealthMonthly.objects.filter(**config).values(
        'month', '%s_name' % loc_level).annotate(
            in_month=Sum('ebf_in_month'),
            eligible=Sum('ebf_eligible'),
        ).order_by('month')

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

    data = {
        'blue': OrderedDict(),
    }

    dates = [dt for dt in rrule(MONTHLY, dtstart=three_before, until=month)]

    for date in dates:
        miliseconds = int(date.strftime("%s")) * 1000
        data['blue'][miliseconds] = {'y': 0, 'all': 0, 'in_month': 0}

    best_worst = {}
    if icds_features_flag:
        if 'month' not in config:
            config['month'] = month
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None

    for row in chart_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
        date = row['month']
        in_month = row['in_month']
        location = row['%s_name' % loc_level]
        eligible = row['eligible']

        best_worst[location] = in_month * 100 / float(eligible or 1)

        date_in_miliseconds = int(date.strftime("%s")) * 1000

        data_for_month = data['blue'][date_in_miliseconds]
        data_for_month['in_month'] += in_month
        data_for_month['all'] += eligible
        data_for_month['y'] = data_for_month['in_month'] / float(
            data_for_month['all'] or 1)

    all_locations = [{
        'loc_name': key,
        'percent': value
    } for key, value in best_worst.items()]
    all_locations_sorted_by_name = sorted(all_locations,
                                          key=lambda x: x['loc_name'])
    all_locations_sorted_by_percent_and_name = sorted(
        all_locations_sorted_by_name, key=lambda x: x['percent'], reverse=True)

    return {
        "chart_data": [{
            "values": [{
                'x': key,
                'y': value['y'],
                'all': value['all'],
                'in_month': value['in_month']
            } for key, value in data['blue'].items()],
            "key":
            "% children exclusively breastfed",
            "strokeWidth":
            2,
            "classed":
            "dashed",
            "color":
            ChartColors.BLUE
        }],
        "all_locations":
        all_locations_sorted_by_percent_and_name,
        "top_five":
        all_locations_sorted_by_percent_and_name[:5],
        "bottom_five":
        all_locations_sorted_by_percent_and_name[-5:],
        "location_type":
        loc_level.title()
        if loc_level != LocationTypes.SUPERVISOR else 'Sector'
    }
def get_lactating_enrolled_women_data_map(domain,
                                          config,
                                          loc_level,
                                          show_test=False,
                                          icds_features_flag=False):
    config['month'] = datetime(*config['month'])

    def get_data_for(filters):
        queryset = AggCcsRecordMonthly.objects.filter(**filters).values(
            '%s_name' % loc_level,
            '%s_map_location_name' % loc_level).annotate(
                valid=Sum('lactating'),
                all=Sum('lactating_all'),
            ).order_by('%s_name' % loc_level,
                       '%s_map_location_name' % loc_level)
        if not show_test:
            queryset = apply_exclude(domain, queryset)
        return queryset

    data_for_map = defaultdict(lambda: {
        'valid': 0,
        'all': 0,
        'original_name': [],
        'fillKey': 'Women'
    })
    average = []
    total_valid = 0
    total = 0
    if icds_features_flag:
        location_launched_status = get_location_launched_status(
            config, loc_level)
    else:
        location_launched_status = None
    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
        valid = row['valid'] or 0
        all_lactating = row['all'] or 0
        name = row['%s_name' % loc_level]
        on_map_name = row['%s_map_location_name' % loc_level] or name

        average.append(valid)

        total_valid += valid
        total += all_lactating

        data_for_map[on_map_name]['valid'] += valid
        data_for_map[on_map_name]['all'] += all_lactating
        data_for_map[on_map_name]['original_name'].append(name)

    fills = OrderedDict()
    fills.update({'Women': MapColors.BLUE})
    fills.update({'defaultFill': MapColors.GREY})

    return {
        "slug": "lactating_enrolled_women",
        "label": "",
        "fills": fills,
        "rightLegend": {
            "average":
            '%.2f' % (total_valid * 100 / float(total or 1)),
            "info":
            percent_lactating_women_enrolled_help_text(),
            "extended_info": [{
                'indicator':
                'Number of lactating women who are enrolled for Anganwadi Services:',
                'value': indian_formatted_number(total_valid)
            }, {
                'indicator':
                ('Total number of lactating women who are registered:'),
                'value':
                indian_formatted_number(total)
            }, {
                'indicator':
                ('Percentage of registered lactating women who are enrolled for Anganwadi Services:'
                 ),
                'value':
                '%.2f%%' % (total_valid * 100 / float(total or 1))
            }]
        },
        "data": dict(data_for_map),
    }