|
| 1 | +from datetime import datetime, timedelta |
| 2 | +from typing import Iterable, Union |
| 3 | + |
| 4 | +import requests |
| 5 | +from django.conf import settings |
| 6 | +from epiweeks import Week |
| 7 | + |
| 8 | +from base.models import GeographyUnit |
| 9 | +from indicatorsets.utils import ( |
| 10 | + generate_epivis_custom_title, |
| 11 | + generate_random_color, |
| 12 | + get_epiweek, |
| 13 | + group_by_property, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +def epiweeks_in_date_range(start_date_str: str, end_date_str: str): |
| 18 | + start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date() |
| 19 | + end_date = datetime.strptime(end_date_str, "%Y-%m-%d").date() |
| 20 | + if end_date < start_date: |
| 21 | + start_date, end_date = end_date, start_date |
| 22 | + |
| 23 | + start_week = Week.fromdate(start_date) |
| 24 | + end_week = Week.fromdate(end_date) |
| 25 | + |
| 26 | + weeks = [] |
| 27 | + seen = set() |
| 28 | + d = start_week.startdate() |
| 29 | + while d <= end_week.enddate(): |
| 30 | + w = Week.fromdate(d) |
| 31 | + key = (w.year, w.week) |
| 32 | + if key not in seen: |
| 33 | + weeks.append(w) |
| 34 | + seen.add(key) |
| 35 | + d += timedelta(days=7) |
| 36 | + return weeks |
| 37 | + |
| 38 | + |
| 39 | +def _epiweek_key(w: Week) -> int: |
| 40 | + # Matches API time_value format YYYYWW, e.g. 202032 |
| 41 | + return w.year * 100 + w.week |
| 42 | + |
| 43 | + |
| 44 | +def _epiweek_label(w: Week) -> str: |
| 45 | + return f"{w.year}-W{w.week:02d}" |
| 46 | + |
| 47 | + |
| 48 | +def get_available_geos(indicators): |
| 49 | + geo_values = [] |
| 50 | + grouped_indicators = group_by_property(indicators, "data_source") |
| 51 | + for data_source, indicators in grouped_indicators.items(): |
| 52 | + indicators_str = ",".join(indicator["name"] for indicator in indicators) |
| 53 | + response = requests.get( |
| 54 | + f"{settings.EPIDATA_URL}covidcast/geo_indicator_coverage", |
| 55 | + params={"data_source": data_source, "signals": indicators_str}, |
| 56 | + auth=("epidata", settings.EPIDATA_API_KEY), |
| 57 | + ) |
| 58 | + if response.status_code == 200: |
| 59 | + data = response.json() |
| 60 | + if len(data["epidata"]): |
| 61 | + geo_values.extend(data["epidata"]) |
| 62 | + unique_values = set(geo_values) |
| 63 | + geo_levels = set([el.split(":")[0] for el in unique_values]) |
| 64 | + geo_unit_ids = set([geo_value.split(":")[1] for geo_value in unique_values]) |
| 65 | + geographic_granularities = [ |
| 66 | + { |
| 67 | + "id": f"{geo_unit.geo_level.name}:{geo_unit.geo_id}", |
| 68 | + "geoType": geo_unit.geo_level.name, |
| 69 | + "text": geo_unit.display_name, |
| 70 | + "geoTypeDisplayName": geo_unit.geo_level.display_name, |
| 71 | + } |
| 72 | + for geo_unit in GeographyUnit.objects.filter(geo_level__name__in=geo_levels) |
| 73 | + .filter(geo_id__in=geo_unit_ids) |
| 74 | + .prefetch_related("geo_level") |
| 75 | + .order_by("level") |
| 76 | + ] |
| 77 | + grouped_geographic_granularities = group_by_property( |
| 78 | + geographic_granularities, "geoTypeDisplayName" |
| 79 | + ) |
| 80 | + geographic_granularities = [] |
| 81 | + for key, value in grouped_geographic_granularities.items(): |
| 82 | + geographic_granularities.append( |
| 83 | + { |
| 84 | + "text": key, |
| 85 | + "children": value, |
| 86 | + } |
| 87 | + ) |
| 88 | + return geographic_granularities |
| 89 | + |
| 90 | + |
| 91 | +def get_covidcast_data(indicator, start_date, end_date, geo, api_key): |
| 92 | + if indicator["_endpoint"] == "covidcast": |
| 93 | + time_values = f"{start_date}--{end_date}" |
| 94 | + if indicator["time_type"] == "week": |
| 95 | + start_day, end_day = get_epiweek(start_date, end_date) |
| 96 | + time_values = f"{start_day}-{end_day}" |
| 97 | + geo_type, geo_value = geo.split(":") |
| 98 | + params = { |
| 99 | + "time_type": indicator["time_type"], |
| 100 | + "time_values": time_values, |
| 101 | + "data_source": indicator["data_source"], |
| 102 | + "signal": indicator["name"], |
| 103 | + "geo_type": geo_type, |
| 104 | + "geo_values": geo_value.lower(), |
| 105 | + "api_key": api_key if api_key else settings.EPIDATA_API_KEY, |
| 106 | + } |
| 107 | + response = requests.get(f"{settings.EPIDATA_URL}covidcast", params=params) |
| 108 | + if response.status_code == 200: |
| 109 | + response_data = response.json() |
| 110 | + if len(response_data["epidata"]): |
| 111 | + return response_data["epidata"] |
| 112 | + return [] |
| 113 | + |
| 114 | + |
| 115 | +def prepare_chart_series_multi( |
| 116 | + api_rows: list[dict], |
| 117 | + start_date: str, |
| 118 | + end_date: str, |
| 119 | + series_by: Union[str, Iterable[str]] = "signal", |
| 120 | +): |
| 121 | + """ |
| 122 | + api_rows: list of dicts with at least 'time_value' (YYYYWW) and 'value' |
| 123 | + series_by: a field name (e.g., 'signal' or 'geo_value') or an iterable of fields (e.g., ('signal','geo_value')) |
| 124 | + returns: { labels: [...], datasets: [{ label, data }, ...] } |
| 125 | + """ |
| 126 | + # 1) Build aligned epiweek axis |
| 127 | + weeks = epiweeks_in_date_range(start_date, end_date) |
| 128 | + labels = [_epiweek_label(w) for w in weeks] |
| 129 | + keys = [_epiweek_key(w) for w in weeks] |
| 130 | + |
| 131 | + # 2) Group rows by series key |
| 132 | + if isinstance(series_by, (list, tuple)): |
| 133 | + |
| 134 | + def series_key_of(row): |
| 135 | + return tuple(row.get(k) for k in series_by) |
| 136 | + |
| 137 | + def series_label_of(key): |
| 138 | + return " - ".join(str(k) for k in key) |
| 139 | + |
| 140 | + else: |
| 141 | + |
| 142 | + def series_key_of(row): |
| 143 | + return row.get(series_by) |
| 144 | + |
| 145 | + def series_label_of(key): |
| 146 | + return str(key) |
| 147 | + |
| 148 | + series_to_values: dict[object, dict[int, float]] = {} |
| 149 | + for row in api_rows: |
| 150 | + tv = row.get("time_value") |
| 151 | + # If the API returned daily values (YYYYMMDD), convert to epiweek key (YYYYWW) |
| 152 | + if tv is not None and (row.get("time_type") == "day"): |
| 153 | + try: |
| 154 | + tv_str = str(tv) |
| 155 | + year = int(tv_str[0:4]) |
| 156 | + month = int(tv_str[4:6]) |
| 157 | + day = int(tv_str[6:8]) |
| 158 | + d = datetime(year, month, day).date() |
| 159 | + w = Week.fromdate(d) |
| 160 | + tv = _epiweek_key(w) |
| 161 | + except Exception: |
| 162 | + # Skip malformed dates |
| 163 | + tv = None |
| 164 | + if tv is None: |
| 165 | + continue |
| 166 | + skey = series_key_of(row) |
| 167 | + if skey not in series_to_values: |
| 168 | + series_to_values[skey] = {} |
| 169 | + # last one wins if duplicates |
| 170 | + series_to_values[skey][tv] = row.get("value", None) |
| 171 | + |
| 172 | + # 3) Align each series to the epiweek axis, filling with None |
| 173 | + datasets = [] |
| 174 | + for skey, tv_map in series_to_values.items(): |
| 175 | + data = [tv_map.get(k, None) for k in keys] |
| 176 | + datasets.append({"label": series_label_of(skey), "data": data}) |
| 177 | + |
| 178 | + return {"labels": labels, "datasets": datasets} |
| 179 | + |
| 180 | + |
| 181 | +def normalize_dataset(data): |
| 182 | + """ |
| 183 | + Normalize a dataset to 0-100% range based on its min/max. |
| 184 | + Preserves None values for missing data. |
| 185 | + """ |
| 186 | + # Filter out None values for min/max calculation |
| 187 | + numeric_values = [v for v in data if v is not None and not (isinstance(v, float) and (v != v or v in (float('inf'), float('-inf'))))] |
| 188 | + |
| 189 | + if not numeric_values: |
| 190 | + return data # Return as-is if no valid numeric values |
| 191 | + |
| 192 | + min_val = min(numeric_values) |
| 193 | + max_val = max(numeric_values) |
| 194 | + range_val = (max_val - min_val) or 1 # Avoid division by zero |
| 195 | + |
| 196 | + # Normalize each value |
| 197 | + normalized = [] |
| 198 | + for value in data: |
| 199 | + if value is None: |
| 200 | + normalized.append(None) |
| 201 | + elif isinstance(value, float) and (value != value or value in (float('inf'), float('-inf'))): |
| 202 | + normalized.append(None) |
| 203 | + else: |
| 204 | + normalized.append(((value - min_val) / range_val) * 100) |
| 205 | + |
| 206 | + return normalized |
| 207 | + |
| 208 | + |
| 209 | +def get_chart_data(indicators, geography): |
| 210 | + chart_data = {"labels": [], "datasets": []} |
| 211 | + geo_type, geo_value = geography.split(":") |
| 212 | + geo_display_name = GeographyUnit.objects.get( |
| 213 | + geo_level__name=geo_type, geo_id=geo_value |
| 214 | + ).display_name |
| 215 | + for indicator in indicators: |
| 216 | + title = generate_epivis_custom_title(indicator, geo_display_name) |
| 217 | + color = generate_random_color() |
| 218 | + data = get_covidcast_data( |
| 219 | + indicator, "2010-01-01", "2025-01-31", geography, settings.EPIDATA_API_KEY |
| 220 | + ) |
| 221 | + if data: |
| 222 | + series = prepare_chart_series_multi( |
| 223 | + data, |
| 224 | + "2020-01-01", |
| 225 | + "2025-01-31", |
| 226 | + series_by="signal", # label per indicator (adjust to ("signal","geo_value") if needed) |
| 227 | + ) |
| 228 | + # Apply readable label, color, and normalize data for each dataset |
| 229 | + for ds in series["datasets"]: |
| 230 | + ds["label"] = f"{title} - {ds['label']}" |
| 231 | + ds["borderColor"] = color |
| 232 | + ds["backgroundColor"] = f"{color}33" |
| 233 | + # Normalize data to 0-100% range |
| 234 | + if ds.get("data"): |
| 235 | + ds["data"] = normalize_dataset(ds["data"]) |
| 236 | + # Initialize labels once; assume same date range for all |
| 237 | + if not chart_data["labels"]: |
| 238 | + chart_data["labels"] = series["labels"] |
| 239 | + chart_data["datasets"].extend(series["datasets"]) |
| 240 | + return chart_data |
0 commit comments