Beispiel #1
0
def stable_consumption_check():
    builder = DefinitionFactory().blank().type(FACILITY_TWO_GROUPS_WITH_SAMPLE)
    thresholds = {
        Tracer.F1().key: 20,
        Tracer.F2().key: 10,
        Tracer.F3().key: 10
    }
    builder.add_group(
        "G1",
        SUM,
        CURRENT_CYCLE,
        CONSUMPTION_MODEL,
        ["consumption"],
        [],
        thresholds=thresholds,
    )
    builder.add_group(
        "G2",
        SUM,
        PREVIOUS_CYCLE,
        CONSUMPTION_MODEL,
        ["consumption"],
        [],
        thresholds=thresholds,
    )
    builder.percentage_variance_is_less_than(50)
    return builder.get()
Beispiel #2
0
 def __init__(self):
     self.test = CONSUMPTION_AND_PATIENTS
     self.combinations = [
         Tracer.F1().with_data(
             {RATIO: 2.0, FIELDS: [COMBINED_CONSUMPTION], IS_ADULT: True}
         ),
         Tracer.F2().with_data(
             {RATIO: 4.6, FIELDS: [COMBINED_CONSUMPTION], IS_ADULT: False}
         ),
         Tracer.F3().with_data(
             {RATIO: 1.0, FIELDS: [COMBINED_CONSUMPTION], IS_ADULT: False}
         ),
     ]
Beispiel #3
0
 def test_that_aar_passes(self):
     aar = {
         "Current": LocationData.migrate_from_dict(
             {
                 "status": "reporting",
                 A_RECORDS: [
                     {FORMULATION: "TDF/3TC/EFV (PMTCT)", "new": 0.0},
                     {FORMULATION: "TDF/3TC/EFV (PMTCT)", "existing": 7.0},
                     {FORMULATION: "TDF/3TC/EFV (ADULT)", "new": 2.0},
                     {FORMULATION: "TDF/3TC/EFV (ADULT)", "existing": 68.0},
                 ],
             }
         ),
         "Previous": LocationData.migrate_from_dict(
             {
                 "status": "reporting",
                 A_RECORDS: [
                     {FORMULATION: "TDF/3TC/EFV (PMTCT)", "new": 0.0},
                     {FORMULATION: "TDF/3TC/EFV (PMTCT)", "existing": 7.0},
                     {FORMULATION: "TDF/3TC/EFV (ADULT)", "new": 2.0},
                     {FORMULATION: "TDF/3TC/EFV (ADULT)", "existing": 68.0},
                 ],
             }
         ),
     }
     new_check = get_check_from_dict(stable_patients_check())
     new_check_result = new_check.for_each_facility(
         aar["Current"], Tracer.F1(), aar["Previous"]
     )
     self.assertEqual("YES", new_check_result)
Beispiel #4
0
    def get(self, request):
        formulation = request.GET.get("formulation", Tracer.F1().key)
        cycle = request.GET.get("cycle", None)
        test_names = [
            test[0] for test in FacilityTest.objects.values_list("name")
        ]
        response = HttpResponse(content_type="text/csv")
        response[
            "Content-Disposition"] = 'attachment; filename="facilitytable-%s-%s.csv"' % (
                cycle, formulation)
        writer = csv.writer(response)
        columns = ["Facility", "District", "Warehouse", "IP"]
        writer.writerow(columns + test_names)
        filter = {"cycle": cycle}
        if self.request.user:
            if self.request.user.access_level and self.request.user.access_area:
                filter[self.request.user.access_level.lower(
                )] = self.request.user.access_area
        for score in Score.objects.filter(**filter).order_by("name"):
            row = [score.name, score.district, score.warehouse, score.ip]
            for c in test_names:
                value = score.data.get(c)
                if type(value) is dict:
                    if DEFAULT in value:
                        row.append(self.parse_value(value.get(DEFAULT)))
                    else:
                        row.append(self.parse_value(value.get(formulation)))
                else:
                    row.append(value)
            writer.writerow(row)

        return response
 def test_that_locations_for_traced_checks_shows_up(self):
     definition = stable_patients_check()
     url = "/api/tests/preview/locations"
     formulations = Tracer.F1().patient_formulations
     gen_adult_record(formulation=formulations[0])
     gen_adult_record(name="loc2", formulation=formulations[1])
     response = self.app.post_json(url, user="******", params=definition)
     json_response = response.content.decode("utf8")
     self.assertEqual(200, response.status_code)
     locations = loads(json_response).get("locations", [])
     self.assertEqual(2, len(locations))
     assert_that(
         locations,
         has_item(
             has_entries({
                 "name": equal_to("loc1"),
                 "district": equal_to("dis1"),
                 "cycles": equal_to(["cycle1"]),
             })),
     )
     assert_that(
         locations,
         has_item(
             has_entries({
                 "name": equal_to("loc2"),
                 "district": equal_to("dis1"),
                 "cycles": equal_to(["cycle1"]),
             })),
     )
Beispiel #6
0
 def test_is_above_threshold(self):
     group = DefinitionGroup(
         name="G2",
         model=None,
         cycle="",
         selected_fields=["consumption"],
         selected_formulations=[],
         sample_formulation_model_overridden={},
         sample_formulation_model_overrides={},
         aggregation=sum_comparison,
         has_factors=None,
         factors=None,
         has_thresholds=True,
         thresholds={
             u"abc3tc-paed": 10, u"efv200-paed": 10, u"tdf3tcefv-adult": "200"
         },
     )
     result = GroupResult(
         group=group,
         values=None,
         factored_records=[],
         aggregate=500.0,
         tracer=Tracer.F1(),
     )
     self.assertEqual(result.is_above_threshold(), True)
 def test_check(self, name, data1, data2, expected):
     new_check = get_check_from_dict(non_repeating_check())
     new_check_result = new_check.for_each_facility(data1, Tracer.F1(),
                                                    data2)
     self.assertEqual(expected, new_check_result)
     check = OrdersOverTimeCheck()
     result = check.for_each_facility(data1, check.combinations[0], data2)
     self.assertEqual(expected, result)
Beispiel #8
0
 def test_f2(self, name, data, expected):
     new_check = get_check_from_dict(volume_tally_check())
     new_check_result = new_check.for_each_facility(data, Tracer.F2())
     self.assertEqual(expected, new_check_result)
     legacy_check = VolumeTallyCheck()
     legacy_check_result = legacy_check.for_each_facility(
         data, legacy_check.combinations[1])
     self.assertEqual(expected, legacy_check_result)
     self.assertEqual(legacy_check_result, new_check_result)
Beispiel #9
0
 def test_view_loads(self):
     name = "F1"
     warehouse = "W1"
     ip = "I1"
     district = "D1"
     cycle = "Jan - Feb 2015"
     score = Score.objects.create(
         name=name,
         warehouse=warehouse,
         ip=ip,
         district=district,
         data={"REPORTING": {
             DEFAULT: YES
         }},
         cycle=cycle,
     )
     for q in F1_PATIENT_QUERY:
         mommy.make(
             AdultPatientsRecord,
             name=name,
             warehouse=warehouse,
             ip=ip,
             district=district,
             cycle=cycle,
             formulation=q,
             new=random.randrange(0, 600),
             existing=random.randrange(0, 600),
         )
         mommy.make(
             PAEDPatientsRecord,
             name=name,
             warehouse=warehouse,
             ip=ip,
             district=district,
             cycle=cycle,
             formulation=q,
             new=random.randrange(0, 600),
             existing=random.randrange(0, 600),
         )
     for formulation in self.get_formulations():
         values = generate_values()
         mommy.make(Consumption,
                    name=name,
                    warehouse=warehouse,
                    ip=ip,
                    district=district,
                    cycle=cycle,
                    formulation=formulation,
                    **values)
     url = reverse("scores-detail",
                   kwargs={
                       "id": score.id,
                       "column": self.column
                   }) + "?combination=" + Tracer.F1().key
     response = self.app.get(url)
     self.assertEqual(response.status_code, 200)
Beispiel #10
0
def persist_scores(score_cache, cycle):
    list_of_score_obj = list()
    mapping = {
        Tracer.F1().key: {
            "pass": "******",
            "fail": "f1_fail_count"
        },
        Tracer.F2().key: {
            "pass": "******",
            "fail": "f2_fail_count"
        },
        Tracer.F3().key: {
            "pass": "******",
            "fail": "f3_fail_count"
        },
        DEFAULT: {
            "pass": "******",
            "fail": "default_fail_count"
        },
    }
    for location, scores in score_cache.items():
        s = Score(
            name=location.facility,
            ip=location.partner,
            district=location.district,
            warehouse=location.warehouse,
            cycle=cycle,
            data=scores,
        )
        for key, value in scores.items():
            for f, result in value.items():
                formulation_mapping = mapping.get(f)
                if result in [YES, WEB]:
                    model_field = formulation_mapping.get("pass")
                    s.__dict__[model_field] += 1
                elif result in [NO]:
                    model_field = formulation_mapping.get("fail")
                    s.__dict__[model_field] += 1

        list_of_score_obj.append(s)
    Score.objects.filter(cycle=cycle).delete()
    Score.objects.bulk_create(list_of_score_obj)
Beispiel #11
0
    def __init__(self):
        self.test = ORDER_FORM_FREE_OF_NEGATIVE_NUMBERS

        self.combinations = Tracer.from_db()

        self.fields = [
            OPENING_BALANCE,
            QUANTITY_RECEIVED,
            COMBINED_CONSUMPTION,
            CLOSING_BALANCE,
            DAYS_OUT_OF_STOCK,
        ]
Beispiel #12
0
def volume_tally_check():
    builder = DefinitionFactory().blank().type(FACILITY_TWO_GROUPS_WITH_SAMPLE)
    builder.add_group(
        "Patients in Current Cycle",
        SUM,
        CURRENT_CYCLE,
        CONSUMPTION_MODEL,
        ["consumption"],
        [],
        factors={
            "Tenofovir/Lamivudine/Efavirenz (TDF/3TC/EFV) 300mg/300mg/600mg[Pack 30]":
            0.5,
            "Abacavir/Lamivudine (ABC/3TC) 60mg/30mg [Pack 60]":
            1 / 4.6,
            "Efavirenz (EFV) 200mg [Pack 90]":
            1,
        },
    )
    f2 = Tracer.F2()
    f3 = Tracer.F3()
    builder.add_group(
        "G2",
        SUM,
        CURRENT_CYCLE,
        "Adult",
        ["new", "existing"],
        [],
        model_overrides={
            f2.key: {
                "id": "Paed",
                "formulations": f2.patient_formulations
            },
            f3.key: {
                "id": "Paed",
                "formulations": f3.patient_formulations
            },
        },
    )
    builder.percentage_variance_is_less_than(30)
    return builder.get()
Beispiel #13
0
 def get_context_data(self, request, id, column):
     scores = {YES: "Pass", NO: "Fail", NOT_REPORTING: "N/A"}
     combination = request.GET.get("combination", DEFAULT)
     combination_name = combination
     if combination != DEFAULT:
         tracers = TracingFormulations.objects.filter(slug=combination)
         if len(tracers) > 0:
             combination_name = tracers[0].name
     column = int(column)
     score = Score.objects.get(id=id)
     score_data = {
         "ip": score.ip,
         "district": score.district,
         "warehouse": score.warehouse,
         "name": score.name,
         "cycle": score.cycle,
         "combination": combination_name,
     }
     has_result = column > 3
     response_data = {"score": score_data, "has_result": has_result}
     template_name = "check/base.html"
     if has_result:
         check_obj = self.get_test_by_column(column)
         check = get_check_from_dict(json.loads(check_obj.definition))
         response_data["data"] = check.get_preview_data(
             {
                 "name": score.name,
                 "district": score.district
             },
             score.cycle,
             Tracer(key=combination),
         )
         if score.data and type(score.data) is dict:
             result = score.data.get(check_obj.name)
         else:
             result = None
         # actual_result = get_actual_result(result, combination)
         result_data = {
             "name": check_obj.name,
             "test": check_obj.short_description,
             "result":
             scores.get(response_data["data"]["result"][combination]),
             "has_combination": len(maybe(result).or_else([])) > 1,
         }
         response_data["result"] = result_data
     response_data["detail"] = {
         "id": id,
         "column": column,
         "test": score.name
     }
     return response_data, template_name, score, combination_name
Beispiel #14
0
def stable_patients_check():
    builder = DefinitionFactory().blank().type(FACILITY_TWO_GROUPS_WITH_SAMPLE)
    f2 = Tracer.F2()
    f3 = Tracer.F3()
    thresholds = {Tracer.F1().key: "20", f2.key: "10", f3.key: "10"}
    model_overrides = {
        f2.key: {
            "id": "Paed",
            "formulations": f2.patient_formulations
        },
        f3.key: {
            "id": "Paed",
            "formulations": f3.patient_formulations
        },
    }
    builder.add_group(
        "G1",
        SUM,
        CURRENT_CYCLE,
        ADULT_MODEL,
        ["existing", "new"],
        [],
        thresholds=thresholds,
        model_overrides=model_overrides,
    )
    builder.add_group(
        "G2",
        SUM,
        PREVIOUS_CYCLE,
        ADULT_MODEL,
        ["existing", "new"],
        [],
        thresholds=thresholds,
        model_overrides=model_overrides,
    )
    builder.percentage_variance_is_less_than(50)
    return builder.get()
    def test_that_legacy_gets_same_result_as_new(self, name, scenario,
                                                 expected):
        legacy_check = StableConsumptionCheck()
        f1_combination = legacy_check.combinations[0]

        new_check = get_check_from_dict(stable_consumption_check())
        new_check_result = new_check.for_each_facility(scenario["Current"],
                                                       Tracer.F1(),
                                                       scenario["Previous"])
        self.assertEqual(expected, new_check_result)

        legacy_check_result = legacy_check.for_each_facility(
            scenario["Current"], f1_combination, scenario["Previous"])
        self.assertEqual(expected, legacy_check_result)
        self.assertEqual(legacy_check_result, new_check_result)
    def test_that_check_has_same_result_as_preview(self, name, scenario,
                                                   combination, expected):
        f1_combination = StableConsumptionCheck().combinations[0]
        f2_combination = StableConsumptionCheck().combinations[1]
        combinations = {"f1": f1_combination, "f2": f2_combination}
        combination = combinations[combination]
        new_check = get_check_from_dict(stable_consumption_check())
        new_check_result = new_check.for_each_facility(scenario["Current"],
                                                       Tracer.F1(),
                                                       scenario["Previous"])
        self.assertEqual(expected, new_check_result)
        current_cycle = "Nov - Dec 2017"
        previous_cycle = "Sep - Oct 2017"
        location = Location(facility="loc1",
                            district="dis1",
                            partner="",
                            warehouse="")
        for record in scenario.get("Current").c_records:
            create_consumption_record(
                location,
                record.formulation,
                current_cycle,
                consumption=record.consumption,
            )

        for record in scenario.get("Previous").c_records:
            create_consumption_record(
                location,
                record.formulation,
                previous_cycle,
                consumption=record.consumption,
            )

        data = new_check.get_preview_data(
            {
                "name": location.facility,
                "district": location.district
            },
            current_cycle,
            combination,
        )
        self.assertEqual(data["result"][combination.key], expected)
Beispiel #17
0
    def __init__(self):

        self.test = NNRTI_PAED
        self.combinations = [
            Tracer.Default().with_data(
                {
                    DF2: [
                        "Nevirapine (NVP) 50mg [Pack 60]",
                        "Lopinavir/Ritonavir (LPV/r) 80mg/20ml oral susp [Bottle 60ml]",
                        "Lopinavir/Ritonavir (LPV/r) 100mg/25mg",
                    ],
                    DF1: [
                        "Abacavir/Lamivudine (ABC/3TC) 60mg/30mg [Pack 60]",
                        "Zidovudine/Lamivudine (AZT/3TC) 60mg/30mg [Pack 60]",
                    ],
                    OTHER: ["Efavirenz (EFV) 200mg [Pack 90]"],
                    FIELDS: [COMBINED_CONSUMPTION],
                    RATIO: 4.6,
                    SHOW_CONVERSION: True,
                }
            )
        ]
Beispiel #18
0
 def get_preview_data(self,
                      sample_location=None,
                      sample_cycle=None,
                      sample_tracer=None):
     if sample_location is None:
         sample_location = self.definition.sample.get("location")
     if sample_cycle is None:
         sample_cycle = self.definition.sample.get("cycle")
     if sample_tracer is None:
         sample_tracer = Tracer.from_dict(
             self.definition.sample.get("tracer"))
     results = []
     for group in self.definition.groups:
         values_for_group = self._group_values_from_db(
             group, sample_cycle, sample_location, sample_tracer)
         results.append(values_for_group)
     data = {"groups": [r.as_dict() for r in results]}
     comparison_result, comparison_text = self.compare_results(results)
     data["result"] = {
         self.get_result_key(sample_tracer): comparison_result
     }
     data["resultText"] = comparison_text
     return data
Beispiel #19
0
 def __init__(self):
     self.test = NNRTI_ADULTS
     self.combinations = [
         Tracer.Default().with_data(
             {
                 DF2: [
                     "Efavirenz (EFV) 600mg [Pack 30]",
                     "Nevirapine (NVP) 200mg [Pack 60]",
                     "Atazanavir/Ritonavir (ATV/r) 300mg/100mg [Pack 30]",
                     "Lopinavir/Ritonavir (LPV/r) 200mg/50mg [Pack 120]",
                     "Dolutegravir (DTG) 50mg",
                 ],
                 DF1: [
                     "Zidovudine/Lamivudine (AZT/3TC) 300mg/150mg [Pack 60]",
                     "Tenofovir/Lamivudine (TDF/3TC) 300mg/300mg [Pack 30]",
                     "Abacavir/Lamivudine (ABC/3TC) 600mg/300mg [Pack 30]",
                 ],
                 FIELDS: [COMBINED_CONSUMPTION],
                 RATIO: 2.0,
                 SHOW_CONVERSION: True,
             }
         )
     ]
     self.count = 0
r1 = DataRecord(
    formulation=
    "Tenofovir/Lamivudine/Efavirenz (TDF/3TC/EFV) 300mg/300mg/600mg[Pack 30]",
    values=[50.0],
    fields=["consumption"],
)
r2 = DataRecord(
    formulation=
    "Tenofovir/Lamivudine/Efavirenz (TDF/3TC/EFV) 300mg/300mg/600mg[Pack 30]",
    values=[0],
    fields=["consumption"],
)
tracer = Tracer(
    key=u"tdf3tcefv-adult",
    consumption_formulations=[
        u"Tenofovir/Lamivudine/Efavirenz (TDF/3TC/EFV) 300mg/300mg/600mg[Pack 30]"
    ],
    patient_formulations=[u"TDF/3TC/EFV (PMTCT)", u"TDF/3TC/EFV (ADULT)"],
    extras=None,
)


class TestThresholds(TestCase):
    def test_groups_have_insufficient_data_if_the_aggregate_is_below_the_threshold(
            self):
        group1 = DefinitionGroup(
            name="G1",
            model=None,
            cycle=current_cycle,
            selected_fields=["consumption"],
            selected_formulations=[],
            sample_formulation_model_overridden={},
Beispiel #21
0
 def get_combinations(self):
     return [Tracer.Default()]
 def test_get_result_key_should_return_key_for_tracer(self):
     definition = Definition.from_dict(DefinitionFactory().initial().get())
     check = DBBasedCheckPreview(definition=definition)
     key = check.get_result_key(Tracer.F1())
     self.assertEqual(key, "tdf3tcefv-adult")
Beispiel #23
0
 def get_combinations(self):
     return [
         Tracer.from_dict(tr)
         for tr in self.definition.groups[0].model.tracing_formulations
     ]