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": _(("Percentage of children between 6 - 8 months given timely introduction to solid, " "semi-solid or soft food.")), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
def get_lactating_enrolled_data_chart(domain, config, loc_level, show_test=False, icds_features_flag=False): month = datetime(*config['month']) three_before = datetime(*config['month']) - relativedelta(months=3) config['month__range'] = (three_before, month) del config['month'] chart_data = AggCcsRecordMonthly.objects.filter( **config ).values( 'month', '%s_name' % loc_level ).annotate( valid=Sum('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 = {} if 'month' not in config: config['month'] = month location_launched_status = get_location_launched_status(config, loc_level) for row in chart_data: launched_status = location_launched_status.get(row['%s_name' % loc_level]) if launched_status is None or launched_status <= 0: continue 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 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 lactating 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_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": awcs_reported_functional_toilet_help_text(), "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: data = data.exclude(age_tranche=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']) gender_label, age_label, chosen_filters = chosen_filters_to_labels( config, default_interval=default_age_interval(icds_feature_flag)) return { "tooltips_data": dict(tooltips_data), "info": _(wasting_help_text(age_label)), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
def get_infants_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_infant_weighing_scale'), all=Sum( Case(When(Q(infra_last_update_date=None), then=1), default=0, output_field=IntegerField())), ).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 infants", "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_newborn_with_low_birth_weight_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( low_birth=Sum('low_birth_weight_in_month'), 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, 'low_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) 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 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": _(("Percentage of newborns with born with birth weight less than 2500 grams." "<br/><br/>" "Newborns with Low Birth Weight are closely associated with foetal and neonatal " "mortality and morbidity, inhibited growth and cognitive development, and chronic " "diseases later in life")), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }
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_data_for_child_health_monthly(date, filters): age_filters = {'age_tranche': 72} moderately_underweight = include_records_by_age_for_column( {'age_tranche__lt': 72}, 'nutrition_status_moderately_underweight' ) severely_underweight = include_records_by_age_for_column( {'age_tranche__lt': 72}, 'nutrition_status_severely_underweight' ) wasting_moderate = include_records_by_age_for_column( {'age_tranche__lt': 72}, wasting_moderate_column(icds_feature_flag) ) wasting_severe = include_records_by_age_for_column( {'age_tranche__lt': 72}, wasting_severe_column(icds_feature_flag) ) stunting_moderate = include_records_by_age_for_column( {'age_tranche__lt': 72}, stunting_moderate_column(icds_feature_flag) ) stunting_severe = include_records_by_age_for_column( {'age_tranche__lt': 72}, stunting_severe_column(icds_feature_flag) ) nutrition_status_weighed = include_records_by_age_for_column( {'age_tranche__lt': 72}, 'nutrition_status_weighed' ) height_measured_in_month = include_records_by_age_for_column( {'age_tranche__lt': 72}, hfa_recorded_in_month_column(icds_feature_flag) ) weighed_and_height_measured_in_month = include_records_by_age_for_column( {'age_tranche__lt': 72}, wfh_recorded_in_month_column(icds_feature_flag) ) queryset = AggChildHealthMonthly.objects.filter( month=date, **filters ).values( 'aggregation_level' ).annotate( underweight=( Sum(moderately_underweight) + Sum(severely_underweight) ), valid=Sum(nutrition_status_weighed), wasting=Sum(wasting_moderate) + Sum(wasting_severe), stunting=Sum(stunting_moderate) + Sum(stunting_severe), height_measured_in_month=Sum(height_measured_in_month), weighed_and_height_measured_in_month=Sum(weighed_and_height_measured_in_month), low_birth_weight=Sum('low_birth_weight_in_month'), bf_birth=Sum('bf_at_birth'), born=Sum('born_in_month'), weighed_and_born_in_month=Sum('weighed_and_born_in_month'), ebf=Sum('ebf_in_month'), ebf_eli=Sum('ebf_eligible'), cf_initiation=Sum('cf_initiation_in_month'), cf_initiation_eli=Sum('cf_initiation_eligible') ) if not show_test: queryset = apply_exclude(domain, queryset) return queryset
def get_logs_sum(self): return self.issuelog_set.aggregate(Sum('cost'))['cost__sum'] or 0
def get_uploaded(self): versions = Version.objects.filter(backup__owner=self.user) torrents = map(lambda x:x.torrent,versions) peers = Peer.objects.filter(torrent__in=torrents,user__not=self.user) return peers.aggregate(Sum('downloaded'))['downloaded__sum']
def range_statistics(start, end): """ Returns the statistics (totals) for a target date. Its month will be used. """ return DayStatistics.objects.filter(day__gte=start, day__lt=end).aggregate( total_cost=Sum('total_cost'), electricity1=Sum('electricity1'), electricity1_cost=Sum('electricity1_cost'), electricity1_returned=Sum('electricity1_returned'), electricity2=Sum('electricity2'), electricity2_cost=Sum('electricity2_cost'), electricity2_returned=Sum('electricity2_returned'), electricity_merged=Sum(models.F('electricity1') + models.F('electricity2')), electricity_cost_merged=Sum(models.F('electricity1_cost') + models.F('electricity2_cost')), electricity_returned_merged=Sum(models.F('electricity1_returned') + models.F('electricity2_returned')), gas=Sum('gas'), gas_cost=Sum('gas_cost'), temperature_min=Min('lowest_temperature'), temperature_max=Max('highest_temperature'), temperature_avg=Avg('average_temperature'), )
def get_downloaded(self): contentType = ContentType.objects.get(model='version') peers = Peer.objects.filter(user=self.user,torrent__content_type=contentType) return peers.aggregate(Sum('downloaded'))['downloaded__sum']
def generate_person_list_with_class_register_statistics( self: Group, persons: Optional[Iterable] = None) -> QuerySet: """Get with class register statistics annotated list of all members.""" if persons is None: persons = self.members.all() lesson_periods = LessonPeriod.objects.filter( lesson__validity__school_term=self.school_term).filter( Q(lesson__groups=self) | Q(lesson__groups__parent_groups=self)) extra_lessons = ExtraLesson.objects.filter( school_term=self.school_term).filter( Q(groups=self) | Q(groups__parent_groups=self)) events = Event.objects.filter(school_term=self.school_term).filter( Q(groups=self) | Q(groups__parent_groups=self)) persons = persons.select_related("primary_group", "primary_group__school_term").order_by( "last_name", "first_name") persons = persons.annotate(filtered_personal_notes=FilteredRelation( "personal_notes", condition=(Q(personal_notes__event__in=events) | Q(personal_notes__lesson_period__in=lesson_periods) | Q(personal_notes__extra_lesson__in=extra_lessons)), )).annotate( absences_count=Count( "filtered_personal_notes", filter=Q(filtered_personal_notes__absent=True), ), excused=Count( "filtered_personal_notes", filter=Q( filtered_personal_notes__absent=True, filtered_personal_notes__excused=True, filtered_personal_notes__excuse_type__isnull=True, ), ), unexcused=Count( "filtered_personal_notes", filter=Q(filtered_personal_notes__absent=True, filtered_personal_notes__excused=False), ), tardiness=Sum("filtered_personal_notes__late"), tardiness_count=Count( "filtered_personal_notes", filter=Q(filtered_personal_notes__late__gt=0), ), ) for extra_mark in ExtraMark.objects.all(): persons = persons.annotate( **{ extra_mark.count_label: Count( "filtered_personal_notes", filter=Q(filtered_personal_notes__extra_marks=extra_mark), ) }) for excuse_type in ExcuseType.objects.all(): persons = persons.annotate( **{ excuse_type.count_label: Count( "filtered_personal_notes__absent", filter=Q( filtered_personal_notes__absent=True, filtered_personal_notes__excuse_type=excuse_type, ), ) }) return persons
def get_context_data(self, **kwargs): context = super(CheckListView, self).get_context_data(**kwargs) context["outstanding"] = Check.objects.filter(deposit_date=None).aggregate( total=Sum("amount") )["total"] return context
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 calculate_estimation_sum(self): return self.issue_set.exclude(status=Issue.CLOSED).aggregate( Sum('estimation'))['estimation__sum'] or 0
def get_medicine_kit_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_medicine_kits'), 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 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['in_month'] / float(value['all'] or 1), 'in_month': value['in_month'] } for key, value in data['blue'].items() ], "key": "Percentage of AWCs that reported having a Medicine Kit", "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 test_empty_group_by_cols(self): window = Window(expression=Sum('pk')) self.assertEqual(window.get_group_by_cols(), []) self.assertFalse(window.contains_aggregate)
def get_newborn_with_low_birth_weight_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( low_birth=Sum('low_birth_weight_in_month'), 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, 'low_birth': 0} best_worst = {} for row in chart_data: date = row['month'] in_month = row['in_month'] location = row['%s_name' % loc_level] low_birth = row['low_birth'] best_worst[location] = (low_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['low_birth'] += low_birth data_for_month['all'] += in_month data_for_month['y'] = data_for_month['low_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']) return { "chart_data": [{ "values": [{ 'x': key, 'y': val['y'], 'all': val['all'], 'low_birth': val['low_birth'] } for key, val in six.iteritems(data['blue'])], "key": "% Newborns with Low Birth Weight", "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 test_invalid_order_by(self): msg = 'order_by must be either an Expression or a sequence of expressions' with self.assertRaisesMessage(ValueError, msg): Window(expression=Sum('power'), order_by='-horse')
def get_prevalence_of_severe_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(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('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, 'total_weighed': 0, 'total_measured': 0, 'total_height_eligible': 0 } data['orange'][miliseconds] = { 'y': 0, 'total_weighed': 0, 'total_measured': 0, 'total_height_eligible': 0 } data['peach'][miliseconds] = { 'y': 0, 'total_weighed': 0, 'total_measured': 0, 'total_height_eligible': 0 } best_worst = {} for row in chart_data: date = row['month'] total_weighed = row['total_weighed'] or 0 total_measured = row['total_measured'] or 0 total_height_eligible = row['total_height_eligible'] 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(total_measured or 1) date_in_miliseconds = int(date.strftime("%s")) * 1000 data['peach'][date_in_miliseconds]['y'] += normal data['peach'][date_in_miliseconds]['total_weighed'] += total_weighed data['peach'][date_in_miliseconds]['total_measured'] += total_measured data['peach'][date_in_miliseconds][ 'total_height_eligible'] += total_height_eligible data['orange'][date_in_miliseconds]['y'] += moderate data['orange'][date_in_miliseconds]['total_weighed'] += total_weighed data['orange'][date_in_miliseconds]['total_measured'] += total_measured data['orange'][date_in_miliseconds][ 'total_height_eligible'] += total_height_eligible data['red'][date_in_miliseconds]['y'] += severe data['red'][date_in_miliseconds]['total_weighed'] += total_weighed data['red'][date_in_miliseconds]['total_measured'] += total_measured data['red'][date_in_miliseconds][ 'total_height_eligible'] += total_height_eligible 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['total_measured'] or 1), 'total_weighed': value['total_weighed'], 'total_measured': value['total_measured'], 'total_height_eligible': value['total_height_eligible'] } 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['total_measured'] or 1), 'total_weighed': value['total_weighed'], 'total_measured': value['total_measured'], 'total_height_eligible': value['total_height_eligible'] } for key, value in six.iteritems(data['orange'])], "key": "% moderately wasted (moderate acute malnutrition)", "strokeWidth": 2, "classed": "dashed", "color": ChartColors.ORANGE }, { "values": [{ 'x': key, 'y': value['y'] / float(value['total_measured'] or 1), 'total_weighed': value['total_weighed'], 'total_measured': value['total_measured'], 'total_height_eligible': value['total_height_eligible'] } for key, value in six.iteritems(data['red'])], "key": "% severely wasted (severe acute malnutrition)", "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_lactating_enrolled_women_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( 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 }) location_launched_status = get_location_launched_status(config, loc_level) for row in data: if location_launched_status: launched_status = location_launched_status.get(row['%s_name' % loc_level]) if launched_status is None or launched_status <= 0: continue valid = row['valid'] or 0 all_lactating = row['all'] or 0 name = row['%s_name' % loc_level] row_values = { 'valid': valid, 'all': all_lactating } for prop, value in row_values.items(): tooltips_data[name][prop] += value chart_data['blue'].append([ name, valid ]) chart_data['blue'] = sorted(chart_data['blue']) return { "tooltips_data": dict(tooltips_data), "format": "number", "info": percent_lactating_women_enrolled_help_text(), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE } ] }
def payment_history(request): user = request.user if request.user.is_staff: user_id = request.REQUEST.get('user_id', request.user.pk) user = User.objects.get(pk=user_id) history = PaymentHistory.objects.filter(user=user) statistics = { "created_date": user.date_joined, "last_seen_date": user.profile.last_seen_on, "last_seen_ip": user.profile.last_seen_ip, "timezone": unicode(user.profile.timezone), "stripe_id": user.profile.stripe_id, "paypal_email": user.profile.latest_paypal_email, "profile": user.profile, "feeds": UserSubscription.objects.filter(user=user).count(), "email": user.email, "read_story_count": RUserStory.read_story_count(user.pk), "feed_opens": UserSubscription.objects.filter(user=user).aggregate( sum=Sum('feed_opens'))['sum'], "training": { 'title_ps': MClassifierTitle.objects.filter(user_id=user.pk, score__gt=0).count(), 'title_ng': MClassifierTitle.objects.filter(user_id=user.pk, score__lt=0).count(), 'tag_ps': MClassifierTag.objects.filter(user_id=user.pk, score__gt=0).count(), 'tag_ng': MClassifierTag.objects.filter(user_id=user.pk, score__lt=0).count(), 'author_ps': MClassifierAuthor.objects.filter(user_id=user.pk, score__gt=0).count(), 'author_ng': MClassifierAuthor.objects.filter(user_id=user.pk, score__lt=0).count(), 'feed_ps': MClassifierFeed.objects.filter(user_id=user.pk, score__gt=0).count(), 'feed_ng': MClassifierFeed.objects.filter(user_id=user.pk, score__lt=0).count(), } } return { 'is_premium': user.profile.is_premium, 'premium_expire': user.profile.premium_expire, 'payments': history, 'statistics': statistics, }
def get_infants_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_infant_weighing_scale'), all=Sum( Case(When(Q(infra_last_update_date=None), then=1), default=0, output_field=IntegerField())), ).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": _(("Percentage of AWCs that reported having a weighing scale for infants" )), "chart_data": [ { "values": chart_data['blue'], "key": "", "strokeWidth": 2, "classed": "dashed", "color": MapColors.BLUE }, ] }