-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_data.py
More file actions
1413 lines (1262 loc) · 50.7 KB
/
process_data.py
File metadata and controls
1413 lines (1262 loc) · 50.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Process raw CSV inputs into optimized frontend assets.
Outputs:
- public/data/projects.json
- public/data/tags.json
- public/data/globe.json
- public/data/tags/<tag_id>.json
"""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import json
import shutil
import re
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import pandas as pd
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Process GeoLocator raw CSV data.")
parser.add_argument("--input", default="raw_data", help="Input directory with raw CSV files.")
parser.add_argument("--output", default="public/data", help="Output directory for processed assets.")
parser.add_argument(
"--skip-pressurepaths",
action="store_true",
help="Skip pressurepaths processing.",
)
return parser.parse_args()
def parse_taxonomic(value: Optional[str]) -> List[str]:
if value is None:
return []
text = str(value).strip().strip("\"")
if not text:
return []
return [item.strip().strip("\"") for item in text.split(",") if item.strip().strip("\"")]
def to_float(value: Optional[str]) -> Optional[float]:
if value is None:
return None
text = str(value).strip()
if not text or text.upper() == "NA":
return None
return float(text)
def to_int(value: Optional[str]) -> Optional[int]:
if value is None:
return None
text = str(value).strip()
if not text or text.upper() == "NA":
return None
return int(float(text))
def parse_csv_contributors(value: str) -> List[Dict[str, Any]]:
text = value.strip()
if not text:
return []
if ";" in text:
names = [item.strip() for item in text.split(";") if item.strip()]
return [{"title": name} for name in names]
parts = [item.strip() for item in text.split(",") if item.strip()]
if not parts:
return []
if len(parts) == 1:
return [{"title": parts[0]}]
contributors: List[Dict[str, Any]] = []
index = 0
while index < len(parts):
if index + 1 < len(parts):
title = f"{parts[index]}, {parts[index + 1]}"
index += 2
else:
title = parts[index]
index += 1
contributors.append({"title": title})
return contributors
def parse_csv_licenses(value: str) -> List[Dict[str, Any]]:
text = value.strip()
if not text:
return []
items = [item.strip() for item in text.split(";") if item.strip()]
licenses: List[Dict[str, Any]] = []
for item in items:
code = ""
match = re.search(r"\(([^()]+)\)\s*$", item)
if match:
code = match.group(1).strip().lower()
licenses.append({"title": item, "name": code or item, "path": ""})
return licenses
def parse_csv_related_identifiers(value: str) -> List[Dict[str, Any]]:
text = value.strip()
if not text:
return []
items = [item.strip() for item in text.split(",") if item.strip()]
related: List[Dict[str, Any]] = []
for item in items:
if ":" in item:
relation_raw, identifier_raw = item.split(":", 1)
relation_type = relation_raw.strip()
identifier = identifier_raw.strip()
else:
relation_type = ""
identifier = item
if not identifier:
continue
identifier_type = "other"
doi_match = re.match(r"^(?:https?://doi\.org/)?(10\.\S+)$", identifier, re.IGNORECASE)
if doi_match:
identifier = doi_match.group(1)
identifier_type = "doi"
elif re.match(r"^https?://", identifier, re.IGNORECASE):
identifier_type = "url"
related.append(
{
"relationType": relation_type,
"relatedIdentifier": identifier,
"relatedIdentifierType": identifier_type,
}
)
return related
def parse_datapackages_csv(path: Path) -> List[Dict[str, Any]]:
count_keys = [
"tags",
"measurements",
"light",
"pressure",
"activity",
"temperature_external",
"temperature_internal",
"magnetic",
"wet_count",
"conductivity",
"paths",
"pressurepaths",
]
required_columns = {
"datapackage_id",
"title",
"version",
"created",
"status",
"access_status",
"embargo",
"conceptid",
"codeRepository",
"homepage",
"contributors",
"licenses",
"keywords",
"grants",
"relatedIdentifiers",
"temporal_start",
"temporal_end",
"taxonomic",
"bibliographicCitation",
*[f"numberTags_{key}" for key in count_keys],
}
rows: List[Dict[str, Any]] = []
with path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
header = set(reader.fieldnames or [])
missing_columns = sorted(required_columns - header)
if missing_columns:
raise SystemExit(
f"Missing required columns in {path.name}: {', '.join(missing_columns)}"
)
for raw in reader:
project_id = raw["datapackage_id"].strip()
if not project_id:
raise SystemExit("Missing datapackage_id in datapackages.csv.")
concept_id = raw["conceptid"].strip()
counts: Dict[str, Optional[int]] = {
key: to_int(raw[f"numberTags_{key}"]) for key in count_keys
}
temporal_start = raw["temporal_start"].strip()
temporal_end = raw["temporal_end"].strip()
temporal = None
if temporal_start or temporal_end:
temporal = {"start": temporal_start, "end": temporal_end}
record: Dict[str, Any] = {
"id": project_id,
"concept_id": concept_id,
"title": raw["title"].strip(),
"version": raw["version"].strip(),
"created": raw["created"].strip(),
"status": raw["status"].strip(),
"access_status": raw["access_status"].strip(),
"embargo": raw["embargo"].strip(),
"repository": raw["codeRepository"].strip(),
"homepage": raw["homepage"].strip(),
"keywords": raw["keywords"].strip(),
"grants": raw["grants"].strip(),
"bibliographicCitation": raw["bibliographicCitation"].strip(),
"taxonomic": parse_taxonomic(raw["taxonomic"]),
"numberTags": counts,
"contributors": parse_csv_contributors(raw["contributors"]),
"licenses": parse_csv_licenses(raw["licenses"]),
"relatedIdentifiers": parse_csv_related_identifiers(raw["relatedIdentifiers"]),
}
if temporal is not None:
record["temporal"] = temporal
rows.append(record)
return rows
def load_datapackage_records(csv_path: Path) -> List[Dict[str, Any]]:
if not csv_path.exists():
raise SystemExit(f"Missing {csv_path}")
rows = parse_datapackages_csv(csv_path)
if not rows:
raise SystemExit("datapackages.csv could not be parsed.")
return rows
def round_decimal(value: Any, digits: int) -> Optional[float]:
num = to_float(value)
if num is None:
return None
return round(num, digits)
def round_coord(value: Any) -> Optional[float]:
return round_decimal(value, 4)
def round_int(value: Any) -> Optional[int]:
num = to_float(value)
if num is None:
return None
return int(round(num))
def transform_rows(rows: Dict[str, List[Any]], transforms: Dict[str, Any]) -> Dict[str, List[Any]]:
updated: Dict[str, List[Any]] = {}
for key, values in rows.items():
fn = transforms.get(key)
if not fn:
updated[key] = values
continue
updated[key] = [fn(value) for value in values]
return updated
def parse_datetime(value: Optional[str]) -> Optional[dt.datetime]:
if value is None:
return None
text = value.strip()
if not text:
return None
return dt.datetime.fromisoformat(text.replace("Z", "+00:00"))
def round_datetime_minute(value: Any) -> Optional[str]:
if value is None:
return None
text = str(value).strip()
if not text:
return None
parsed = parse_datetime(text)
if not parsed:
return value
rounded = parsed.replace(second=0, microsecond=0)
iso = rounded.isoformat()
if iso.endswith("+00:00"):
return iso.replace("+00:00", "Z")
return iso
def compact_dump(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=True, separators=(",", ":"))
def reset_output_dir(output_dir: Path) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
for subdir in ("projects", "tags"):
path = output_dir / subdir
if path.exists():
shutil.rmtree(path)
for filename in ("projects.json", "tags.json", "globe.json"):
path = output_dir / filename
if path.exists():
path.unlink()
def load_resource_descriptors(datapackage_path: Path) -> Dict[str, Dict[str, Any]]:
with datapackage_path.open(encoding="utf-8") as handle:
data = json.load(handle)
resources = {}
base_dir = datapackage_path.parent
for resource in data["resources"]:
name = resource["name"]
fields = resource["schema"]["fields"]
path_value = resource["path"]
resources[name] = {
"name": name,
"path": str((base_dir / path_value).resolve()),
"fields": fields,
}
return resources
def pandas_dtype_map(fields: List[Dict[str, Any]]) -> Dict[str, str]:
dtype_map: Dict[str, str] = {}
for field in fields:
name = field.get("name")
if not name:
continue
field_type = (field.get("type") or "string").lower()
if field_type in ("date", "datetime"):
dtype_map[name] = "string"
elif field_type == "integer":
dtype_map[name] = "Int64"
elif field_type == "number":
dtype_map[name] = "float64"
elif field_type == "boolean":
dtype_map[name] = "boolean"
else:
dtype_map[name] = "string"
return dtype_map
def process_projects(
records: List[Dict[str, Any]],
) -> Tuple[List[Dict[str, Any]], Dict[str, Dict[str, Any]], Dict[str, str]]:
projects: List[Dict[str, Any]] = []
ordered_projects: List[Dict[str, Any]] = []
project_index: Dict[str, Dict[str, Any]] = {}
record_to_project: Dict[str, str] = {}
for row in records:
taxonomic = [normalize_species(name) for name in row["taxonomic"]]
counts = {key: to_int(value) for key, value in row["numberTags"].items()}
record_id = row["id"].strip()
concept_id = row["concept_id"].strip()
if not record_id:
title = row.get("title") or "unknown"
raise SystemExit(f"Project missing id in datapackages.csv: {title}")
concept_numeric = to_concept_id(concept_id) or to_concept_id(record_id)
concept_doi = to_concept_doi(concept_numeric)
project_id = concept_numeric or record_id
project = dict(row)
project["record_id"] = record_id
if concept_numeric:
project["concept_id"] = concept_numeric
if concept_doi:
project["concept_doi"] = concept_doi
project["id"] = project_id
project["taxonomic"] = taxonomic
project["counts"] = counts
project["relatedIdentifiers"] = [
{**entry, "relationType": humanize_relation_type(entry.get("relationType", ""))}
for entry in project.get("relatedIdentifiers", [])
]
projects.append(project)
if project_id in project_index:
raise SystemExit(f"Duplicate project id in datapackages.csv: {project_id}")
project_index[project_id] = project
record_to_project[normalize_doi(record_id)] = project_id
if concept_doi:
record_to_project[normalize_doi(concept_doi)] = project_id
if concept_numeric:
record_to_project[concept_numeric] = project_id
def is_embargoed(project: Dict[str, Any]) -> bool:
embargo = project.get("embargo")
if not embargo or str(embargo).strip().upper() == "NA":
return False
embargo_dt = dt.datetime.fromisoformat(str(embargo).replace("Z", "+00:00"))
return embargo_dt.date() > dt.date.today()
ordered_projects = sorted(
projects,
key=lambda item: (is_embargoed(item), item.get("title") or ""),
)
return ordered_projects, project_index, record_to_project
def humanize_relation_type(value: str) -> str:
mapping = {
"iscitedby": "Is cited by",
"cites": "Cites",
"issupplementto": "Is supplement to",
"issupplementedby": "Is supplemented by",
"iscontinuedby": "Is continued by",
"continues": "Continues",
"isnewversionof": "Is new version of",
"ispreviousversionof": "Is previous version of",
"ispartof": "Is part of",
"haspart": "Has part",
"ispublishedin": "Is published in",
"isreferencedby": "Is referenced by",
"references": "References",
"isdocumentedby": "Is documented by",
"documents": "Documents",
"iscompiledby": "Is compiled by",
"compiles": "Compiles",
"isvariantformof": "Is variant form of",
"isoriginalformof": "Is original form of",
"isidenticalto": "Is identical to",
"hasmetadata": "Has metadata",
"ismetadatafor": "Is metadata for",
"reviews": "Reviews",
"isreviewedby": "Is reviewed by",
"isderivedfrom": "Is derived from",
"issourceof": "Is source of",
"describes": "Describes",
"isdescribedby": "Is described by",
"hasversion": "Has version",
"isversionof": "Is version of",
"requires": "Requires",
"isrequiredby": "Is required by",
"obsoletes": "Obsoletes",
"isobsoletedby": "Is obsoleted by",
"collects": "Collects",
"iscollectedby": "Is collected by",
"hastranslation": "Has translation",
"istranslationof": "Is translation of",
}
lowered = str(value or "").strip().lower()
if lowered in mapping:
return mapping[lowered]
spaced = re.sub(r"([a-z])([A-Z])", r"\1 \2", str(value or "").strip())
return spaced[:1].upper() + spaced[1:]
def normalize_species(name: str) -> str:
cleaned = " ".join(name.strip().split())
corrections = {
"Caprimulgus europeaus": "Caprimulgus europaeus",
}
return corrections.get(cleaned, cleaned)
def normalize_doi(value: str) -> str:
cleaned = (value or "").strip()
if not cleaned:
return ""
lowered = cleaned.lower()
if lowered.startswith("doi:"):
lowered = lowered[4:].strip()
if lowered.startswith("https://doi.org/"):
lowered = lowered.replace("https://doi.org/", "")
if lowered.startswith("http://doi.org/"):
lowered = lowered.replace("http://doi.org/", "")
return f"https://doi.org/{lowered}".rstrip("/")
def to_concept_id(value: str) -> str:
if not value:
return ""
numeric = re.sub(r"[^0-9]", "", value)
return numeric or ""
def to_concept_doi(concept_id: str) -> str:
numeric = to_concept_id(concept_id)
if not numeric:
return ""
return f"https://doi.org/10.5281/zenodo.{numeric}"
def build_taxa_objects(
taxonomic: List[str],
species_lookup: Dict[str, Dict[str, Any]],
) -> List[Dict[str, Any]]:
taxa: List[Dict[str, Any]] = []
for name in taxonomic:
scientific = normalize_species(name)
species = species_lookup.get(scientific)
if not species:
raise SystemExit(f"Missing species mapping in species.csv for: {scientific}")
taxa.append(
{
"scientific_name": species["scientific_name"],
"common_name": species["common_name"],
"species_code": species["species_code"],
"in_ebirdst": species["in_ebirdst"],
"birdlife_factsheet_url": species["birdlife_factsheet_url"],
"birds_of_the_world_url": species["birds_of_the_world_url"],
}
)
return taxa
def safe_project_id(value: str) -> str:
text = str(value or "").strip()
if text.isdigit():
return text
numeric = to_concept_id(text)
if numeric:
return numeric
normalized = normalize_doi(text)
match = re.search(r"zenodo\.(\d+)$", normalized)
if match:
return match.group(1)
return re.sub(r"[^A-Za-z0-9_-]", "_", text)
def safe_tag_id(value: str) -> str:
return re.sub(r"[^A-Za-z0-9_-]", "_", str(value or "").strip())
def parse_bool_string(value: str, field_name: str) -> bool:
text = value.strip().upper()
if text == "TRUE":
return True
if text == "FALSE":
return False
raise SystemExit(f"Invalid {field_name} value: {value}")
def parse_optional_url(value: str) -> str:
text = value.strip()
return "" if not text or text.upper() == "NA" else text
def load_species_lookup(csv_path: Path) -> Dict[str, Dict[str, Any]]:
required_columns = [
"scientific_name_input",
"Scientific_name",
"English_name_AviList",
"Species_code_Cornell_Lab",
"Birds_of_the_World_URL",
"BirdLife_DataZone_URL",
"in_ebirdst",
]
lookup: Dict[str, Dict[str, Any]] = {}
with csv_path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
header = reader.fieldnames or []
missing = [col for col in required_columns if col not in header]
if missing:
raise SystemExit(
f"Missing required columns in {csv_path.name}: {', '.join(missing)}"
)
for row in reader:
scientific_input = normalize_species(row["scientific_name_input"])
scientific_name = normalize_species(row["Scientific_name"])
entry = {
"scientific_name": scientific_name,
"common_name": row["English_name_AviList"].strip(),
"species_code": row["Species_code_Cornell_Lab"].strip(),
"birds_of_the_world_url": parse_optional_url(row["Birds_of_the_World_URL"]),
"birdlife_factsheet_url": parse_optional_url(row["BirdLife_DataZone_URL"]),
"in_ebirdst": parse_bool_string(row["in_ebirdst"], "in_ebirdst"),
}
for key in {scientific_input, scientific_name}:
existing = lookup.get(key)
if existing and existing != entry:
raise SystemExit(f"Conflicting species mapping for: {key}")
lookup[key] = entry
if not lookup:
raise SystemExit("species.csv could not be parsed.")
return lookup
def process_observations(
observations_path: Path,
) -> Tuple[
Dict[str, Dict[str, Optional[Any]]],
Dict[str, Dict[str, List[Dict[str, Any]]]],
Dict[str, List[Dict[str, Any]]],
]:
tag_stats: Dict[str, Dict[str, Optional[Any]]] = {}
tag_locations: Dict[str, Dict[str, List[Dict[str, Any]]]] = defaultdict(
lambda: {"equipment": [], "retrieval": []}
)
tag_observations: Dict[str, List[Dict[str, Any]]] = {}
obs_by_tag: Dict[str, List[Tuple[dt.datetime, Dict[str, Any]]]] = defaultdict(list)
age_class_map = {
"1": "Pullus",
"2": "Full-grown",
"3": "1yr",
"4": ">1yr",
"5": "2yr",
"6": ">2yr",
}
age_class_values = set(age_class_map.values())
with observations_path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
for row in reader:
tag_id = (row.get("tag_id") or "").strip()
if not tag_id:
continue
stamp = parse_datetime(row.get("datetime"))
if stamp is None:
continue
obs_by_tag[tag_id].append((stamp, row))
obs_type = (row.get("observation_type") or "").strip().lower()
if obs_type in {"equipment", "retrieval"}:
lat = to_float(row.get("latitude"))
lon = to_float(row.get("longitude"))
location_name = (row.get("location_name") or "").strip()
if lat is not None and lon is not None:
tag_locations[tag_id][obs_type].append(
{
"latitude": round(lat, 6),
"longitude": round(lon, 6),
"location_name": location_name,
}
)
for tag_id, entries in obs_by_tag.items():
entries.sort(key=lambda item: item[0])
sex = None
age_class = None
wing_length = None
obs_entries: List[Dict[str, Any]] = []
for _, row in entries:
if sex is None:
value = (row.get("sex") or "").strip()
if value and value.upper() != "U":
sex = value
if age_class is None:
value = (row.get("age_class") or "").strip()
if value and value.upper() != "U" and value not in {"0", "0.0"}:
mapped = age_class_map.get(value)
if mapped:
age_class = mapped
elif value in age_class_values:
age_class = value
if wing_length is None:
value = to_float(row.get("wing_length"))
if value is not None and value > 0:
wing_length = round(value, 2)
if sex is not None and age_class is not None and wing_length is not None:
break
for stamp, row in entries:
raw_age = (row.get("age_class") or "").strip()
mapped_age = age_class_map.get(raw_age) if raw_age else ""
if not mapped_age and raw_age in age_class_values:
mapped_age = raw_age
obs_entries.append(
{
"datetime": stamp.isoformat(),
"observation_type": (row.get("observation_type") or "").strip() or None,
"latitude": to_float(row.get("latitude")),
"longitude": to_float(row.get("longitude")),
"location_name": (row.get("location_name") or "").strip() or None,
"sex": (row.get("sex") or "").strip() or None,
"age_class": mapped_age or raw_age or None,
"wing_length": to_float(row.get("wing_length")),
}
)
tag_stats[tag_id] = {
"sex": sex,
"age_class": age_class,
"wing_length": wing_length,
}
tag_observations[tag_id] = obs_entries
return tag_stats, tag_locations, tag_observations
def process_project_assets(
output_dir: Path,
paths_path: Path,
staps_path: Path,
tag_to_project: Dict[str, str],
tag_meta_map: Dict[str, Dict[str, Any]],
project_known_locations: Dict[str, List[Dict[str, Any]]],
) -> set:
stap_stats: Dict[Tuple[str, str], List[float]] = defaultdict(lambda: [0.0, 0.0, 0.0])
with paths_path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
for row in reader:
tag_id = (row.get("tag_id") or "").strip()
if not tag_id:
continue
if (row.get("type") or "").strip().lower() != "most_likely":
continue
lon = to_float(row.get("lon"))
lat = to_float(row.get("lat"))
stap_id = (row.get("stap_id") or "").strip()
if lon is None or lat is None:
continue
if stap_id:
stats = stap_stats[(tag_id, stap_id)]
stats[0] += lon
stats[1] += lat
stats[2] += 1
project_staps: Dict[str, Dict[str, List[Dict[str, Any]]]] = defaultdict(
lambda: defaultdict(list)
)
with staps_path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
for row in reader:
tag_id = (row.get("tag_id") or "").strip()
if not tag_id:
continue
stap_id = (row.get("stap_id") or "").strip()
start_dt = parse_datetime(row.get("start"))
end_dt = parse_datetime(row.get("end"))
lon = to_float(row.get("known_lon"))
lat = to_float(row.get("known_lat"))
stats = stap_stats.get((tag_id, stap_id))
if stats and stats[2] > 0:
lon = stats[0] / stats[2]
lat = stats[1] / stats[2]
if start_dt is None or end_dt is None or lon is None or lat is None:
continue
duration = (end_dt - start_dt).total_seconds() / 86400.0
project_id = tag_to_project.get(tag_id)
if project_id:
project_staps[project_id][tag_id].append(
{
"stap_id": stap_id,
"longitude": round(lon, 5),
"latitude": round(lat, 5),
"duration_days": round(max(duration, 0.0), 2),
"start": start_dt.isoformat(),
"end": end_dt.isoformat(),
}
)
projects_dir = output_dir / "projects"
projects_dir.mkdir(parents=True, exist_ok=True)
project_tags: Dict[str, set] = defaultdict(set)
for tag_id, project_id in tag_to_project.items():
if project_id:
project_tags[project_id].add(tag_id)
project_ids_with_data = set(project_staps.keys())
for project_id in project_ids_with_data:
tag_ids = sorted(project_tags.get(project_id, set()))
tags_payload = []
for tag_id in tag_ids:
meta = tag_meta_map.get(tag_id, {})
staps = project_staps.get(project_id, {}).get(tag_id, [])
staps_sorted = sorted(staps, key=lambda item: item.get("start") or "")
tag_entry = {
"tag_id": tag_id,
"scientific_name": meta.get("scientific_name"),
"common_name": meta.get("common_name"),
"species_code": meta.get("species_code"),
"birdlife_factsheet_url": meta.get("birdlife_factsheet_url"),
"birds_of_the_world_url": meta.get("birds_of_the_world_url"),
"in_ebirdst": meta.get("in_ebirdst"),
"sex": meta.get("sex"),
"age_class": meta.get("age_class"),
"wing_length": meta.get("wing_length"),
"staps": staps_sorted,
}
tags_payload.append(tag_entry)
payload = {
"tags": tags_payload,
"known_locations": project_known_locations.get(project_id, []),
}
compact_dump(projects_dir / f"{safe_project_id(project_id)}.json", payload)
return project_ids_with_data
def resolve_project_id(
raw_project_id: str,
project_index: Dict[str, Dict[str, Any]],
record_to_project: Dict[str, str],
) -> str:
if not raw_project_id:
return ""
concept_candidate = to_concept_id(raw_project_id)
if concept_candidate and concept_candidate in project_index:
return concept_candidate
normalized_project_id = normalize_doi(raw_project_id)
if normalized_project_id in record_to_project:
return record_to_project[normalized_project_id]
if raw_project_id in record_to_project:
return record_to_project[raw_project_id]
return concept_candidate or raw_project_id
def process_tags(
tags_path: Path,
project_index: Dict[str, Dict[str, Any]],
record_to_project: Dict[str, str],
species_lookup: Dict[str, Dict[str, Any]],
) -> List[Dict[str, Any]]:
tags: List[Dict[str, Any]] = []
missing_species: List[str] = []
missing_project_tags: List[str] = []
unknown_project_ids: List[str] = []
seen_tags: set = set()
with tags_path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
for row in reader:
tag_id = (row.get("tag_id") or "").strip()
if not tag_id:
raise SystemExit("Missing tag_id in tags.csv.")
if tag_id in seen_tags:
raise SystemExit(f"Duplicate tag_id in tags.csv: {tag_id}")
seen_tags.add(tag_id)
scientific_name = normalize_species(row.get("scientific_name") or "")
raw_project_id = (row.get("datapackage_id") or "").strip()
project_id = resolve_project_id(raw_project_id, project_index, record_to_project)
if not raw_project_id:
missing_project_tags.append(tag_id or "unknown")
elif project_id not in project_index:
unknown_project_ids.append(raw_project_id)
species = species_lookup.get(scientific_name)
if scientific_name and not species:
missing_species.append(scientific_name)
tags.append(
{
"tag_id": tag_id,
"ring_number": row.get("ring_number"),
"scientific_name": species.get("scientific_name") if species else scientific_name,
"common_name": species.get("common_name") if species else None,
"species_code": species.get("species_code") if species else None,
"birdlife_factsheet_url": species.get("birdlife_factsheet_url") if species else "",
"birds_of_the_world_url": species.get("birds_of_the_world_url") if species else "",
"in_ebirdst": species.get("in_ebirdst") if species else None,
"manufacturer": row.get("manufacturer"),
"model": row.get("model"),
"firmware": row.get("firmware"),
"weight": row.get("weight"),
"attachment_type": row.get("attachment_type"),
"readout_method": row.get("readout_method"),
"tag_comments": row.get("tag_comments"),
"project_id": project_id,
}
)
if missing_species:
missing_sorted = sorted(set(missing_species))
preview = ", ".join(missing_sorted[:15])
raise SystemExit(
f"Missing species mapping in species.csv for {len(missing_sorted)} species: {preview}"
)
if missing_project_tags:
missing_sorted = sorted(set(missing_project_tags))
preview = ", ".join(missing_sorted[:10])
raise SystemExit(
f"Missing datapackage_id for {len(missing_sorted)} tags: {preview}"
)
if unknown_project_ids:
unknown_sorted = sorted(set(unknown_project_ids))
preview = ", ".join(unknown_sorted[:10])
raise SystemExit(
f"Unknown datapackage_id values for {len(unknown_sorted)} tags: {preview}"
)
return tags
def load_staps(
staps_path: Path,
) -> Tuple[
Dict[Tuple[str, str], Tuple[Optional[dt.datetime], Optional[dt.datetime]]],
Dict[str, Tuple[Optional[dt.datetime], Optional[dt.datetime]]],
]:
staps_index: Dict[Tuple[str, str], Tuple[Optional[dt.datetime], Optional[dt.datetime]]] = {}
tag_ranges: Dict[str, Tuple[Optional[dt.datetime], Optional[dt.datetime]]] = {}
with staps_path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
for row in reader:
tag_id = (row.get("tag_id") or "").strip()
stap_id = (row.get("stap_id") or "").strip()
if not tag_id or not stap_id:
continue
start_dt = parse_datetime(row.get("start"))
end_dt = parse_datetime(row.get("end"))
if start_dt is None or end_dt is None:
continue
staps_index[(tag_id, stap_id)] = (start_dt, end_dt)
current_start, current_end = tag_ranges.get(tag_id, (None, None))
if current_start is None or start_dt < current_start:
current_start = start_dt
if current_end is None or end_dt > current_end:
current_end = end_dt
tag_ranges[tag_id] = (current_start, current_end)
return staps_index, tag_ranges
def process_paths(
paths_path: Path,
staps_path: Path,
tag_meta_map: Dict[str, Dict[str, Any]],
tag_to_project: Dict[str, Optional[str]],
project_title_map: Dict[str, str],
) -> Dict[str, Any]:
staps_index, tag_ranges = load_staps(staps_path)
stap_accum: Dict[Tuple[str, str], List[float]] = defaultdict(lambda: [0.0, 0.0, 0.0])
with paths_path.open(newline="", encoding="utf-8") as handle:
reader = csv.DictReader(handle)
for row in reader:
tag_id = (row.get("tag_id") or "").strip()
if not tag_id:
continue
if (row.get("type") or "").strip().lower() != "most_likely":
continue
lon = to_float(row.get("lon"))
lat = to_float(row.get("lat"))
stap_id = (row.get("stap_id") or "").strip()
if lon is None or lat is None or not stap_id:
continue
bucket = stap_accum[(tag_id, stap_id)]
bucket[0] += lon
bucket[1] += lat
bucket[2] += 1
tag_segments: Dict[str, List[Tuple[dt.datetime, dt.datetime, float, float]]] = defaultdict(list)
for (tag_id, stap_id), (sum_lon, sum_lat, count) in stap_accum.items():
if count == 0:
continue
start_dt, end_dt = staps_index.get((tag_id, stap_id), (None, None))
if start_dt is None or end_dt is None or end_dt < start_dt:
continue
lon = round(sum_lon / count, 5)
lat = round(sum_lat / count, 5)
tag_segments[tag_id].append((start_dt, end_dt, lon, lat))
tags: List[Dict[str, Any]] = []
for tag_id, segments in tag_segments.items():
range_start, range_end = tag_ranges.get(tag_id, (None, None))
if range_start is None or range_end is None:
continue
max_end = range_start + dt.timedelta(days=365)
display_end = min(range_end, max_end)
if display_end <= range_start:
continue
segments.sort(key=lambda item: item[0])
positions: List[Optional[List[float]]] = [None] * 365
has_positions = False
segment_index = 0
for offset in range(365):
date = range_start.date() + dt.timedelta(days=offset)
sample_time = dt.datetime(
date.year,
date.month,
date.day,
12,
0,
0,
tzinfo=range_start.tzinfo,
)
if sample_time < range_start or sample_time > display_end:
continue
while segment_index < len(segments) and segments[segment_index][1] < sample_time:
segment_index += 1
if segment_index >= len(segments):
break
seg_start, seg_end, lon, lat = segments[segment_index]
if not (seg_start <= sample_time <= seg_end):
continue
day_index = sample_time.timetuple().tm_yday
day_index = min(day_index, 365)
coord = [lon, lat]
positions[day_index - 1] = coord
has_positions = True
if not has_positions:
continue
meta = tag_meta_map.get(tag_id, {})
project_id = tag_to_project.get(tag_id)
tags.append(
{
"tag_id": tag_id,
"scientific_name": meta.get("scientific_name"),
"common_name": meta.get("common_name"),