当前位置: 首页>>代码示例>>Python>>正文


Python MonthPeriod.from_url_str方法代码示例

本文整理汇总了Python中snisi_core.models.Periods.MonthPeriod.from_url_str方法的典型用法代码示例。如果您正苦于以下问题:Python MonthPeriod.from_url_str方法的具体用法?Python MonthPeriod.from_url_str怎么用?Python MonthPeriod.from_url_str使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在snisi_core.models.Periods.MonthPeriod的用法示例。


在下文中一共展示了MonthPeriod.from_url_str方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        october = MonthPeriod.from_url_str("10-2014")
        november = MonthPeriod.from_url_str("11-2014")
        mopti_csref = Entity.get_or_none("J5C6")

        logger.info("Remove Expected and data for {}".format(october))

        rc_slugs = ['nutrition_monthly_routine',
                    'nutrition_monthly_routine_aggregated',
                    'nut_urenam_monthly_routine',
                    'nut_urenam_monthly_routine_aggregated',
                    'nut_urenas_monthly_routine',
                    'nut_urenas_monthly_routine_aggregated',
                    'nut_ureni_monthly_routine',
                    'nut_ureni_monthly_routine_aggregated',
                    'nut_stocks_monthly_routine',
                    'nut_stocks_monthly_routine_aggregated',
                    'nutrition_weekly_routine',
                    'nutrition_weekly_routine_aggregated']

        for rc_slug in rc_slugs:
            rc = ReportClass.get_or_none(rc_slug)

            logger.info("Deleting expecteds")
            ExpectedReporting.objects.filter(
                report_class=rc,
                period__end_on__lte=october.end_on).delete()

            logger.info("Deleting reports and expected validations")
            rqs = rc.report_class.objects.filter(
                period__end_on__lte=october.end_on)
            for r in rqs:
                logger.info("\treport: {}".format(r))
                if r.expected_reportings.count():
                    logger.info("\tfound exp")
                    r.expected_reportings.all().delete()
                if r.expected_validation:
                    logger.info("\tfound expval")
                    r.expected_validation.delete()
                logger.info("\tdeleting report.")
                r.delete()

        logger.info("Updating Mopti CSRef")
        mopti_csref.has_urenam = False
        mopti_csref.has_urenas = False
        mopti_csref.save()

        logger.info("Removing Mopti CSRef Expected")
        ExpectedReporting.objects.filter(
            entity__slug=mopti_csref.slug,
            report_class__slug__in=['nut_urenam_monthly_routine',
                                    'nut_urenam_monthly_routine_aggregated',
                                    'nut_urenas_monthly_routine',
                                    'nut_urenas_monthly_routine_aggregated'],
            period=november).delete()

        logger.info("done.")
开发者ID:yeleman,项目名称:snisi,代码行数:60,代码来源:fix_mopti_ureni_and_october.py

示例2: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        start = MonthPeriod.from_url_str('12-2014').start_on
        end = MonthPeriod.from_url_str('01-2015').end_on

        bads = ExpectedReporting.objects.filter(
            period__start_on__gte=start,
            period__end_on__lte=end,
            completion_status='')
        logger.info("DELETING {} bads".format(bads.count()))
        bads.delete()

        for exp in ExpectedReporting.objects.filter(
                period__start_on__gte=start,
                period__end_on__lte=end,
                completion_status=ExpectedReporting.COMPLETION_MISSING):

            # logger.info(exp)

            params = {
                'report_class': exp.report_class,
                'reporting_role': exp.reporting_role,

                'period': exp.period,
                'within_period': exp.within_period,

                'entity': exp.entity,
                'within_entity': exp.within_entity,

                'reporting_period': exp.reporting_period,
                'extended_reporting_period': exp.extended_reporting_period,

                'amount_expected': exp.amount_expected,

                'completion_status__in': (
                    ExpectedReporting.COMPLETION_COMPLETE,
                    ExpectedReporting.COMPLETION_MATCHING),
            }

            filter = ExpectedReporting.objects.filter(**params)

            if not filter.count():
                # no duplicates on this one.
                logger.info("... No duplicate")
                continue

            good = filter.get()

            if not exp.satisfied and not exp.arrived_reports.count():
                logger.info(". DELETING exp: {}".format(exp))
                exp.delete()
            else:
                logger.info("CAN'T DELETE EXP as satisfied: {}".format(exp))
                logger.info(good)
开发者ID:yeleman,项目名称:snisi,代码行数:56,代码来源:fix_double_expected.py

示例3: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        epidemio_cluster = Cluster.objects.get(slug="epidemiology_routine")
        DEBUG_change_system_date(
            MonthPeriod.from_url_str("07-2012").end_on
            - datetime.timedelta(days=5), True)

        mali = Entity.get_or_none("mali")

        regions = ['2732']

        health_units = [mali]
        for region_slug in regions:
            region = Entity.get_or_none(region_slug)
            health_units += [region] + region.get_health_districts() \
                                     + region.get_health_centers()

        for health_unit in health_units:
            logger.info(health_unit)

            p, created = Participation.objects.get_or_create(
                cluster=epidemio_cluster,
                entity=health_unit,
                modified_on=timezone.now())

        DEBUG_change_system_date(None, True)
开发者ID:yeleman,项目名称:snisi,代码行数:28,代码来源:epidemiology_create_cluster.py

示例4: dashboard

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
def dashboard(request, **kwargs):

    now = timezone.now()
    last_period = MonthPeriod.current().previous() if now.day < 26 else None
    periods = MonthPeriod.all_from(
        MonthPeriod.from_url_str("11-2014"), last_period)
    entity = request.user.location.casted()

    context = {
        'periods': periods,
        'entity': entity,
    }

    if entity.has_ureni or entity.has_urenas:
        context.update({
            'sam_performance': SAMPerformanceTable(entity=entity,
                                                   periods=periods)
        })
    if entity.has_urenam:
        context.update({
            'mam_performance': MAMPerformanceTable(entity=entity,
                                                   periods=periods)
        })

    return render(request, kwargs.get('template_name',
                  'nutrition/dashboard.html'), context)
开发者ID:yeleman,项目名称:snisi,代码行数:28,代码来源:indicators.py

示例5: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        logger.info("Issue #67. Removing expecteds for djenne entities.")

        january = MonthPeriod.from_url_str("12-2014")
        periods = MonthPeriod.all_from(january)
        entity_slugs = ['ANT9', 'M894', 'C332']

        for exp in ExpectedReporting.objects.filter(
                period__in=periods, entity__slug__in=entity_slugs):
            logger.debug(exp)
            exp.delete()

        logger.info("Disable health area if not already")
        for slug in entity_slugs:
            area_slug = "Z{}".format(slug)
            e = Entity.objects.get(slug=area_slug)
            if e and e.active:
                logger.info(e)
                e.active = False
                e.save()

        logger.info("Remove from clusters")
        Participation.objects.filter(entity__slug__in=entity_slugs).delete()

        logger.info("Update cluster cache")
        call_command("update-cluster-caches")

        logger.info("done.")
开发者ID:yeleman,项目名称:snisi,代码行数:31,代码来源:fix_67_rm_expecteds.py

示例6: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        period = MonthPeriod.from_url_str("11-2014")

        for report in AggMalariaR.objects.filter(period=period):
            logger.info(report)
            report.update_expected_reportings_number()
            report.save()

        logger.info("All done.")
开发者ID:yeleman,项目名称:snisi,代码行数:12,代码来源:fix_malaria_nb_exp_nov14.py

示例7: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        logger.info("Issue #74. Wrong counts in Agg meta (reg #61)")

        november = MonthPeriod.from_url_str("11-2014")

        for report in SNISIReport.objects.filter(period=november):
            report = report.casted()
            if not hasattr(report, 'update_expected_reportings_number'):
                continue

            logger.info(".{}".format(report))
            report.update_expected_reportings_number()

        logger.info("done.")
开发者ID:yeleman,项目名称:snisi,代码行数:17,代码来源:fix_74_meta_numbers.py

示例8: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        msi_cluster = Cluster.objects.get(slug="msi_reprohealth_routine")
        msi_cluster_sms = \
            Cluster.objects.get(slug="msi_reprohealth_routine_sms")
        DEBUG_change_system_date(
            MonthPeriod.from_url_str("08-2012").end_on
            - datetime.timedelta(days=5), True)

        headers = ['SNISI', 'Name', 'Type']
        input_file = open(options.get('input_file'), 'r')
        csv_reader = csv.DictReader(input_file, fieldnames=headers)

        if options.get('clear'):
            Participation.objects.filter(
                cluster__in=[msi_cluster, msi_cluster_sms]).delete()

        for entry in csv_reader:
            if csv_reader.line_num == 1:
                continue

            health_unit = Entity.get_or_none(entry.get('SNISI'))
            if health_unit is None:
                continue

            logger.info(health_unit)

            p, created = Participation.objects.get_or_create(
                cluster=msi_cluster,
                entity=health_unit,
                modified_on=timezone.now())
            p, created = Participation.objects.get_or_create(
                cluster=msi_cluster_sms,
                entity=health_unit,
                modified_on=timezone.now())

        DEBUG_change_system_date(None, True)
开发者ID:yeleman,项目名称:snisi,代码行数:39,代码来源:snisi_reprohealth_create_cluster.py

示例9: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        period = MonthPeriod.from_url_str("11-2014")

        logger.info(NutritionR.objects.filter(period=period).count())

        ok_slugs = [r['entity']
                    for r in
                    NutritionR.objects.filter(period=period).values('entity')]

        for r in URENAMNutritionR.objects.filter(period=period):
            if r.entity.slug not in ok_slugs:
                logger.debug(r)
                exp = ExpectedReporting.objects.get(
                    report_class__slug='nut_urenam_monthly_routine',
                    period=period,
                    entity__slug=r.entity.slug)
                exp.arrived_reports.remove(r)
                exp.completion_status = exp.COMPLETION_MISSING
                exp.save()
                exp.updated_on = timezone.now()

                try:
                    expv = ExpectedValidation.objects.get(report=r)
                    expv.delete()
                except:
                    pass

                r.delete()

        for r in URENASNutritionR.objects.filter(period=period):
            if r.entity.slug not in ok_slugs:
                logger.debug(r)
                exp = ExpectedReporting.objects.get(
                    report_class__slug='nut_urenas_monthly_routine',
                    period=period,
                    entity__slug=r.entity.slug)
                exp.arrived_reports.remove(r)
                exp.completion_status = exp.COMPLETION_MISSING
                exp.save()
                exp.updated_on = timezone.now()

                try:
                    expv = ExpectedValidation.objects.get(report=r)
                    expv.delete()
                except:
                    pass

                r.delete()

        for r in URENINutritionR.objects.filter(period=period):
            if r.entity.slug not in ok_slugs:
                logger.debug(r)
                exp = ExpectedReporting.objects.get(
                    report_class__slug='nut_ureni_monthly_routine',
                    period=period,
                    entity__slug=r.entity.slug)
                exp.arrived_reports.remove(r)
                exp.completion_status = exp.COMPLETION_MISSING
                exp.save()
                exp.updated_on = timezone.now()

                try:
                    expv = ExpectedValidation.objects.get(report=r)
                    expv.delete()
                except:
                    pass

                r.delete()

        for r in NutritionStocksR.objects.filter(period=period):
            if r.entity.slug not in ok_slugs:
                logger.debug(r)
                exp = ExpectedReporting.objects.get(
                    report_class__slug='nut_stocks_monthly_routine',
                    period=period,
                    entity__slug=r.entity.slug)
                exp.arrived_reports.remove(r)
                exp.completion_status = exp.COMPLETION_MISSING
                exp.save()
                exp.updated_on = timezone.now()

                try:
                    expv = ExpectedValidation.objects.get(report=r)
                    expv.delete()
                except:
                    pass

                r.delete()

        logger.info(NutritionR.objects.filter(period=period).count())
开发者ID:yeleman,项目名称:snisi,代码行数:93,代码来源:fix_bankass_nut.py

示例10: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        # delete all reports from koulikoro
        kkr = Entity.get_or_none("4JN7")

        for report in list(PFActivitiesR.objects.all()) + \
                list(AggPFActivitiesR.objects.all()):
            if report.entity.get_health_region() == kkr:
                logger.info(report)
                report.delete()

        # delete all reports from August
        before_october = [MonthPeriod.from_url_str("08-2014"),
                          MonthPeriod.from_url_str("09-2014")]
        PFActivitiesR.objects.filter(period__in=before_october).delete()

        # delete all Expected from August
        ExpectedReporting.objects.filter(
            period__in=before_october,
            report_class__slug__in=["msi_pf_monthly_routine",
                                    "msi_pf_monthly_routine_aggregated"]) \
            .delete()

        # delete all aggregated
        AggPFActivitiesR.objects.all().delete()

        # delete september and october tasks
        for slug in ['reprohealth_10-2014_end_of_region_period',
                     'reprohealth_10-2014_end_of_district_period',
                     'reprohealth_09-2014_end_of_region_period',
                     'reprohealth_09-2014_end_of_district_period']:
            try:
                p = PeriodicTask.objects.get(slug=slug)
            except:
                continue
            logger.info(p)
            p.delete()

        # add missing entities to cluster
        districts = [Entity.get_or_none(s) for s in
                     [u'W6D2', u'RN42', u'YF98', u'8GK0', u'HFD9',
                      u'ZWT5', u'D2K8', u'N696', u'8R92', u'MJ86', u'5B40']]

        mali = Entity.get_or_none("mali")
        segou = Entity.get_or_none("2732")
        mopti = Entity.get_or_none("SSH3")
        bko = Entity.get_or_none("9GR8")
        entities = [mali] + districts + [mopti, segou, kkr]
        cluster = Cluster.get_or_none("msi_reprohealth_routine")
        for entity in entities:
            if entity is None:
                continue

            p, created = Participation.objects.get_or_create(
                cluster=cluster,
                entity=entity,
                is_active=True)
            if created:
                logger.info(p)

        # remove bamako region from cluster
        try:
            Participation.objects.get(cluster=cluster, entity=bko).delete()
        except Participation.DoesNotExist:
            pass
开发者ID:yeleman,项目名称:snisi,代码行数:67,代码来源:fix_reprohealth_nov.py

示例11: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        autobot = Provider.get_or_none('autobot')
        reportcls_slug = "malaria_monthly_routine_aggregated"
        rclass = ReportClass.get_or_none(reportcls_slug)
        charge_sis = Role.get_or_none("charge_sis")
        first_period = MonthPeriod.from_url_str(
            options.get('start_period') if options.get('start_period')
            else "09-2011")
        last_period = MonthPeriod.from_url_str(
            options.get('end_period') if options.get('end_period')
            else "03-2014")
        first_period_mopti_district = MonthPeriod.from_url_str("09-2013")
        first_period_mopti_region = MonthPeriod.from_url_str("01-2014")
        mali = Entity.get_or_none("mali")

        def entity_expected_for(entity, period, region_level=False):
            if period > last_period:
                return False

            if entity is mali:
                return period >= first_period

            region = entity.get_health_region()

            if region.slug in ('9GR8', '2732'):
                return period >= first_period
            elif region.slug == 'SSH3':
                if region_level:
                    return period >= first_period_mopti_district
                if entity.slug == 'HFD9':
                    return period >= first_period_mopti_district
                else:
                    return period >= first_period_mopti_region
            else:
                return False

        # remove old ones if requested
        if options.get('clear'):
            ExpectedReporting.objects.filter(
                report_class__slug=reportcls_slug).delete()
            receipts = [r.receipt for r in AggMalariaR.objects.all()]
            AggMalariaR.objects.filter(receipt__in=receipts)
            SNISIReport.objects.filter(receipt__in=receipts).delete()
            ExpectedValidation.objects.filter(
                report__receipt__in=receipts).delete()

        cluster = Cluster.get_or_none("malaria_monthly_routine")
        periods = MonthPeriod.all_from(first_period, last_period)
        districts = [e for e in cluster.members()
                     if e.type.slug == 'health_district']
        regions = [e for e in cluster.members()
                   if e.type.slug == 'health_region']

        # loop on periods
        for period in periods:

            reporting_period = period.following()
            logger.info("Switching to {}".format(period))

            region_validation_period = DefaultRegionValidationPeriod \
                .find_create_by_date(reporting_period.middle())

            # change date to beginning
            DEBUG_change_system_date(reporting_period.start_on, True)

            # loop on all districts/region/country
            for entity in districts + regions + [mali]:
                if not entity_expected_for(
                        entity, period, entity.type.slug == 'health_region'):
                    continue

                logger.info("\tCreating for {}".format(entity))

                # create expected reporting
                ExpectedReporting.objects.create(
                    report_class=rclass,
                    reporting_role=charge_sis if entity is not mali else None,
                    period=period,
                    within_period=False,
                    entity=entity,
                    within_entity=False,
                    amount_expected=ExpectedReporting.EXPECTED_SINGLE,
                    completion_status=ExpectedReporting.COMPLETION_MISSING)

            # change date to 16
            district_date = datetime.datetime(
                reporting_period.start_on.year,
                reporting_period.start_on.month,
                16, 8, 0).replace(tzinfo=timezone.utc)
            DEBUG_change_system_date(district_date, True)

            # loop on all districts
            for district in districts:
                if not entity_expected_for(district, period):
                    continue

                logger.info("\tAt district {}".format(district))

                # auto-validate non-validated reports
#.........这里部分代码省略.........
开发者ID:yeleman,项目名称:snisi,代码行数:103,代码来源:regen_malaria_agg_reports.py

示例12: import

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
from __future__ import (unicode_literals, absolute_import,
                        division, print_function)
import datetime
import logging

from django.core.management.base import BaseCommand
from django.utils import timezone

from snisi_core.models.Entities import Entity
from snisi_core.models.Periods import MonthPeriod
from snisi_core.models.Projects import Cluster, Participation
from snisi_tools.datetime import DEBUG_change_system_date

logger = logging.getLogger(__name__)

speriod = MonthPeriod.from_url_str("01-2013")
eperiod = MonthPeriod.from_url_str("12-2013")
periods = MonthPeriod.all_from(speriod, eperiod)


class Command(BaseCommand):

    def handle(self, *args, **options):

        coverage_cluster = Cluster.objects.get(slug="vacc_coverage_routine")
        DEBUG_change_system_date(
            MonthPeriod.from_url_str("12-2012").end_on
            - datetime.timedelta(days=5), True)

        mali = Entity.get_or_none("mali")
开发者ID:yeleman,项目名称:snisi,代码行数:32,代码来源:vacc_create_cluster.py

示例13: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
    def handle(self, *args, **options):

        speriod = MonthPeriod.from_url_str("01-2013")
        eperiod = MonthPeriod.from_url_str("12-2013")
        periods = MonthPeriod.all_from(speriod, eperiod)

        autobot = Provider.get_or_none("autobot")

        for period in periods:

            for entity_slug in ['ACE3', 'KTE4', '3ZF3']:

                entity = Entity.get_or_none(entity_slug)

                if entity_slug == 'ACE3' and period.middle().month >= 10:
                    continue

                if entity_slug == 'KTE4' and period.middle().month >= 9:
                    continue

                day_periods = DayPeriod.objects.filter(
                    start_on__gte=period.start_on,
                    end_on__lte=period.end_on)
                day_reports = EpidemioMalariaR.objects.filter(
                    period__in=day_periods,
                    entity=entity)

                # change date to begining of period
                DEBUG_change_system_date(period.start_on, True)

                # create expected if not exist
                eo = ExpectedReporting.objects.get(
                    period=period, entity__slug='S5C4')
                expected_reporting = eo.clone(
                    save=True,
                    entity=entity,
                    completion_status=ExpectedReporting.COMPLETION_MISSING)

                DEBUG_change_system_date(
                    period.start_on + timedelta(days=1), True)

                provider = Provider.objects.get(
                    location=entity, role__slug='dtc')
                report = MalariaR.start(
                    period=period,
                    entity=entity,
                    created_by=provider,
                    arrival_status=MalariaR.ON_TIME)

                def sum_days(fields):
                    fields = [fields] \
                        if not isinstance(fields, (tuple, list)) else fields
                    return sum([sum([getattr(r, field, 0)
                                for r in day_reports for field in fields])])

                report.fill_blank()

                report.add_underfive_data(
                    total_consultation_all_causes=sum_days(
                        'u5_total_consultation_all_causes'),
                    total_suspected_malaria_cases=sum_days(
                        'u5_total_suspected_malaria_cases'),
                    total_simple_malaria_cases=sum_days(
                        'u5_total_simple_malaria_cases'),
                    total_severe_malaria_cases=sum_days(
                        'u5_total_severe_malaria_cases'),
                    total_tested_malaria_cases=sum_days(
                        ['u5_total_rdt_tested_malaria_cases',
                         'u5_total_ts_tested_malaria_cases']),
                    total_confirmed_malaria_cases=sum_days(
                        ['u5_total_rdt_confirmed_malaria_cases',
                         'u5_total_ts_confirmed_malaria_cases']),
                    total_treated_malaria_cases=0,
                    total_inpatient_all_causes=0,
                    total_malaria_inpatient=0,
                    total_death_all_causes=sum_days(
                        'u5_total_death_all_causes'),
                    total_malaria_death=sum_days(
                        'u5_total_malaria_death'),
                    total_distributed_bednets=0)
                report.add_overfive_data(
                    total_consultation_all_causes=sum_days(
                        'o5_total_consultation_all_causes'),
                    total_suspected_malaria_cases=sum_days(
                        'o5_total_suspected_malaria_cases'),
                    total_simple_malaria_cases=sum_days(
                        'o5_total_simple_malaria_cases'),
                    total_severe_malaria_cases=sum_days(
                        'o5_total_severe_malaria_cases'),
                    total_tested_malaria_cases=sum_days(
                        ['o5_total_rdt_tested_malaria_cases',
                         'o5_total_ts_tested_malaria_cases']),
                    total_confirmed_malaria_cases=sum_days(
                        ['o5_total_rdt_confirmed_malaria_cases',
                         'o5_total_ts_confirmed_malaria_cases']),
                    total_treated_malaria_cases=0,
                    total_inpatient_all_causes=0,
                    total_malaria_inpatient=0,
                    total_death_all_causes=sum_days(
                        'o5_total_death_all_causes'),
#.........这里部分代码省略.........
开发者ID:yeleman,项目名称:snisi,代码行数:103,代码来源:fix_1_mopti_reports_validation.py

示例14: geojson_indicator

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
def geojson_indicator(request):

    feature_list = {
        "type": "FeatureCollection",
        "crs": {"type": "name",
                "properties": {
                    "name": "urn:ogc:def:crs:OGC:1.3:CRS84"}},
        "properties": {},
        "features": []
    }

    try:
        json_request = json.loads(request.body)
    except Exception as e:
        return HttpResponse(json.dumps({"error": e}))

    project_slug = json_request.get('project_slug')
    target_level = json_request.get('level')
    # display_hc = json_request.get('display_hc')
    indicator_slug = json_request.get('indicator_slug')
    timing = json_request.get('timing')  # single_period | evolution

    period_slug_a = json_request.get('period_a')
    period_a = MonthPeriod.from_url_str(period_slug_a)

    period_slug_b = json_request.get('period_b')
    if period_slug_b:
        period_b = MonthPeriod.from_url_str(period_slug_b)
    else:
        period_b = None

    domain = Domain.get_or_none(project_slug)
    indicator = domain.import_from('indicators.{}'.format(indicator_slug))

    for entity in HealthEntity.objects.filter(type__slug=target_level):

        if timing == 'single_period':
            indicator_instance = indicator(period=period_a, entity=entity)
            indicator_value_a = indicator_instance.data
            indicator_value_b = None

            indicator_value = indicator_value_a
        else:
            indicator_instance_a = indicator(period=period_a, entity=entity)
            indicator_instance_b = indicator(period=period_b, entity=entity)
            indicator_value_a = indicator_instance_a.data
            indicator_value_b = indicator_instance_b.data
            indicator_value = indicator_value_a - indicator_value_b

        entity_feature = {
            "type": "Feature",
            "properties": {
                "indicator_value_a": indicator_value_a,
                "indicator_value_b": indicator_value_b,
                "indicator_value": indicator_value,
                "indicator_value_human": indicator_instance.human(),
            }
        }
        entity_feature['properties'].update(entity.to_dict())

        if entity.geojson:
            entity_feature.update({"geometry": entity.geojson})

        feature_list['features'].append(entity_feature)

    indicator_values = list(set([v['properties']['indicator_value']
                                 for v in feature_list['features']]))
    try:
        indicator_values.remove(None)
    except:
        pass
    feature_list['properties'].update({
        "indicator_value_min": min(indicator_values),
        "indicator_value_max": max(indicator_values),
        "indicator_slug": indicator.spec()['slug'],
        "indicator_name": indicator.spec()['name']})

    return HttpResponse(json.dumps(feature_list),
                        content_type='application/json')
开发者ID:yeleman,项目名称:snisi,代码行数:81,代码来源:indicators_api.py

示例15: dashboard

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import from_url_str [as 别名]
def dashboard(request, **kwargs):

    now = timezone.now()
    last_period = MonthPeriod.current().previous() if now.day < 26 else None
    if now.day < 10:
        last_period = last_period.previous()
    periods = MonthPeriod.all_from(
        MonthPeriod.from_url_str("11-2014"), last_period)
    entity = request.user.location.casted()

    fwp = NutWeekPeriod.find_create_by_date(datetime.datetime(2014, 12, 1))
    lwp = NutWeekPeriod.find_create_by_date(datetime.datetime(2015, 6, 26))
    wperiods = NutWeekPeriod.all_from(fwp, lwp)

    imatrix = OrderedDict([
        ('promptitude', TableauPromptitudeRapportage),
        ('promptitude_graph', FigurePromptitudeRapportage),
        ('w_promptitude', WeekTableauPromptitudeRapportage),
        ('w_promptitude_graph', WeekFigurePromptitudeRapportage),
    ])

    gp = lambda s: wperiods if s.startswith('w_') else periods

    sm_indics = {slug: icls(entity=entity, periods=gp(slug))
                 for slug, icls in imatrix.items()}

    def pc(a, b):
        try:
            return b / a
        except ZeroDivisionError:
            return 0

    mopti = Entity.get_or_none("SSH3")
    nb_hc = len(mopti.get_health_centers())
    nb_months = len(periods)
    nb_exp = nb_hc * nb_months
    nb_received = NutritionR.objects.all().count()
    nb_received_it = NutritionR.objects.filter(
        arrival_status=NutritionR.ON_TIME).count()
    # nb_stock = len([1 for r in NutritionStocksR.objects.all()
    #                 if r.has_stockout()])
    nb_stock_thera = len([1 for r in NutritionStocksR.objects.all()
                          if r.has_therapeutic_stockout()])
    nb_stock_drug = len([1 for r in NutritionStocksR.objects.all()
                         if r.has_drug_stockout()])

    nb_weeks = len(wperiods)
    nb_expw = nb_hc * nb_weeks
    nb_receivedw = WeeklyNutritionR.objects.all().count()
    nb_received_itw = WeeklyNutritionR.objects.filter(
        arrival_status=WeeklyNutritionR.ON_TIME).count()

    ds_received = [(ds.name,
                    pc(len(ds.get_health_centers()) * nb_months,
                       NutritionR.objects.filter(
                        entity__slug__in=[hc.slug
                                          for hc in ds.get_health_centers()])
                       .count()))
                   for ds in mopti.get_health_districts()]

    ds_auto_val = [(ds.name,
                    pc(len(ds.get_health_centers()) * nb_months,
                       NutritionR.objects.filter(
                        entity__slug__in=[hc.slug
                                          for hc in ds.get_health_centers()],
                        auto_validated=False)
                       .count()))
                   for ds in mopti.get_health_districts()]

    nb_hc_100 = len([hc for hc in mopti.get_health_centers()
                     if NutritionR.objects.filter(entity__slug=hc.slug)
                                  .count() == nb_months])

    overall_table = OrderedDict([
        ("Nombre de centres", nb_hc),
        ("Nombre de mois", nb_months),
        ("Nombre de rapports attendus", nb_exp),
        ("Nombre de rapports reçus", nb_received),
        ("Taux de complétude moyen", pc(nb_exp, nb_received)),
        ("Nombre de rapports reçus à temps", nb_received_it),
        ("Taux de promptitude moyen", pc(nb_exp, nb_received_it)),

        ("Nombre de semaines", nb_weeks),
        ("Nombre de rapports hebdo attendus", nb_expw),
        ("Nombre de rapports hebdo reçus", nb_receivedw),
        ("Taux de complétude hebdo moyen", pc(nb_expw, nb_receivedw)),
        ("Nombre de rapports hebdo reçus à temps", nb_received_itw),
        ("Taux de promptitude hebdo moyen", pc(nb_expw, nb_received_itw)),

        ("Nombre de rapports avec de mauvais indicateurs de performances", 0),
        ("Pourcentage de mauvais indicateurs de performances", 0),
        ("Classement du rapportage (complétude) par DS", "-"),
    ])
    for idx, dsdd in enumerate(sorted(ds_received,
                                      key=lambda x: x[1], reverse=True)):
        overall_table.update({
            "nº {} – DS de {}".format(idx + 1, dsdd[0]): dsdd[1]})

    overall_table.update({"Taux de rapports validés par les districts": "-"})
    for idx, dsdd in enumerate(sorted(ds_auto_val,
#.........这里部分代码省略.........
开发者ID:yeleman,项目名称:snisi,代码行数:103,代码来源:small_indicators.py


注:本文中的snisi_core.models.Periods.MonthPeriod.from_url_str方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。