Exemplo n.º 1
0
                if len(exclude_list) > 0:
                    if clinic in exclude_list:
                        continue
                if include_case_type:
                    if set(locations[clinic].case_type) & include_case_type:
                        non_reporting_clinics.append(clinic)
                elif exclude_case_type and "code:" not in exclude_case_type:
                    if not set(
                            locations[clinic].case_type) & exclude_case_type:
                        non_reporting_clinics.append(clinic)

                else:
                    non_reporting_clinics.append(clinic)
        return {"clinics": non_reporting_clinics}


api.add_resource(
    NonReporting, "/non_reporting/<variable>/<location>",
    "/non_reporting/<variable>/<location>/<num_weeks>/<exclude_case_type>",
    "/non_reporting/<variable>/<location>/<num_weeks>/<exclude_case_type>/<include_case_type>",
    "/non_reporting/<variable>/<location>/<num_weeks>/<exclude_case_type>/<include_case_type>/<include_clinic_type>/<require_case_report>"
)

api.add_resource(
    Completeness, "/completeness/<variable>/<location>/<number_per_week>",
    "/completeness/<variable>/<location>/<number_per_week>/<start_week>",
    "/completeness/<variable>/<location>/<number_per_week>/<start_week>/<weekend>",
    "/completeness/<variable>/<location>/<number_per_week>/<start_week>/<weekend>/<non_reporting_variable>",
    "/completeness/<variable>/<location>/<number_per_week>/<start_week>/<weekend>/<non_reporting_variable>/<end_date>"
)
Exemplo n.º 2
0
        args = parser.parse_args()
        filters = args['filter']
        parent_id = int(args['location'])
        all_locations_dict = get_locations(db.session)
        children_location_ids = get_children(parent_id, all_locations_dict)
        results_by_location = []
        for location_id in children_location_ids:
            result = []
            location = Location.get_location_by_id(location_id)
            sql_alchemy_filters = self.get_sql_alchemy_filters(filters)

            if location.deviceid:
                device_ids = location.deviceid.split(',')
                for device_id in device_ids:
                    result.append(self._get_variable_count_for_deivce_id(device_id, variable_id, sql_alchemy_filters))
            results_by_location.append({
                "clinicId": location_id,
                "deviceSubmissions": result
            })
        return jsonify({
            "parentLocationId": parent_id,
            "clinicCount": len(children_location_ids),
            "clinicSubmissions": results_by_location
        })


api.add_resource(Devices, "/devices")

api.add_resource(DeviceSubmissions, "/device/<device_id>/submissions/<variable_id>")
api.add_resource(DeviceSubmissionsForLocation, "/devices/submissions/<variable_id>")
Exemplo n.º 3
0
                indicator_data = {}
                for key in analysis_output:
                    indicator_data[str(key)] = prepare_indicator_output(
                        analysis_output[key], mult_factor)
                return indicator_data

            else:
                if count_over:
                    analysis_output = count_over_count(data, numerator,
                                                       denominator, start_date,
                                                       end_date)
                else:
                    analysis_output = count(data, numerator, start_date,
                                            end_date)
                return prepare_indicator_output(analysis_output, mult_factor)

        except (RuntimeError, TypeError, NameError, IndexError) as err:
            logging.error(err)
            logging.error("Not enough data avaliable to show the indicator")
            return {
                "timeline": [],
                "cummulative": 0,
                "current": 0,
                "previous": 0
            }


api.add_resource(
    Indicators, "/indicators/<flags>/<variables>/<location>",
    "/indicators/<flags>/<variables>/<location>/<start_date>/<end_date>")
Exemplo n.º 4
0
        if date:
            date = parse(date)
        else:
            date = datetime.datetime.today()

        _epi_year, _epi_week_number = epi_week_util.epi_week_for_date(date)
        _epi_year_start_day_weekday = epi_week_util.epi_year_start_date(date).weekday()
        return jsonify(epi_week=_epi_week_number,
                       year=_epi_year,
                       offset=_epi_year_start_day_weekday)


class EpiWeekStart(Resource):
    """
    Return the start date of an epi week in the given year

    Args:\n
        epi-week: epi week\n
        year: year\n
    Returns:
        start-date: start-date\n
    """

    def get(self, year, epi_week):
        _epi_week_start_date = epi_week_util.epi_week_start_date(year, epi_week)
        return jsonify(start_date=_epi_week_start_date)


api.add_resource(EpiWeek, "/epi_week", "/epi_week/<date>")
api.add_resource(EpiWeekStart, "/epi_week_start/<year>/<epi_week>")
Exemplo n.º 5
0
                    })

        return prescriptions

    def _get_number_of_kits_in_clinic(self, prescription_location_id):
        kits_in_clinic = self.locs[prescription_location_id].other.get('IEHK kits', '')
        try:
            kits_in_clinic = int(kits_in_clinic)
        except ValueError:
            kits_in_clinic = DEFAULT_KIT_COUNT_IN_CLINIC
        return kits_in_clinic


def find_highest_depletion(clinic_medicines):
    if not clinic_medicines:
        return {}
    depletion_list = []
    for medicine in clinic_medicines.keys():
        depletion_list.append({
            'medicine': medicine,
            'depletion': clinic_medicines[medicine].get('depletion', False)
        })

    sorted_depletion_list = sorted(depletion_list, key=lambda k: k['depletion'], reverse=True)
    return sorted_depletion_list[0]


api.add_resource(Prescriptions, "/prescriptions/<location>",
                 "/prescriptions/<location>/<end_date>",
                 "/prescriptions/<location>/<end_date>/<start_date>")
Exemplo n.º 6
0
        tot_pop = 0
        clinic_map = []
        for clinic in refugee_clinics:
            result = get_latest_category("population", clinic,
                                         datetime(2015, 1, 1), datetime.now())
            clinic_pop = 0
            if (result):
                clinic_pop = sum(
                    [sum(result[x].values()) for x in result.keys()])

                tot_pop += clinic_pop
            geo = to_shape(locs[clinic].point_location)
            clinic_map.append({"value": clinic_pop,
                               "geolocation": [geo.y, geo.x],
                               "clinic": locs[clinic].name,
                               "location_id": clinic})
        return clinic_map


api.add_resource(KeyIndicators, "/key_indicators",
                 "/key_indicators/<int:location>")
api.add_resource(TotMap, "/tot_map",
                 "/tot_map/<int:location>")
api.add_resource(ConsultationMap, "/consultation_map",
                 "/consultation_map/<int:location>")
api.add_resource(NumAlerts, "/num_alerts",
                 "/num_alerts/<int:location>")
api.add_resource(NumClinics, "/num_clinics",
                 "/num_clinics/<int:location>")
api.add_resource(RefugeePage, "/refugee_page")
Exemplo n.º 7
0
            weeks=True)

        #Structure the return data.
        ret = {"weeks": results["weeks"], "year": results["total"]}

        #Get population for specified location.
        location = db.session.query(Locations).filter_by(id=location_id).all()
        population = location[0].population

        #For each week and year value in ret, incidence = val/pop * mult_factor.
        for week in ret["weeks"]:
            ret["weeks"][week] = ret["weeks"][week] / population * mult_factor
        ret["year"] = ret["year"] / population * mult_factor

        return ret

# IncidenceRate
api.add_resource(
    IncidenceRate,
    "/incidence_rate/<variable_id>/<level>",
    "/incidence_rate/<variable_id>/<level>/<mult_factor>",
    "/incidence_rate/<variable_id>/<level>/<mult_factor>/<year>",
    "/incidence_rate/<variable_id>/<level>/<mult_factor>/<year>/<monthly>"
)
api.add_resource(
    WeeklyIncidenceRate,
    "/weekly_incidence/<variable_id>/<loc_id>",
    "/weekly_incidence/<variable_id>/<loc_id>/<year>",
    "/weekly_incidence/<variable_id>/<loc_id>/<year>/<mult_factor>"
)
Exemplo n.º 8
0
    Returns:\n
       location: location
    """
    def get(self, device_id):
        location_filter = _get_by_device_id_filter(device_id)
        query = db.session.query(model.Locations).filter(location_filter)
        if query.count() == 0:
            abort(404,
                  message="No location matching deviceid: {!r}".format(
                      device_id))
        else:
            return jsonify(row_to_dict(query.one()))


def _get_by_device_id_filter(device_id):
    locations_deviceid = model.Locations.deviceid
    location_filter = or_(
        locations_deviceid == device_id,
        locations_deviceid.startswith("{},".format(device_id)),
        locations_deviceid.contains(",{},".format(device_id)),
        locations_deviceid.endswith(",{}".format(device_id)))
    return location_filter


api.add_resource(Locations, "/locations")
api.add_resource(LocationTree, "/locationtree")
api.add_resource(Location, "/location/<location_id>")
# endpoint "/device/<device_id>" is deprecated use /locations?deviceId=<device_id> instead
api.add_resource(LocationByDeviceId, "/device/<device_id>")
api.add_resource(TotClinics, "/tot_clinics/<location_id>")
Exemplo n.º 9
0
                clinic_records.setdefault(r.clinic, [])
                clinic_records[r.clinic].append(r)

            results = []
            for clinic, records in clinic_records.items():
                if len(records) == 1:
                    results.append(records[0])
                else:
                    results.append(
                        sorted(records, key=lambda x: x.date)[-1]
                    )

        return jsonify({"records": rows_to_dicts(results)})


api.add_resource(Aggregate, "/aggregate/<variable_id>/<location_id>")
api.add_resource(AggregateLatest, "/aggregate_latest/<variable_id>/<identifier_id>/<location_id>")

api.add_resource(AggregateYear,
                 "/aggregate_year/<variable_id>/<location_id>",
                 "/aggregate_year/<variable_id>/<location_id>/<year>")
api.add_resource(AggregateLatestYear,
                 "/aggregate_latest_year/<variable_id>/<identifier_id>/<location_id>",
                 "/aggregate_latest_year/<variable_id>/<identifier_id>/<location_id>/<weeks>",
                 "/aggregate_latest_year/<variable_id>/<identifier_id>/<location_id>/<weeks>/<year>")
api.add_resource(AggregateLatestLevel,
                 "/aggregate_latest_level/<variable_id>/<identifier_id>/<level>",
                 "/aggregate_latest_level/<variable_id>/<identifier_id>/<level>/<weekly>",
                 "/aggregate_latest_level/<variable_id>/<identifier_id>/<level>/<weekly>/<location_id>")
api.add_resource(AggregateLatestCategory,
                 "/aggregate_latest_category/<category>/<identifier_id>/<location_id>",
Exemplo n.º 10
0
                        else:
                            status = "Ongoing"

                else:
                    if "ale_1" in a["variables"]:
                        if "ale_2" in a["variables"]:
                            status = "Confirmed"
                        elif "ale_3" in a["variables"]:
                            status = "Disregarded"
                        elif "ale_4" in a["variables"]:
                            status = "Ongoing"
                        else:
                            status = "Ongoing"
                    else:
                        # We set all  without an investigation to Pending
                        status = "Pending"
                r = ret.setdefault(str(reason), {})
                r.setdefault(status, 0)
                r[status] += 1
                total += 1

        ret["total"] = total
        return jsonify(ret)


api.add_resource(AggregateAlerts, "/aggregate_alerts",
                 "/aggregate_alerts/<central_review>",
                 "/aggregate_alerts/<central_review>/<hard_date_limit>")
api.add_resource(Alert, "/alert/<alert_id>")
api.add_resource(Alerts, "/alerts")
Exemplo n.º 11
0
    def get(self, form):
        uid = str(uuid.uuid4())
        if "fields" in request.args.keys():
            fields = request.args["fields"].split(",")
        else:
            fields = None
        yaml_config = yaml.dump(abacus_config)
        export_form.delay(
            uid, form, g.allowed_location, fields,
            param_config_yaml=yaml_config
        )
        return uid


# Export data
api.add_resource(GetCSVDownload, "/export/getcsv/<uid>")
api.add_resource(GetXLSDownload, "/export/getxls/<uid>")
api.add_resource(GetStatus, "/export/get_status/<uid>")
api.add_resource(ExportData, "/export/data",
                 "/export/data/<use_loc_ids>")
api.add_resource(ExportForm, "/export/form/<form>")
api.add_resource(Forms, "/export/forms")
api.add_resource(ExportCategory,
                 "/export/category/<form_name>/<category>/<download_name>",
                 "/export/category/<form_name>/<category>/<download_name>/<data_type>")
api.add_resource(ExportDataTable,
                 "/export/data_table/<download_name>/<restrict_by>")
api.add_resource(ExportWeekLevel,
                 "/export/week_level/<download_name>/<level>")
Exemplo n.º 12
0
            if "include_group_b" in request.args:
                results = db.session.query(model.AggregationVariables).filter(
                    or_(model.AggregationVariables.alert == 1,
                        model.AggregationVariables.alert_desc == "Group B"))
            else:
                results = db.session.query(model.AggregationVariables).filter(
                    model.AggregationVariables.alert == 1)
        elif category != "all":
            results = db.session.query(model.AggregationVariables).filter(
                model.AggregationVariables.category.has_key(category))
        else:
            results = db.session.query(model.AggregationVariables)
        return rows_to_dicts(results.all(), dict_id="id")


class Variable(Resource):
    """
    Returns a variable
    
    Args:\n
        variable_id: id of variable to be returned\n
    """
    def get(self, variable_id):
        return row_to_dict(
            db.session.query(model.AggregationVariables).filter(
                model.AggregationVariables.id == variable_id).first())


api.add_resource(Variables, "/variables/<category>")
api.add_resource(Variable, "/variable/<variable_id>")
Exemplo n.º 13
0
            i2 = row[1]
            if "locations" in group_by1:
                i1 = row[2]
            if "locations" in group_by2:
                i2 = row[2]
            if i1 and i2:
                ret.setdefault(names1[i1], {}).setdefault(names2[i2], 0)
                ret[names1[i1]][names2[i2]] += 1
        # We also add rows and columns with zeros
        for n1 in names1.values():
            for n2 in names2.values():
                if n1 in ret:
                    if n2 not in ret[n1]:
                        ret[n1][n2] = 0
                else:
                    ret.setdefault(n1, {})
                    ret[n1][n2] = 0
        return ret


api.add_resource(
    QueryVariable, "/query_variable/<variable>/<group_by>",
    "/query_variable/<variable>/<group_by>"
    "/<start_date>/<end_date>")
api.add_resource(
    QueryCategory, "/query_category/<group_by1>/<group_by2>",
    "/query_category/<group_by1>/<group_by2>/<only_loc>",
    "/query_category/<group_by1>/<group_by2>"
    "/<start_date>/<end_date>", "/query_category/<group_by1>/<group_by2>"
    "/<start_date>/<end_date>/<only_loc>")
Exemplo n.º 14
0
            if r[1] is not None:
                if level == "clinic":
                    shape = to_shape(r[0])
                else:
                    shape = to_shape(r[1])

                feature = {
                    "type": "Feature",
                    "properties": {
                        "Name": r[2]
                    },
                    "geometry": shapely.geometry.mapping(shape)
                }
                features.append(feature)
        return {"type": "FeatureCollection", "features": features}


api.add_resource(Clinics, "/clinics/<location_id>",
                 "/clinics/<location_id>/<clinic_type>",
                 "/clinics/<location_id>/<clinic_type>/<require_case_report>")
api.add_resource(Shapes, "/geo_shapes/<level>")

api.add_resource(MapVariable, "/map/<variable_id>",
                 "/map/<variable_id>/<location>",
                 "/map/<variable_id>/<location>/<end_date>",
                 "/map/<variable_id>/<location>/<end_date>/<start_date>")
api.add_resource(MapCategory, "/map_category/<category>",
                 "/map_category/<category>/<location>")

api.add_resource(IncidenceMap, "/incidence_map/<variable_id>")