def get_enrolled_children_data_chart(domain, config, loc_level, show_test=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 = {} for row in chart_data: 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 six.iteritems(chart) ], "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' }
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
def get_data_for_daily_usage(date, filters): queryset = AggAwcDailyView.objects.filter( date=date, **filters ).values( 'aggregation_level' ).annotate( awcs=Sum('num_launched_awcs'), daily_attendance=Sum('daily_attendance_open') ) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(filters): filters['month'] = datetime(*filters['month']) 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
def get_data(date, filters): queryset = AggLsMonthly.objects.filter( month=date, **filters ).values( "aggregation_level", "awc_visits", "vhnd_observed", "beneficiary_vists", "num_launched_awcs", ) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(filters): queryset = AggAwcDailyView.objects.filter( **filters ).values( *group_by ).annotate( in_day=Sum('daily_attendance_open'), all=Sum('num_launched_awcs'), ).order_by('%s_name' % loc_level) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(filters): filters['month'] = datetime(*filters['month']) queryset = AggAwcMonthly.objects.filter( **filters ).values( '%s_name' % loc_level, '%s_map_location_name' % loc_level ).annotate( household=Sum('cases_household'), ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(filters): filters['month'] = datetime(*filters['month']) queryset = AggAwcMonthly.objects.filter( **filters ).values( '%s_name' % loc_level, '%s_map_location_name' % loc_level ).annotate( in_month=Sum('infra_infant_weighing_scale'), all=Sum('num_awc_infra_last_update'), ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(filters): filters['month'] = datetime(*filters['month']) queryset = AggAwcMonthly.objects.filter( **filters ).values( '%s_name' % loc_level, '%s_map_location_name' % loc_level ).annotate( in_month=Sum(person_has_aadhaar_column(beta)), all=Sum(person_is_beneficiary_column(beta)), ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(filters): filters['month'] = datetime(*filters['month']) queryset = AggAwcMonthly.objects.filter( **filters ).values( '%s_name' % loc_level, '%s_map_location_name' % loc_level ).annotate( valid=Sum('cases_person_adolescent_girls_11_14'), all=Sum('cases_person_adolescent_girls_11_14_all'), ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(filters): filters['month'] = datetime(*filters['month']) 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
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( 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
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( children=Sum('cf_initiation_in_month'), all=Sum('cf_initiation_eligible'), ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
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( 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
def get_data_for(filters): filters['month'] = datetime(*filters['month']) queryset = AggAwcMonthly.objects.filter( **filters ).values( '%s_name' % loc_level, '%s_map_location_name' % loc_level ).annotate( states=Sum('num_launched_states') if level <= 1 else Max('num_launched_states'), districts=Sum('num_launched_districts') if level <= 2 else Max('num_launched_districts'), blocks=Sum('num_launched_blocks') if level <= 3 else Max('num_launched_blocks'), supervisors=Sum('num_launched_supervisors') if level <= 4 else Max('num_launched_supervisors'), awcs=Sum('num_launched_awcs') if level <= 5 else Max('num_launched_awcs'), ).order_by('%s_name' % loc_level, '%s_map_location_name' % loc_level) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(month, filters): queryset = AggAwcMonthly.objects.filter( month=month, **filters ).values( 'aggregation_level' ).annotate( clean_water=Sum('infra_clean_water'), functional_toilet=Sum('infra_functional_toilet'), medicine_kits=Sum('infra_medicine_kits'), infant_scale=Sum('infra_infant_weighing_scale'), adult_scale=Sum('infra_adult_weighing_scale'), sum_last_update=Sum('num_awc_infra_last_update') ) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
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
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( 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.exclude(age_tranche=72) return queryset
def get_data_for_awc_monthly(month, filters): level = filters['aggregation_level'] queryset = AggAwcMonthly.objects.filter( month=month, **filters ).values( 'aggregation_level' ).annotate( states=Sum('num_launched_states') if level <= 1 else Max('num_launched_states'), districts=Sum('num_launched_districts') if level <= 2 else Max('num_launched_districts'), blocks=Sum('num_launched_blocks') if level <= 3 else Max('num_launched_blocks'), supervisors=Sum('num_launched_supervisors') if level <= 4 else Max('num_launched_supervisors'), awc_num_open=Sum('awc_num_open') if level <= 5 else Max('awc_num_open'), awcs=Sum('num_launched_awcs') if level <= 5 else Max('num_launched_awcs'), all_awcs=Sum('num_awcs') if level <= 5 else Max('num_awcs') ) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_data_for(query_class, filters): queryset = query_class.objects.filter( **filters ).values( 'aggregation_level' ).annotate( household=Sum('cases_household'), child_health=Sum('cases_child_health'), child_health_all=Sum('cases_child_health_all'), ccs_pregnant=Sum('cases_ccs_pregnant'), ccs_pregnant_all=Sum('cases_ccs_pregnant_all'), css_lactating=Sum('cases_ccs_lactating'), css_lactating_all=Sum('cases_ccs_lactating_all'), person_adolescent=Sum('cases_person_adolescent_girls_11_14'), person_adolescent_all=Sum('cases_person_adolescent_girls_11_14_all'), person_aadhaar=Sum(person_has_aadhaar_column(beta)), all_persons=Sum(person_is_beneficiary_column(beta)) ) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
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 }, ] }
def get_registered_household_data_chart(domain, config, loc_level, show_test=False): month = datetime(*config['month']) three_before = datetime(*config['month']) - relativedelta(months=3) config['month__range'] = (three_before, month) del config['month'] chart_data = AggAwcMonthly.objects.filter(**config).values( 'month', '%s_name' % loc_level).annotate( household=Sum('cases_household'), ).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 = {} for row in chart_data: date = row['month'] household = (row['household'] or 0) location = row['%s_name' % loc_level] if date.month == (month - relativedelta(months=1)).month: if location in best_worst: best_worst[location].append(household) else: best_worst[location] = [household] date_in_miliseconds = int(date.strftime("%s")) * 1000 data['blue'][date_in_miliseconds]['y'] += household top_locations = sorted([ dict(loc_name=key, value=sum(value) / len(value)) for key, value in best_worst.iteritems() ], key=lambda x: x['value'], reverse=True) return { "chart_data": [{ "values": [{ 'x': key, 'y': value['y'] / float(value['all'] or 1), 'all': value['all'] } for key, value in data['blue'].iteritems()], "key": "Registered Households", "strokeWidth": 2, "classed": "dashed", "color": BLUE }], "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' }
def get_excel_data(self): def _format_report_data(column, value, is_launched): location_names = ['state_name', 'district_name', 'block_name', 'supervisor_name', 'awc_name', 'awc_site_code'] AWC_NOT_LAUNCHED = 'AWC Not Launched' if column in location_names: return value elif not is_launched: return AWC_NOT_LAUNCHED else: return value if value is not None else DATA_NOT_ENTERED filters = {"month": self.month, "aggregation_level": 5} if self.loc_level == 4: filters['supervisor_id'] = self.location order_by = ('awc_name',) elif self.loc_level == 3: filters['block_id'] = self.location order_by = ('supervisor_name', 'awc_name') elif self.loc_level == 2: filters['district_id'] = self.location order_by = ('block_name', 'supervisor_name', 'awc_name') elif self.loc_level == 1: filters['state_id'] = self.location order_by = ('district_name', 'block_name', 'supervisor_name', 'awc_name') else: order_by = ('state_name', 'district_name', 'block_name', 'supervisor_name', 'awc_name') if self.report_type == THR_REPORT_BENEFICIARY_TYPE: headers, data = self.get_beneficiary_wise_data(filters, order_by) elif self.report_type == THR_REPORT_DAY_BENEFICIARY_TYPE: headers, data = self.get_beneficiary_and_days_wise_data(filters, order_by) else: headers, data = self.get_consolidated_data(filters, order_by) #Exclude test states data = apply_exclude(self.domain, data) excel_rows = [headers] for row in data: awc_is_launched = row.get('is_launched') == 'yes' or row.get('num_launched_awcs') == 1 row_data = [_format_report_data(column_name, col_values, awc_is_launched) for column_name, col_values in row.items() if column_name not in ('num_launched_awcs', 'is_launched')] excel_rows.append(row_data) filters = [['Generated at', india_now()]] if self.location: locs = SQLLocation.objects.get(location_id=self.location).get_ancestors(include_self=True) for loc in locs: filters.append([loc.location_type.name.title(), loc.name]) else: filters.append(['Location', 'National']) date = self.month filters.append(['Month', date.strftime("%B")]) filters.append(['Year', date.year]) return [ [ self.title, excel_rows ], [ 'Export Info', filters ] ]
def get_functional_toilet_sector_data(domain, config, loc_level, location_id, show_test=False): group_by = ['%s_name' % loc_level] config['month'] = datetime(*config['month']) data = AggAwcMonthly.objects.filter( **config ).values( *group_by ).annotate( in_month=Sum('infra_functional_toilet'), all=Sum('num_awc_infra_last_update'), ).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, 'all': 0 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: valid = row['all'] name = row['%s_name' % loc_level] result_set.add(name) in_month = row['in_month'] row_values = { 'in_month': in_month or 0, 'all': valid or 0 } for prop, value in six.iteritems(row_values): tooltips_data[name][prop] += value value = (in_month or 0) / float(valid or 1) chart_data['blue'].append([ name, value ]) 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": _(( "Of the AWCs that submitted an Infrastructure Details form, the percentage of AWCs " "that reported having a functional toilet" )), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
def get_functional_toilet_data_chart(domain, config, loc_level, show_test=False): month = datetime(*config['month']) three_before = datetime(*config['month']) - relativedelta(months=3) config['month__range'] = (three_before, month) del config['month'] chart_data = AggAwcMonthly.objects.filter( **config ).values( 'month', '%s_name' % loc_level ).annotate( in_month=Sum('infra_functional_toilet'), all=Sum('num_awc_infra_last_update'), ).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 }) for row in chart_data: date = row['month'] in_month = (row['in_month'] or 0) location = row['%s_name' % loc_level] valid = row['all'] best_worst[location]['in_month'] = in_month best_worst[location]['all'] = (valid or 0) date_in_miliseconds = int(date.strftime("%s")) * 1000 data['blue'][date_in_miliseconds]['all'] += (valid or 0) data['blue'][date_in_miliseconds]['in_month'] += in_month top_locations = sorted( [ dict( loc_name=key, percent=(value['in_month'] * 100) / float(value['all'] or 1) ) for key, value in six.iteritems(best_worst) ], key=lambda x: x['percent'], reverse=True ) return { "chart_data": [ { "values": [ { 'x': key, 'y': value['in_month'] / float(value['all'] or 1), 'in_month': value['in_month'] } for key, value in six.iteritems(data['blue']) ], "key": "Percentage of AWCs that reported having a functional toilet", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.BLUE } ], "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' }
def get_institutional_deliveries_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 = AggCcsRecordMonthly.objects.filter(**config).values( *group_by).annotate( in_month=Sum('institutional_delivery_in_month'), eligible=Sum('delivered_in_month'), ).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": institutional_deliveries_help_text(html=True), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
def get_awcs_covered_sector_data(domain, config, loc_level, location_id, show_test=False): group_by = ['%s_name' % loc_level] config['month'] = datetime(*config['month']) level = config['aggregation_level'] data = AggAwcMonthly.objects.filter(**config).values(*group_by).annotate( states=Sum('num_launched_states') if level <= 1 else Max('num_launched_states'), districts=Sum('num_launched_districts') if level <= 2 else Max('num_launched_districts'), blocks=Sum('num_launched_blocks') if level <= 3 else Max('num_launched_blocks'), supervisors=Sum('num_launched_supervisors') if level <= 4 else Max('num_launched_supervisors'), awcs=Sum('num_launched_awcs') if level <= 5 else Max('num_launched_awcs'), ).order_by('%s_name' % loc_level) if not show_test: data = apply_exclude(domain, data) chart_data = { 'blue': [], } tooltips_data = defaultdict(lambda: { 'districts': 0, 'blocks': 0, 'states': 0, 'supervisors': 0, 'awcs': 0 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: name = row['%s_name' % loc_level] awcs = row['awcs'] or 0 supervisors = row['supervisors'] or 0 blocks = row['blocks'] or 0 districts = row['districts'] or 0 states = row['states'] or 0 result_set.add(name) row_values = { 'awcs': awcs, 'supervisors': supervisors, 'blocks': blocks, 'districts': districts, 'states': states, } for prop, value in six.iteritems(row_values): tooltips_data[name][prop] += (value or 0) for name, value_dict in six.iteritems(tooltips_data): chart_data['blue'].append([name, value_dict['awcs']]) 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']) if level == 1: prop = 'states' elif level == 2: prop = 'districts' elif level == 3: prop = 'blocks' elif level == 4: prop = 'supervisors' else: prop = 'awcs' total_awcs = sum([(x['awcs'] or 0) for x in six.itervalues(tooltips_data)]) total = sum([(x[prop] or 0) for x in six.itervalues(tooltips_data)]) info = _("Total AWCs that have launched ICDS CAS <br />" + "Number of AWCs launched: %d" % total_awcs) if level != 5: info = _("Total AWCs that have launched ICDS CAS <br />" + "Number of AWCs launched: %d <br />" % total_awcs + "Number of %s launched: %d" % (prop.title(), total)) return { "tooltips_data": dict(tooltips_data), "format": "number", "info": info, "chart_data": [{ "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }] }
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_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 = AggChildHealthMonthly.objects.filter(**config).values( 'month', '%s_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('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, 'in_month': 0, 'low_birth': 0, 'all': 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'] or 0 location = row['%s_name' % loc_level] low_birth = row['low_birth'] or 0 all_birth = row['all'] or 0 best_worst[location] = low_birth * 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['low_birth'] += low_birth data_for_month['in_month'] += in_month data_for_month['all'] += all_birth data_for_month['y'] = data_for_month['low_birth'] / float( data_for_month['in_month'] 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']) return { "chart_data": [{ "values": [{ 'x': key, 'y': val['y'], 'in_month': val['in_month'], 'low_birth': val['low_birth'], 'all': val['all'] } for key, val in data['blue'].items()], "key": "% Newborns with Low Birth Weight", "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_immunization_coverage_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( 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 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: valid = row['eligible'] name = row['%s_name' % loc_level] result_set.add(name) in_month = row['in_month'] row_values = { 'children': in_month or 0, 'all': valid or 0 } for prop, value in six.iteritems(row_values): tooltips_data[name][prop] += value value = (in_month or 0) / float(valid or 1) chart_data['blue'].append([ name, value ]) 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": _(( "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 } ] }
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: if icds_feature_flag: data = data.exclude(age_tranche=72) else: data = data.exclude(age_tranche__in=[0, 6, 72]) chart_data = { 'blue': [], } tooltips_data = defaultdict(lambda: { 'severe': 0, 'moderate': 0, 'total_height_eligible': 0, 'normal': 0, 'total_weighed': 0, 'total_measured': 0 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: total_weighed = row['total_weighed'] or 0 name = row['%s_name' % loc_level] result_set.add(name) 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 ]) 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": _(wasting_help_text(icds_feature_flag)), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
def get_adult_weight_scale_sector_data(domain, config, loc_level, location_id, show_test=False): group_by = ['%s_name' % loc_level] config['month'] = datetime(*config['month']) data = AggAwcMonthly.objects.filter( **config ).values( *group_by ).annotate( in_month=Sum('infra_adult_weighing_scale'), all=Sum('num_awc_infra_last_update'), ).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, 'all': 0 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: valid = row['all'] name = row['%s_name' % loc_level] result_set.add(name) in_month = row['in_month'] row_values = { 'in_month': in_month or 0, 'all': valid or 0 } for prop, value in six.iteritems(row_values): tooltips_data[name][prop] += value value = (in_month or 0) / float(valid or 1) chart_data['blue'].append([ name, value ]) 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": awcs_reported_weighing_scale_mother_and_child_help_text(), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE } ] }
def get_awcs_covered_data_chart(domain, config, loc_level, show_test=False): month = datetime(*config['month']) three_before = datetime(*config['month']) - relativedelta(months=3) config['month__range'] = (three_before, month) del config['month'] level = config['aggregation_level'] chart_data = AggAwcMonthly.objects.filter(**config).values( 'month', '%s_name' % loc_level).annotate( awcs=Sum('num_launched_awcs') if level <= 5 else Max('num_launched_awcs'), ).order_by('month') if not show_test: chart_data = apply_exclude(domain, chart_data) data = {'pink': OrderedDict()} dates = [dt for dt in rrule(MONTHLY, dtstart=three_before, until=month)] for date in dates: miliseconds = int(date.strftime("%s")) * 1000 data['pink'][miliseconds] = {'y': 0, 'all': 0} best_worst = {} for row in chart_data: date = row['month'] awcs = (row['awcs'] or 0) location = row['%s_name' % loc_level] if date.month == month.month: if location in best_worst: best_worst[location].append(awcs) else: best_worst[location] = [awcs] date_in_miliseconds = int(date.strftime("%s")) * 1000 data['pink'][date_in_miliseconds]['y'] += awcs top_locations = sorted([ dict(loc_name=key, value=sum(value) / len(value)) for key, value in six.iteritems(best_worst) ], key=lambda x: x['value'], reverse=True) return { "chart_data": [{ "values": [{ 'x': key, 'y': value['y'] / float(value['all'] or 1), 'all': value['all'] } for key, value in six.iteritems(data['pink'])], "key": "Number of AWCs Launched", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.PINK }], "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' }
def get_prevalence_of_severe_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( moderate=Sum('wasting_moderate'), severe=Sum('wasting_severe'), valid=Sum('height_eligible'), normal=Sum('wasting_normal'), total_measured=Sum('weighed_and_height_measured_in_month'), ).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__in=[0, 6, 72]) chart_data = { 'blue': [], } tooltips_data = defaultdict(lambda: { 'severe': 0, 'moderate': 0, 'total': 0, 'normal': 0, 'total_measured': 0 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: valid = row['valid'] name = row['%s_name' % loc_level] result_set.add(name) severe = row['severe'] moderate = row['moderate'] normal = row['normal'] total_measured = row['total_measured'] tooltips_data[name]['severe'] += (severe or 0) tooltips_data[name]['moderate'] += (moderate or 0) tooltips_data[name]['total'] += (valid or 0) tooltips_data[name]['normal'] += normal tooltips_data[name]['total_measured'] += total_measured value = ((moderate or 0) + (severe or 0)) / float(valid or 1) chart_data['blue'].append([ name, value ]) 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": _(( "Percentage of children between 6 - 60 months enrolled for ICDS services with " "weight-for-height below -3 standard deviations of the WHO Child Growth Standards median." "<br/><br/>" "Severe Acute Malnutrition (SAM) or wasting in children is a symptom of acute " "undernutrition usually as a consequence of insufficient food intake or a high " "incidence of infectious diseases." )), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
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'] # using child health monthly while querying for sector level due to performance issues if icds_feature_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( 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' }
def get_early_initiation_breastfeeding_data(domain, config, loc_level, show_test=False): group_by = ['%s_name' % loc_level] if loc_level == LocationTypes.SUPERVISOR: config['aggregation_level'] += 1 group_by.append('%s_name' % LocationTypes.AWC) 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) loc_data = {'green': 0, 'orange': 0, 'red': 0} tmp_name = '' rows_for_location = 0 chart_data = {'green': [], 'orange': [], 'red': []} tooltips_data = defaultdict(lambda: { 'in_month': 0, 'birth': 0, }) for row in data: in_month = row['in_month'] name = row['%s_name' % loc_level] if tmp_name and name != tmp_name: chart_data['green'].append([ tmp_name, (loc_data['green'] / float(rows_for_location or 1)) ]) chart_data['orange'].append([ tmp_name, (loc_data['orange'] / float(rows_for_location or 1)) ]) chart_data['red'].append( [tmp_name, (loc_data['red'] / float(rows_for_location or 1))]) rows_for_location = 0 loc_data = {'green': 0, 'orange': 0, 'red': 0} birth = row['birth'] value = (birth or 0) * 100 / float(in_month or 1) tooltips_data[name]['birth'] += birth tooltips_data[name]['in_month'] += (in_month or 0) if value >= 60.0: loc_data['green'] += 1 elif 20.0 <= value < 60.0: loc_data['orange'] += 1 elif value < 20.0: loc_data['red'] += 1 tmp_name = name rows_for_location += 1 chart_data['green'].append( [tmp_name, (loc_data['green'] / float(rows_for_location or 1))]) chart_data['orange'].append( [tmp_name, (loc_data['orange'] / float(rows_for_location or 1))]) chart_data['red'].append( [tmp_name, (loc_data['red'] / float(rows_for_location or 1))]) return { "tooltips_data": tooltips_data, "chart_data": [{ "values": chart_data['red'], "key": "0%-20%", "strokeWidth": 2, "classed": "dashed", "color": RED }, { "values": chart_data['orange'], "key": "20%-60%", "strokeWidth": 2, "classed": "dashed", "color": ORANGE }, { "values": chart_data['green'], "key": "60%-100%", "strokeWidth": 2, "classed": "dashed", "color": PINK }] }
def get_immunization_coverage_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( 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}) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: valid = row['eligible'] name = row['%s_name' % loc_level] result_set.add(name) in_month = row['in_month'] row_values = {'children': in_month or 0, 'all': valid or 0} for prop, value in six.iteritems(row_values): tooltips_data[name][prop] += value value = (in_month or 0) / float(valid or 1) chart_data['blue'].append([name, value]) 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": _(("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 }] }
def get_institutional_deliveries_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( in_month=Sum('institutional_delivery_in_month'), eligible=Sum('delivered_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, 'in_month': 0} best_worst = defaultdict(lambda: {'in_month': 0, 'all': 0}) 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] 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": "% Institutional deliveries", "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_institutional_deliveries_sector_data(domain, config, loc_level, location_id, show_test=False): group_by = ['%s_name' % loc_level] config['month'] = datetime(*config['month']) data = AggCcsRecordMonthly.objects.filter(**config).values( *group_by).annotate( in_month=Sum('institutional_delivery_in_month'), eligible=Sum('delivered_in_month'), ).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}) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: valid = row['eligible'] name = row['%s_name' % loc_level] result_set.add(name) in_month = row['in_month'] row_values = {'children': in_month or 0, 'all': valid or 0} for prop, value in six.iteritems(row_values): tooltips_data[name][prop] += value value = (in_month or 0) / float(valid or 1) chart_data['blue'].append([name, value]) 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": _(("Percentage of pregnant women who delivered in a public or private medical facility " "in the last month. " "<br/><br/>" "Delivery in medical instituitions is associated with a decrease in maternal mortality rate" )), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
def get_service_delivery_report_data(domain, start, length, order, reversed_order, location_filters, year, month, step, include_test=False): if location_filters.get('aggregation_level') == 1: default_order = 'state_name' elif location_filters.get('aggregation_level') == 2: default_order = 'district_name' elif location_filters.get('aggregation_level') == 3: default_order = 'block_name' elif location_filters.get('aggregation_level') == 4: default_order = 'supervisor_name' else: default_order = 'awc_name' location_fields = [ 'state_name', 'district_name', 'block_name', 'supervisor_name', 'awc_name' ] value_fields = location_fields + [ 'num_launched_awcs', 'valid_visits', 'expected_visits', 'gm_0_3', 'children_0_3', 'num_awcs_conducted_cbe', 'num_awcs_conducted_vhnd', 'thr_21_days', 'thr_25_days', 'thr_eligible', 'lunch_21_days', 'lunch_25_days', 'pse_eligible', 'pse_21_days', 'pse_25_days', 'gm_3_5', 'children_3_5', 'vhnd_conducted' ] data = ServiceDeliveryReportView.objects.filter( month=date(year, month, 1), **location_filters).order_by(default_order).values(*value_fields) if not include_test: data = apply_exclude(domain, data) data_count = data.count() config = { 'data': [], } def should_show_25(): return year >= 2020 and month >= 4 def update_total_row(first_dict, second_dict): for key, value in first_dict.items(): # excluding location and percentage fields if key not in location_fields + [ 'cbe', 'thr', 'pse', 'sn', 'gm', 'home_visits' ]: first_dict[key] = format_data_not_entered_to_zero(first_dict[key]) +\ format_data_not_entered_to_zero(second_dict[key]) return first_dict def get_pw_lw_percents(return_dict, row_data): return_dict['home_visits'] = percent_or_not_entered( row_data['valid_visits'], row_data['expected_visits']) return_dict['gm'] = percent_or_not_entered(row_data['gm_0_3'], row_data['children_0_3']) return_dict['cbe'] = percent_or_not_entered( row_data['num_awcs_conducted_cbe'], row_data['num_launched_awcs']) if should_show_25(): return_dict['thr'] = percent_or_not_entered( row_data['thr_25_days'], row_data['thr_eligible']) else: return_dict['thr'] = percent_or_not_entered( row_data['thr_21_days'], row_data['thr_eligible']) return return_dict def get_children_percents(return_dict, row_data): return_dict['gm'] = percent_or_not_entered(row_data['gm_3_5'], row_data['children_3_5']) if should_show_25(): return_dict['pse'] = percent_or_not_entered( row_data['pse_25_days'], row_data['pse_eligible']) return_dict['sn'] = percent_or_not_entered( row_data['lunch_25_days'], row_data['pse_eligible']) else: return_dict['pse'] = percent_or_not_entered( row_data['pse_21_days'], row_data['pse_eligible']) return_dict['sn'] = percent_or_not_entered( row_data['lunch_21_days'], row_data['pse_eligible']) return return_dict def base_data(row_data): if step == 'pw_lw_children': return_dict = dict( state_name=get_value_or_data_not_entered( row_data, 'state_name'), district_name=get_value_or_data_not_entered( row_data, 'district_name'), block_name=get_value_or_data_not_entered( row_data, 'block_name'), supervisor_name=get_value_or_data_not_entered( row_data, 'supervisor_name'), awc_name=get_value_or_data_not_entered(row_data, 'awc_name'), num_launched_awcs=get_value_or_data_not_entered( row_data, 'num_launched_awcs'), valid_visits=get_value_or_data_not_entered( row_data, 'valid_visits'), expected_visits=get_value_or_data_not_entered( row_data, 'expected_visits'), gm_0_3=get_value_or_data_not_entered(row_data, 'gm_0_3'), children_0_3=get_value_or_data_not_entered( row_data, 'children_0_3'), num_awcs_conducted_cbe=get_value_or_data_not_entered( row_data, 'num_awcs_conducted_cbe'), num_awcs_conducted_vhnd=get_value_or_data_not_entered( row_data, 'num_awcs_conducted_vhnd'), thr_21_days=get_value_or_data_not_entered( row_data, 'thr_21_days'), thr_25_days=get_value_or_data_not_entered( row_data, 'thr_25_days'), thr_eligible=get_value_or_data_not_entered( row_data, 'thr_eligible'), vhnd_conducted=get_value_or_data_not_entered( row_data, 'vhnd_conducted')) return_dict = get_pw_lw_percents(return_dict, row_data) else: return_dict = dict( num_launched_awcs=get_value_or_data_not_entered( row_data, 'num_launched_awcs'), state_name=get_value_or_data_not_entered( row_data, 'state_name'), district_name=get_value_or_data_not_entered( row_data, 'district_name'), block_name=get_value_or_data_not_entered( row_data, 'block_name'), supervisor_name=get_value_or_data_not_entered( row_data, 'supervisor_name'), awc_name=get_value_or_data_not_entered(row_data, 'awc_name'), lunch_21_days=get_value_or_data_not_entered( row_data, 'lunch_21_days'), lunch_25_days=get_value_or_data_not_entered( row_data, 'lunch_25_days'), pse_eligible=get_value_or_data_not_entered( row_data, 'pse_eligible'), pse_21_days=get_value_or_data_not_entered( row_data, 'pse_21_days'), pse_25_days=get_value_or_data_not_entered( row_data, 'pse_25_days'), gm_3_5=get_value_or_data_not_entered(row_data, 'gm_3_5'), children_3_5=get_value_or_data_not_entered( row_data, 'children_3_5')) return_dict = get_children_percents(return_dict, row_data) return return_dict all_row = dict() data_length = len(data) for index, row in enumerate(data): base_row = base_data(row) if not all_row.keys(): all_row = copy.deepcopy(base_row) else: all_row = update_total_row(all_row, base_row) config['data'].append(base_row) if data_length: # setting location params to all for location in location_fields: all_row[location] = 'All' # Calculating percentages for all row if step == 'pw_lw_children': get_pw_lw_percents(all_row, all_row) all_row['cbe_sector_percent'] = percent_or_not_entered( all_row['num_awcs_conducted_cbe'], data_length) all_row['vhnd_sector_value'] = get_value_or_data_not_entered( all_row, 'num_awcs_conducted_vhnd') else: get_children_percents(all_row, all_row) percentage_fields = ('home_visits', 'gm', 'thr', 'sn', 'pse') if order: if order in percentage_fields: config['data'].sort(key=lambda x: float(x[order][:-1] if x[ order] != DATA_NOT_ENTERED else 0), reverse=reversed_order) else: config['data'].sort(key=lambda x: x[order], reverse=reversed_order) config['data'] = config['data'][start:(start + length)] config['data'].insert(0, all_row) config["aggregationLevel"] = location_filters['aggregation_level'] config["recordsTotal"] = data_count config["recordsFiltered"] = data_count return config
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 }) 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 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 }] }
def get_service_delivery_details(domain, start, length, order, reversed_order, location_filters, year, month, step, include_test=False): if location_filters.get('aggregation_level') == 1: default_order = 'state_name' elif location_filters.get('aggregation_level') == 2: default_order = 'district_name' elif location_filters.get('aggregation_level') == 3: default_order = 'block_name' elif location_filters.get('aggregation_level') == 4: default_order = 'supervisor_name' else: default_order = 'awc_name' location_fields = [ 'state_name', 'district_name', 'block_name', 'supervisor_name', 'awc_name' ] count_columns = ['num_launched_awcs'] if step == 'thr': count_columns += [ 'thr_eligible', 'thr_0_days', 'thr_1_7_days', 'thr_8_14_days', 'thr_15_20_days', 'thr_21_24_days', 'thr_25_days' ] elif step == 'cbe': count_columns += [ 'cbe_conducted', 'third_fourth_month_of_pregnancy_count', 'annaprasan_diwas_count', 'suposhan_diwas_count', 'coming_of_age_count', 'public_health_message_count' ] elif step == 'sn': count_columns += [ 'pse_eligible', 'lunch_0_days', 'lunch_1_7_days', 'lunch_8_14_days', 'lunch_15_20_days', 'lunch_21_24_days', 'lunch_25_days' ] elif step == 'pse': count_columns += [ 'pse_eligible', 'pse_0_days', 'pse_1_7_days', 'pse_8_14_days', 'pse_15_20_days', 'pse_21_24_days', 'pse_25_days' ] values = location_fields + count_columns def get_data_for(default_order, values): return ServiceDeliveryReportView.objects.filter(month=date(year, month, 1), **location_filters)\ .order_by(default_order).values(*values) data = get_data_for(default_order, values) if not include_test: data = apply_exclude(domain, data) data_count = data.count() config = { 'data': [], } def update_total_row(first_dict, second_dict): for key, value in first_dict.items(): # excluding location and percentage fields if key in values: first_dict[key] = format_data_not_entered_to_zero(first_dict[key]) +\ format_data_not_entered_to_zero(second_dict[key]) return first_dict def base_data(row_data): base_dict = dict( state_name=get_value_or_data_not_entered(row_data, 'state_name'), district_name=get_value_or_data_not_entered( row_data, 'district_name'), block_name=get_value_or_data_not_entered(row_data, 'block_name'), supervisor_name=get_value_or_data_not_entered( row_data, 'supervisor_name'), awc_name=get_value_or_data_not_entered(row_data, 'awc_name'), num_launched_awcs=get_value_or_data_not_entered( row_data, 'num_launched_awcs')) if step == 'thr': # calculating percents base_dict = _get_pre_percents(base_dict, row_data, 'thr', 'thr') # filling the data fields base_dict = _get_pre_values(base_dict, row_data, 'thr', 'thr') elif step == 'cbe': base_dict['cbe_conducted'] = get_value_or_data_not_entered( row_data, 'cbe_conducted') base_dict['third_fourth_month_of_pregnancy_count'] =\ get_value_or_data_not_entered(row_data, 'third_fourth_month_of_pregnancy_count') base_dict[ 'annaprasan_diwas_count'] = get_value_or_data_not_entered( row_data, 'annaprasan_diwas_count') base_dict['suposhan_diwas_count'] = get_value_or_data_not_entered( row_data, 'suposhan_diwas_count') base_dict['coming_of_age_count'] = get_value_or_data_not_entered( row_data, 'coming_of_age_count') base_dict['public_health_message_count'] =\ get_value_or_data_not_entered(row_data, 'public_health_message_count') elif step == 'sn': base_dict = _get_pre_percents(base_dict, row_data, 'lunch', 'pse') base_dict = _get_pre_values(base_dict, row_data, 'lunch', 'pse') elif step == 'pse': base_dict = _get_pre_percents(base_dict, row_data, 'pse', 'pse') base_dict = _get_pre_values(base_dict, row_data, 'pse', 'pse') return base_dict all_row = dict() data_length = len(data) for index, row in enumerate(data): base_row = base_data(row) if not all_row.keys(): all_row = copy.deepcopy(base_row) else: all_row = update_total_row(all_row, base_row) config['data'].append(base_data(row)) if data_length: # setting location params to all for location in location_fields: all_row[location] = 'All' # Calculating percentages for all row if step == 'thr': all_row = _get_pre_percents(all_row, all_row, 'thr', 'thr') elif step == 'sn': all_row = _get_pre_percents(all_row, all_row, 'lunch', 'pse') elif step == 'pse': all_row = _get_pre_percents(all_row, all_row, 'pse', 'pse') sort_columns = [field + '_val' for field in count_columns] percentage_fields = sort_columns if order: if order in percentage_fields: config['data'].sort(key=lambda x: float(x[order][:-1] if x[ order] != DATA_NOT_ENTERED else 0), reverse=reversed_order) else: config['data'].sort(key=lambda x: x[order], reverse=reversed_order) config['data'] = config['data'][start:(start + length)] config['data'].insert(0, all_row) config["aggregationLevel"] = location_filters['aggregation_level'] config["recordsTotal"] = data_count config["recordsFiltered"] = data_count return config
def get_prevalence_of_stunting_data_chart(domain, config, loc_level, show_test=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'), severe=Sum('stunting_severe'), normal=Sum('stunting_normal'), total=Sum('height_eligible'), measured=Sum('height_measured_in_month'), ).order_by('month') if not show_test: chart_data = apply_exclude(domain, chart_data) if 'age_tranche' not in config: chart_data = chart_data.exclude(age_tranche__in=[0, 6, 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 = {} for row in chart_data: 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 six.iteritems(best_worst)], key=lambda x: x['percent'] ) return { "chart_data": [ { "values": [ { 'x': key, 'y': value['y'] / float(value['measured'] or 1), 'all': value['all'], 'measured': value['measured'] } for key, value in six.iteritems(data['peach']) ], "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 six.iteritems(data['orange']) ], "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 six.iteritems(data['red']) ], "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' }
def get_awc_daily_status_data_chart(domain, config, loc_level, show_test=False): month = datetime(*config['month']) last = datetime(*config['month']) - relativedelta(days=30) config['date__range'] = (last, month) del config['month'] chart_data = AggAwcDailyView.objects.filter( **config ).values( 'date', '%s_name' % loc_level ).annotate( in_day=Sum('daily_attendance_open'), all=Sum('num_launched_awcs'), ).order_by('date') if not show_test: chart_data = apply_exclude(domain, chart_data) data = { 'open_in_day': OrderedDict(), 'launched': OrderedDict() } dates = [dt for dt in rrule(DAILY, dtstart=last, until=month)] for date in dates: miliseconds = int(date.strftime("%s")) * 1000 data['open_in_day'][miliseconds] = {'y': 0, 'all': 0} data['launched'][miliseconds] = {'y': 0, 'all': 0} best_worst = defaultdict(lambda: { 'in_month': 0, 'all': 0 }) for row in chart_data: date = row['date'] in_day = row['in_day'] or 0 location = row['%s_name' % loc_level] valid = row['all'] or 0 if date.month == (month - relativedelta(months=1)).month: best_worst[location]['in_day'] = in_day best_worst[location]['all'] = valid date_in_miliseconds = int(date.strftime("%s")) * 1000 data['open_in_day'][date_in_miliseconds]['y'] += in_day data['launched'][date_in_miliseconds]['y'] += valid top_locations = sorted( [ dict( loc_name=key, value=value['in_day'] ) for key, value in best_worst.iteritems() ], key=lambda x: x['value'], reverse=True ) return { "chart_data": [ { "values": [ { 'x': key, 'y': value['y'], 'all': value['all'] } for key, value in data['launched'].iteritems() ], "key": "Number of AWCs launched", "strokeWidth": 2, "classed": "dashed", "color": PINK }, { "values": [ { 'x': key, 'y': value['y'], 'all': value['all'] } for key, value in data['open_in_day'].iteritems() ], "key": "Total AWCs open yesterday", "strokeWidth": 2, "classed": "dashed", "color": BLUE } ], "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' }
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.exclude(age_tranche=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 = {} for row in chart_data: 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 six.iteritems(best_worst)], 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 six.iteritems(data['peach']) ], "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 six.iteritems(data['orange']) ], "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 six.iteritems(data['red']) ], "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' }
def get_prevalence_of_stunting_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( moderate=Sum('stunting_moderate'), severe=Sum('stunting_severe'), total=Sum('height_eligible'), normal=Sum('stunting_normal'), total_measured=Sum('height_measured_in_month'), ).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__in=[0, 6, 72]) chart_data = { 'blue': [], } tooltips_data = defaultdict(lambda: { 'severe': 0, 'moderate': 0, 'total': 0, 'normal': 0, 'total_measured': 0 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: total = row['total'] or 0 name = row['%s_name' % loc_level] result_set.add(name) 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 six.iteritems(row_values): tooltips_data[name][prop] += value value = (moderate + severe) / float(total_measured or 1) chart_data['blue'].append([ name, value ]) 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']) __, __, chosen_filters = chosen_filters_to_labels(config, default_interval='6 - 60 months') return { "tooltips_data": dict(tooltips_data), "info": _(( "Percentage of children{} enrolled for Anganwadi Services with height-for-age below " "-2Z standard deviations of the WHO Child Growth Standards median." "<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 }, ] }
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.exclude(age_tranche=72) chart_data = { 'blue': [], } tooltips_data = defaultdict(lambda: { 'severe': 0, 'moderate': 0, 'total': 0, 'normal': 0, 'total_measured': 0 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: total = row['total'] or 0 name = row['%s_name' % loc_level] result_set.add(name) 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 six.iteritems(row_values): tooltips_data[name][prop] += value value = (moderate + severe) / float(total_measured or 1) chart_data['blue'].append([ name, value ]) 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']) __, __, 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 }, ] }
def get_prevalence_of_undernutrition_data_chart(domain, config, loc_level, show_test=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( moderately_underweight=Sum( 'nutrition_status_moderately_underweight'), normal=Sum('nutrition_status_normal'), severely_underweight=Sum('nutrition_status_severely_underweight'), valid=Sum('valid_in_month'), ).order_by('month') if not show_test: chart_data = apply_exclude(domain, chart_data) 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, 'all': 0} data['orange'][miliseconds] = {'y': 0, 'all': 0} data['red'][miliseconds] = {'y': 0, 'all': 0} best_worst = {} for row in chart_data: date = row['month'] valid = row['valid'] location = row['%s_name' % loc_level] severely_underweight = row['severely_underweight'] moderately_underweight = row['moderately_underweight'] normal = row['normal'] underweight = ((moderately_underweight or 0) + (severely_underweight or 0)) * 100 / float(valid 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]['all'] += valid data['orange'][date_in_miliseconds]['y'] += moderately_underweight data['orange'][date_in_miliseconds]['all'] += valid data['red'][date_in_miliseconds]['y'] += severely_underweight data['red'][date_in_miliseconds]['all'] += valid top_locations = sorted([ dict(loc_name=key, percent=value) for key, value in best_worst.iteritems() ], key=lambda x: x['percent']) return { "chart_data": [{ "values": [{ 'x': key, 'y': value['y'] / float(value['all'] or 1), 'all': value['all'] } for key, value in data['peach'].iteritems()], "key": "% Normal", "strokeWidth": 2, "classed": "dashed", "color": PINK }, { "values": [{ 'x': key, 'y': value['y'] / float(value['all'] or 1), 'all': value['all'] } for key, value in data['orange'].iteritems()], "key": "% Moderately Underweight (-2 SD)", "strokeWidth": 2, "classed": "dashed", "color": ORANGE }, { "values": [{ 'x': key, 'y': value['y'] / float(value['all'] or 1), 'all': value['all'] } for key, value in data['red'].iteritems()], "key": "% Severely Underweight (-3 SD) ", "strokeWidth": 2, "classed": "dashed", "color": 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' }
def get_adult_weight_scale_data_chart(domain, config, loc_level, show_test=False): month = datetime(*config['month']) three_before = datetime(*config['month']) - relativedelta(months=3) config['month__range'] = (three_before, month) del config['month'] chart_data = AggAwcMonthly.objects.filter( **config ).values( 'month', '%s_name' % loc_level ).annotate( in_month=Sum('infra_adult_weighing_scale'), all=Sum('num_awc_infra_last_update'), ).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 }) for row in chart_data: date = row['month'] in_month = (row['in_month'] or 0) location = row['%s_name' % loc_level] valid = row['all'] best_worst[location]['in_month'] = in_month best_worst[location]['all'] = (valid or 0) date_in_miliseconds = int(date.strftime("%s")) * 1000 data['blue'][date_in_miliseconds]['all'] += (valid or 0) data['blue'][date_in_miliseconds]['in_month'] += in_month top_locations = sorted( [ dict( loc_name=key, percent=(value['in_month'] * 100) / float(value['all'] or 1) ) for key, value in six.iteritems(best_worst) ], key=lambda x: x['percent'], reverse=True ) return { "chart_data": [ { "values": [ { 'x': key, 'y': value['in_month'] / float(value['all'] or 1), 'in_month': value['in_month'] } for key, value in six.iteritems(data['blue']) ], "key": "Percentage of AWCs that reported having a weighing scale for mother and child", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.BLUE } ], "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' }
def get_prevalence_of_undernutrition_sector_data(domain, config, loc_level, 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'), valid=Sum('wer_eligible'), normal=Sum('nutrition_status_normal')).order_by('%s_name' % loc_level) if not show_test: data = apply_exclude(domain, data) chart_data = {'blue': []} tooltips_data = defaultdict( lambda: { 'severely_underweight': 0, 'moderately_underweight': 0, 'total': 0, 'normal': 0 }) for row in data: valid = row['valid'] 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]['total'] += (valid or 0) tooltips_data[name]['normal'] += normal chart_data['blue'].append([ name, ((moderately_underweight or 0) + (severely_underweight or 0)) / float(valid or 1) ]) return { "tooltips_data": dict(tooltips_data), "info": _(("Percentage of children between 0-5 years enrolled for ICDS services with weight-for-age " "less than -2 standard deviations of the WHO Child Growth Standards median. " "<br/><br/>" "Children who are moderately or severely underweight have a higher risk of mortality" )), "chart_data": [{ "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": BLUE }] }
def get_lactating_enrolled_data_chart(domain, config, loc_level, show_test=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('lactating'), all=Sum('lactating_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 = {} for row in chart_data: date = row['month'] valid = row['valid'] or 0 all_lactating = 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_lactating top_locations = sorted( [dict(loc_name=key, value=sum(value) / len(value)) for key, value in six.iteritems(best_worst)], key=lambda x: x['value'], reverse=True ) return { "chart_data": [ { "values": [ { 'x': key, 'y': value['y'], 'all': value['all'] } for key, value in six.iteritems(data['blue']) ], "key": "Total number of lactating women who are enrolled for Anganwadi Services", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.BLUE } ], "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' }
def get_enrolled_women_data_chart(domain, config, loc_level, show_test=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 = {} for row in chart_data: 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' }
def get_lactating_enrolled_women_sector_data(domain, config, loc_level, location_id, show_test=False): group_by = ['%s_name' % loc_level] config['month'] = datetime(*config['month']) data = AggCcsRecordMonthly.objects.filter( **config ).values( *group_by ).annotate( valid=Sum('lactating'), all=Sum('lactating_all') ).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 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: valid = row['valid'] or 0 all_lactating = row['all'] or 0 name = row['%s_name' % loc_level] result_set.add(name) row_values = { 'valid': valid, 'all': all_lactating } for prop, value in six.iteritems(row_values): tooltips_data[name][prop] += value chart_data['blue'].append([ name, valid ]) 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), "format": "number", "info": percent_lactating_women_enrolled_help_text(), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE } ] }
def get_early_initiation_breastfeeding_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( 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, }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: in_month = row['in_month'] name = row['%s_name' % loc_level] result_set.add(name) 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]) 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": early_initiation_breastfeeding_help_text(html=True), "chart_data": [{ "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }] }
def get_children_initiated_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( in_month=Sum('cf_initiation_in_month'), eligible=Sum('cf_initiation_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 }) loc_children = get_child_locations(domain, location_id, show_test) result_set = set() for row in data: valid = row['eligible'] name = row['%s_name' % loc_level] result_set.add(name) in_month = row['in_month'] row_values = { 'children': in_month or 0, 'all': valid or 0 } for prop, value in six.iteritems(row_values): tooltips_data[name][prop] += value value = (in_month or 0) / float(valid or 1) chart_data['blue'].append([ name, value ]) 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": children_initiated_appropriate_complementary_feeding_help_text(html=True), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
def get_early_initiation_breastfeeding_chart(domain, config, loc_level, show_test=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( 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 = {} for row in chart_data: 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) top_locations = sorted([ dict(loc_name=key, percent=val) for key, val in six.iteritems(best_worst) ], 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 six.iteritems(data['blue'])], "key": "% Early Initiation of Breastfeeding", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.BLUE }], "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' }
def get_children_initiated_data_chart(domain, config, loc_level, show_test=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( in_month=Sum('cf_initiation_in_month'), eligible=Sum('cf_initiation_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 }) for row in chart_data: 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['in_month'] += in_month data_for_month['all'] += valid data_for_month['y'] = data_for_month['in_month'] / float(data_for_month['all'] or 1) top_locations = sorted( [ dict( loc_name=key, percent=(value['in_month'] * 100) / float(value['all'] or 1) ) for key, value in six.iteritems(best_worst) ], 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 six.iteritems(data['blue']) ], "key": "% Children began complementary feeding", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.BLUE } ], "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' }
def get_immunization_coverage_data_chart(domain, config, loc_level, show_test=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( 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 }) for row in chart_data: 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) top_locations = sorted( [ dict( loc_name=key, percent=(value['in_month'] * 100) / float(value['all'] or 1) ) for key, value in best_worst.iteritems() ], 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'].iteritems() ], "key": "% Children received complete immunizations by 1 year", "strokeWidth": 2, "classed": "dashed", "color": BLUE } ], "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' }
def get_awc_daily_status_data_chart(domain, config, loc_level, show_test=False): month = datetime(*config['month']) last = datetime(*config['month']) - relativedelta(days=30) config['date__range'] = (last, month) del config['month'] chart_data = AggAwcDailyView.objects.filter( **config ).values( 'date', '%s_name' % loc_level ).annotate( in_day=Sum('daily_attendance_open'), all=Sum('num_launched_awcs'), ).order_by('date') if not show_test: chart_data = apply_exclude(domain, chart_data) data = { 'open_in_day': OrderedDict(), 'launched': OrderedDict() } dates = [dt for dt in rrule(DAILY, dtstart=last, until=month)] for date in dates: miliseconds = int(date.strftime("%s")) * 1000 data['open_in_day'][miliseconds] = {'y': 0, 'all': 0} data['launched'][miliseconds] = {'y': 0, 'all': 0} best_worst = defaultdict(lambda: { 'in_month': 0, 'all': 0 }) for row in chart_data: date = row['date'] in_day = row['in_day'] or 0 location = row['%s_name' % loc_level] valid = row['all'] or 0 if date.month == month.month: best_worst[location]['in_day'] = in_day best_worst[location]['all'] = valid date_in_miliseconds = int(date.strftime("%s")) * 1000 data['open_in_day'][date_in_miliseconds]['y'] += in_day data['launched'][date_in_miliseconds]['y'] += valid top_locations = sorted( [ dict( loc_name=key, percent=value['in_day'] * 100 / value['all'] ) for key, value in six.iteritems(best_worst) ], key=lambda x: x['percent'], reverse=True ) return { "chart_data": [ { "values": [ { 'x': key, 'y': value['y'], 'all': value['all'] } for key, value in six.iteritems(data['launched']) ], "key": "Number of AWCs launched", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.PINK }, { "values": [ { 'x': key, 'y': value['y'], 'all': value['all'] } for key, value in six.iteritems(data['open_in_day']) ], "key": "Total AWCs open", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.BLUE } ], "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' }
def get_immunization_coverage_sector_data(domain, config, loc_level, show_test=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 }) for row in data: 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.iteritems(): tooltips_data[name][prop] += value value = (in_month or 0) / float(valid or 1) chart_data['blue'].append([ name, value ]) return { "tooltips_data": tooltips_data, "info": _(( """ Percentage of children 1 year+ who have recieved complete immunization as per National Immunization Schedule of India required by age 1 """ )), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": BLUE } ] }