-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathicar_model.py
More file actions
1500 lines (1275 loc) · 68.6 KB
/
Copy pathicar_model.py
File metadata and controls
1500 lines (1275 loc) · 68.6 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
# In this script, we house a class that fits various Stan models to a processed dataset of urban street flooding conditions in New York City.
# Set cache directory BEFORE importing stan/httpstan
# This avoids disk quota issues on home directory
import os
from pathlib import Path
_project_root = Path(__file__).parent.resolve()
_cache_dir = _project_root / ".cache"
os.environ["XDG_CACHE_HOME"] = str(_cache_dir)
## Module Imports
import util
import config
from geometry_config import GeometryType, get_geometry_config
from IPython import embed
import json
from copy import deepcopy
from sklearn.metrics import roc_auc_score
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
import datetime
import logger
import multiprocessing
if multiprocessing.get_start_method(allow_none=True) is None:
multiprocessing.set_start_method("fork")
# Patch aiohttp timeout for large models (CBG has ~6800 areas)
# Default timeout is too short to transfer large fit results
import aiohttp
_original_client_session_init = aiohttp.ClientSession.__init__
def _patched_client_session_init(self, *args, **kwargs):
if 'timeout' not in kwargs:
# 30 minute total timeout for large models
kwargs['timeout'] = aiohttp.ClientTimeout(total=1800)
_original_client_session_init(self, *args, **kwargs)
aiohttp.ClientSession.__init__ = _patched_client_session_init
import pandas as pd
import stan as stan
import numpy as np
from scipy.stats import pearsonr, spearmanr, wasserstein_distance
import arviz as az
from scipy.special import expit
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import nest_asyncio
import sys
import warnings
import argparse
from generate_maps import generate_maps
from refresh_cache import refresh_cache
from analysis_df import generate_nyc_analysis_df
LATEX_PLOTTING=False
if LATEX_PLOTTING:
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
nest_asyncio.apply()
## Class Definition
class ICAR_MODEL:
"""
Intrinsic Conditional Autoregressive (ICAR) model for urban street flooding analysis.
This class implements Bayesian spatial modeling for flood detection using dashcam imagery.
It supports multiple prior specifications, external covariates, and various estimation
parameters for comprehensive flooding analysis.
Attributes:
N_ANNOTATED_CLASSIFIED_NEGATIVE (int): Number of annotated negative samples
N_ANNOTATED_CLASSIFIED_POSITIVE (int): Number of annotated positive samples
N_SIMULATED_TRACTS (int): Number of tracts for simulated data
annotations_have_locations (bool): Whether annotations include spatial locations
use_simulated_data (bool): Whether to use simulated or empirical data
use_external_covariates (bool): Whether to include external covariates
icar_prior_setting (str): Type of spatial prior ("none", "icar", "proper", "just_model_p_y")
ESTIMATE_PARAMETERS (list): Parameters to estimate from the model
models (dict): Dictionary of Stan model specifications
logger: Logger instance for tracking progress
Example:
>>> model = ICAR_MODEL(
... PREFIX='flooding_analysis',
... ICAR_PRIOR_SETTING="icar",
... ANNOTATIONS_HAVE_LOCATIONS=True,
... EXTERNAL_COVARIATES=True,
... ESTIMATE_PARAMS=['p_y', 'at_least_one_positive_image_by_area'],
... EMPIRICAL_DATA_PATH="data/processed/flooding_ct_dataset.csv", # or flooding_cbg_dataset.csv
... geometry_type="ct" # or "cbg", "cb"
... )
>>> model.load_data()
>>> fit = model.fit(CYCLES=1, WARMUP=1000, SAMPLES=1500)
"""
def __init__(
self,
PREFIX='',
ICAR_PRIOR_SETTING="none",
ANNOTATIONS_HAVE_LOCATIONS=True,
EXTERNAL_COVARIATES=False,
SIMULATED_DATA=False,
ESTIMATE_PARAMS=[],
EMPIRICAL_DATA_PATH="",
adj=[],
adj_matrix_storage=None,
downsample_frac=1,
DOWNSAMPLE_ALL_IMAGES=False,
downsample_seed=None,
trim_to_median: bool = False,
trim_remove_frac: float | None = None,
USE_CATCH_BASINS=False,
geometry_type: str | GeometryType = "ct",
):
refresh_cache()
print(SIMULATED_DATA)
# Handle geometry type
if isinstance(geometry_type, str):
geometry_type = GeometryType(geometry_type.lower())
self.geometry_type = geometry_type
self.geometry_config = get_geometry_config(geometry_type)
self.id_column = self.geometry_config.id_column
# Sanity checks on user inputs
# EMPIRICAL_DATA_PATH should not be set if we are using simulated data
if SIMULATED_DATA:
assert EMPIRICAL_DATA_PATH == ""
elif EMPIRICAL_DATA_PATH:
assert not SIMULATED_DATA
# adj_matrix_storage should be set if adj is set
if adj:
assert adj_matrix_storage is not None
# if adj_matrix_storage is set, adj should be set
# if adj_matrix_storage is False, adj should be a list of two string file paths
# if adj_matrix_storage is True, adj should be a list of one string file path
if adj_matrix_storage:
assert adj
assert isinstance(adj, list)
if adj_matrix_storage is True:
assert len(adj) == 1
assert isinstance(adj[0], str)
else:
assert len(adj) == 2
assert isinstance(adj[0], str)
assert isinstance(adj[1], str)
# This block of variables is fixed across modeling fitting runs,
# and represent metadata about real dataset, or simulated data
# Real dataset metadata
self.N_ANNOTATED_CLASSIFIED_NEGATIVE = 500
self.N_ANNOTATED_CLASSIFIED_POSITIVE = 500
self.N_ANNOTATED_CLASSIFIED_NEGATIVE_TRUE_POSITIVE = 3
self.N_ANNOTATED_CLASSIFIED_POSITIVE_TRUE_POSITIVE = 329
self.TOTAL_PRED_POSITIVE = 1465
self.TOTAL_PRED_NEGATIVE = 924747
# Simulated data metadata
self.N_SIMULATED_TRACTS = 1000
# These flags control the behavior of the model fitting routine
self.annotations_have_locations = ANNOTATIONS_HAVE_LOCATIONS
self.use_simulated_data = SIMULATED_DATA
self.use_external_covariates = EXTERNAL_COVARIATES
self.use_catch_basins = USE_CATCH_BASINS
self.downsample_frac = downsample_frac
self.downsample_all_images = DOWNSAMPLE_ALL_IMAGES
self.downsample_seed = downsample_seed
self.trim_to_median = trim_to_median
self.trim_remove_frac = trim_remove_frac
self.trim_history = []
self.EMPIRICAL_DATA_PATH = EMPIRICAL_DATA_PATH
self.icar_prior_setting = ICAR_PRIOR_SETTING
assert self.icar_prior_setting in ["icar"], "Only 'icar' setting is supported in this artifact."
self.VALID_ESTIMATE_PARAMETERS = ["p_y", "at_least_one_positive_image_by_area", "at_least_one_positive_image_by_area_if_you_have_100_images"]
self.ADDITIONAL_PARAMS_TO_SAVE = []
self.ESTIMATE_PARAMETERS = ESTIMATE_PARAMS
for p in self.ESTIMATE_PARAMETERS:
assert p in self.VALID_ESTIMATE_PARAMETERS
# This dictionary stores the available stan models
self.models = {
"ICAR_prior_annotations_have_locations": open(
"stan_models/ICAR_prior_annotations_have_locations.stan"
).read(),
"weighted_ICAR_prior": open(
"stan_models/weighted_ICAR_prior.stan"
).read(),
}
self.logger = logger.setup_logger(f"ICAR_MODEL: {ICAR_PRIOR_SETTING}, ahl {ANNOTATIONS_HAVE_LOCATIONS}, simulated {SIMULATED_DATA}")
self.logger.setLevel("INFO")
self.logger.info("ICAR_MODEL instance initialized.")
self.adj_path = adj
self.adj_matrix_storage = adj_matrix_storage
# other misc sanity checks
# cannot use the at_least_one_positive_image_by_area parameter if additional annotation location data is not utilized
if not self.annotations_have_locations:
assert 'at_least_one_positive_image_by_area' not in self.ESTIMATE_PARAMETERS
# if there's a non-blank prefix, prepend it to runid
if PREFIX:
self.logger.info(f"Setting prefix to {PREFIX}")
self.RUNID = PREFIX
else:
self.logger.info("No prefix set.")
self.RUNID = ""
def parse_data_for_validation(self):
"""
Parse and prepare observed data for validation and debugging.
Converts numpy arrays to lists and handles int64 serialization issues
that can occur when saving data to JSON format.
Returns:
dict: Copy of observed data with numpy arrays converted to lists
and int64 values converted to regular integers
"""
# write jsonified observed data to file for debugging
# need to convert numpy arrays to lists
observed_data_copy = self.data_to_use["observed_data"].copy()
# observed_data_copy is a dict
for k in observed_data_copy.keys():
if isinstance(observed_data_copy[k], np.ndarray):
observed_data_copy[k] = observed_data_copy[k].tolist()
# serialized int64
if isinstance(observed_data_copy[k], np.int64):
observed_data_copy[k] = int(observed_data_copy[k])
# serialize nd arrays with int 64 elements
if isinstance(observed_data_copy[k], list):
for i in range(len(observed_data_copy[k])):
if isinstance(observed_data_copy[k][i], np.int64):
observed_data_copy[k][i] = int(observed_data_copy[k][i])
self.logger.info(
"Successfully converted the observed data into numpy arrays for inspection."
)
return observed_data_copy
def load_data(self):
"""
Load and prepare data for ICAR model fitting.
Depending on configuration, either generates simulated data or loads
empirical data from file. Handles data validation, downsampling, and
external covariates processing.
The loaded data is stored in self.data_to_use and contains:
- observed_data: Dictionary with Stan model inputs
- external covariates (if enabled)
- adjacency information (if provided)
Raises:
FileNotFoundError: If empirical data file is not found
ValueError: If data validation fails
"""
if self.use_simulated_data:
self.logger.info("Generating simulated data.")
N = self.N_SIMULATED_TRACTS
self.data_to_use = util.generate_simulated_data(
N=N,
images_per_location=1000,
total_annotated_classified_negative=self.N_ANNOTATED_CLASSIFIED_NEGATIVE,
total_annotated_classified_positive=self.N_ANNOTATED_CLASSIFIED_POSITIVE,
icar_prior_setting=self.icar_prior_setting,
annotations_have_locations=self.annotations_have_locations,
)
if self.downsample_frac < 1:
mode = "all images" if self.downsample_all_images else "annotated images"
self.logger.info(f"Downsampling {mode} with downsample_frac={self.downsample_frac}.")
self.data_to_use = self.downsample_data(
self.data_to_use,
downsample_frac=self.downsample_frac,
downsample_all_images=self.downsample_all_images,
seed=self.downsample_seed,
)
self.logger.success("Successfully generated simulated data.")
else:
self.logger.info("Reading empirical data.")
self.data_to_use, external_covariates_info = util.read_real_data(
fpath=self.EMPIRICAL_DATA_PATH,
annotations_have_locations=self.annotations_have_locations,
adj=self.adj_path,
adj_matrix_storage=self.adj_matrix_storage,
use_external_covariates=self.use_external_covariates,
use_catch_basins=self.use_catch_basins,
id_column=self.id_column
)
if self.use_external_covariates:
# write external covariates to file for debugging
print(external_covariates_info)
external_covariates_info = pd.DataFrame.from_dict(external_covariates_info['external_covariates'])
with open(f"runs/{self.RUNID}/external_covariates.csv", "w") as f:
external_covariates_info.to_csv(f)
self.logger.success("Successfully read empirical data.")
if self.trim_to_median:
self.logger.info(
"Applying trim_to_median (remove_frac=%s)."
% (self.trim_remove_frac if self.trim_remove_frac is not None else (1.0 - float(self.downsample_frac)))
)
self.data_to_use = self.iterative_trim_to_median(
self.data_to_use,
remove_frac=self.trim_remove_frac,
)
self.logger.success("Successfully applied trim_to_median.")
if (not self.trim_to_median) and (self.downsample_frac < 1):
mode = "all images" if self.downsample_all_images else "annotated images"
self.logger.info(f"Downsampling {mode} with downsample_frac={self.downsample_frac}.")
self.data_to_use = self.downsample_data(
self.data_to_use,
downsample_frac=self.downsample_frac,
downsample_all_images=self.downsample_all_images,
seed=self.downsample_seed,
)
# validate observed data
if self.trim_to_median:
# trim_to_median intentionally changes annotated totals, which breaks the strict validation
self.logger.info("Skipping strict validate_observed_data (trim_to_median enabled).")
else:
observed_data_copy = self.parse_data_for_validation()
util.validate_observed_data(
observed_data_copy, self.annotations_have_locations, self.downsample_frac
)
self.logger.success("Successfully validated the observed data.")
del observed_data_copy
def fit(self, CYCLES=1, WARMUP=1000, SAMPLES=1500, data_already_loaded=False):
# pass in data_already_loaded = True if you want to use data that's already been loaded in.
# by default the method reloads the data.
if not data_already_loaded:
self.RUNID = self.RUNID + "_" + datetime.datetime.now().strftime("%Y%m%d-%H%M")
# add parent dirs that split runs based on simulated or empirical, annotations_have_locations, and icar_prior_setting
self.RUNID = f"icar_{self.icar_prior_setting}/simulated_{self.use_simulated_data}/ahl_{self.annotations_have_locations}/covariates_{self.use_external_covariates}/{self.RUNID}"
os.makedirs(f"runs/{self.RUNID}", exist_ok=True)
for i in range(CYCLES):
if not data_already_loaded:
self.load_data()
if self.icar_prior_setting == "icar":
self.logger.info("Building model with ICAR prior.")
self.data_to_use["observed_data"]["use_ICAR_prior"] = 1
if self.annotations_have_locations:
self.logger.info(
"Building model with annotations have locations."
)
self.logger.info("Building model with use_external_covariates = %s" % self.use_external_covariates)
model_name = "ICAR_prior_annotations_have_locations"
self.logger.info(f"Using model specification: {model_name}")
model = stan.build(
self.models[model_name],
data=self.data_to_use["observed_data"],
)
self.ADDITIONAL_PARAMS_TO_SAVE += ['spatial_sigma', 'external_covariate_beta']
else:
raise ValueError("This artifact requires annotations_have_locations=True.")
self.logger.info(f"Successfully built the model, with use_icar_prior: {self.data_to_use['observed_data']['use_ICAR_prior']}.")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fit = model.sample(num_chains=4, num_warmup=WARMUP, num_samples=SAMPLES)
print(az.summary(fit))
df = fit.to_frame()
self.logger.success("Successfully sampled the model.")
# write metadata to file
# ANNOTATIONS_HAVE_LOCATIONS, SIMULATED_DATA, CYCLES, WARMUP, SAMPLES, use_icar_prior, icar_prior_weight, icar_prior_setting
# N_ANNOTATED_CLASSIFIED_NEGATIVE, N_ANNOTATED_CLASSIFIED_POSITIVE, N_ANNOTATED_CLASSIFIED_NEGATIVE_TRUE_POSITIVE, N_ANNOTATED_CLASSIFIED_POSITIVE_TRUE_POSITIVE, TOTAL_PRED_POSITIVE, TOTAL_PRED_NEGATIVE, N_SIMULATED_TRACTS
# self.adj, self.adj_matrix_storage
metadata = {
"RUNID": self.RUNID,
"ANNOTATIONS_HAVE_LOCATIONS": self.annotations_have_locations,
"SIMULATED_DATA": self.use_simulated_data,
"EXTERNAL_COVARIATES": self.use_external_covariates,
"USE_CATCH_BASINS": self.use_catch_basins,
"CYCLES": CYCLES,
"WARMUP": WARMUP,
"SAMPLES": SAMPLES,
"DOWNSAMPLE_ALL_IMAGES": self.downsample_all_images,
"downsample_frac": self.downsample_frac,
"downsample_seed": self.downsample_seed,
"trim_to_median": self.trim_to_median,
"trim_remove_frac": None if self.trim_remove_frac is None else float(self.trim_remove_frac),
"trim_history": self.trim_history,
"use_icar_prior": self.data_to_use["observed_data"]["use_ICAR_prior"],
"icar_prior_setting": self.icar_prior_setting,
"N_ANNOTATED_CLASSIFIED_NEGATIVE": self.N_ANNOTATED_CLASSIFIED_NEGATIVE,
"N_ANNOTATED_CLASSIFIED_POSITIVE": self.N_ANNOTATED_CLASSIFIED_POSITIVE,
"N_ANNOTATED_CLASSIFIED_NEGATIVE_TRUE_POSITIVE": self.N_ANNOTATED_CLASSIFIED_NEGATIVE_TRUE_POSITIVE,
"N_ANNOTATED_CLASSIFIED_POSITIVE_TRUE_POSITIVE": self.N_ANNOTATED_CLASSIFIED_POSITIVE_TRUE_POSITIVE,
"TOTAL_PRED_POSITIVE": self.TOTAL_PRED_POSITIVE,
"TOTAL_PRED_NEGATIVE": self.TOTAL_PRED_NEGATIVE,
"N_SIMULATED_TRACTS": self.N_SIMULATED_TRACTS,
"adj": self.adj_path,
"adj_matrix_storage": self.adj_matrix_storage,
}
with open(f"runs/{self.RUNID}/metadata.json", "w") as f:
# write with a new line between each key-value pair
f.write(json.dumps(metadata, indent=4))
return fit, df
def divide_data_into_train_and_test_set(self, full_dataset, train_frac=0.7):
"""
Partitions the images into a train and test set. For each Census tract, randomly
assigns a fraction of the images to the train set, and the rest to the test set.
This is a bit tricky to do because the raw data comes as counts.
"""
train_data = {}
test_data = {}
full_dataset = deepcopy(full_dataset)
# add a convenience field because it makes the rest of the code easier to write succinctly.
full_dataset['observed_data']['n_non_annotated_by_area_classified_negative'] = full_dataset['observed_data']['n_non_annotated_by_area'] - full_dataset['observed_data']['n_non_annotated_by_area_classified_positive']
for k in full_dataset['observed_data']:
if k in ['N', 'N_edges', 'node1', 'node2', 'tract_id', 'geoid', 'center_of_phi_offset_prior', 'external_covariates', 'n_external_covariates']:
train_data[k] = deepcopy(full_dataset['observed_data'][k])
test_data[k] = deepcopy(full_dataset['observed_data'][k])
for k in ['n_classified_positive_annotated_positive_by_area',
'n_classified_positive_annotated_negative_by_area',
'n_classified_negative_annotated_negative_by_area',
'n_classified_negative_annotated_positive_by_area',
'n_non_annotated_by_area_classified_positive',
'n_non_annotated_by_area_classified_negative']:
train_data[k] = np.random.binomial(full_dataset['observed_data'][k], train_frac)
test_data[k] = full_dataset['observed_data'][k] - train_data[k]
assert (train_data[k] >= 0).all()
assert (test_data[k] >= 0).all()
train_data['n_non_annotated_by_area'] = train_data['n_non_annotated_by_area_classified_positive'] + train_data['n_non_annotated_by_area_classified_negative']
test_data['n_non_annotated_by_area'] = test_data['n_non_annotated_by_area_classified_positive'] + test_data['n_non_annotated_by_area_classified_negative']
train_data['n_images_by_area'] = train_data['n_non_annotated_by_area'] + train_data['n_classified_positive_annotated_positive_by_area'] + train_data['n_classified_positive_annotated_negative_by_area'] + train_data['n_classified_negative_annotated_negative_by_area'] + train_data['n_classified_negative_annotated_positive_by_area']
test_data['n_images_by_area'] = test_data['n_non_annotated_by_area'] + test_data['n_classified_positive_annotated_positive_by_area'] + test_data['n_classified_positive_annotated_negative_by_area'] + test_data['n_classified_negative_annotated_negative_by_area'] + test_data['n_classified_negative_annotated_positive_by_area']
train_data['n_classified_positive_by_area'] = train_data['n_classified_positive_annotated_positive_by_area'] + train_data['n_classified_positive_annotated_negative_by_area'] + train_data['n_non_annotated_by_area_classified_positive']
test_data['n_classified_positive_by_area'] = test_data['n_classified_positive_annotated_positive_by_area'] + test_data['n_classified_positive_annotated_negative_by_area'] + test_data['n_non_annotated_by_area_classified_positive']
for k in full_dataset['observed_data'].keys():
if k not in ['N', 'N_edges', 'node1', 'node2', 'tract_id', 'geoid', 'center_of_phi_offset_prior', 'external_covariates', 'n_external_covariates']:
assert (train_data[k] + test_data[k] == full_dataset['observed_data'][k]).all()
print("With a train frac of %2.3f, train set has %i total images; test set has %i" %
(train_frac, train_data['n_images_by_area'].sum(), test_data['n_images_by_area'].sum()))
return train_data, test_data
def downsample_data(self, full_dataset, downsample_frac=0.1, downsample_all_images=False, seed=None):
"""
Downsample the dataset by downsample_frac.
If downsample_all_images is False, only annotated images are downsampled.
If True, all base count fields (annotated and non-annotated) are downsampled
before recomputing derived totals.
``seed`` makes the random binomial thinning reproducible. When None, the
draw is non-deterministic (preserving prior behavior).
"""
rng = np.random.default_rng(seed)
if seed is not None:
self.logger.info(f"Downsampling with fixed seed={seed}.")
downsampled_data = deepcopy(full_dataset)
observed = downsampled_data['observed_data']
original_observed = full_dataset['observed_data']
if downsample_all_images:
# Ensure we have both positive and negative non-annotated counts
if 'n_non_annotated_by_area_classified_negative' not in original_observed:
inferred_negative = (
original_observed['n_non_annotated_by_area']
- original_observed['n_non_annotated_by_area_classified_positive']
)
assert (inferred_negative >= 0).all()
original_observed['n_non_annotated_by_area_classified_negative'] = inferred_negative
base_fields = [
'n_classified_positive_annotated_positive_by_area',
'n_classified_positive_annotated_negative_by_area',
'n_classified_negative_annotated_negative_by_area',
'n_classified_negative_annotated_positive_by_area',
'n_non_annotated_by_area_classified_positive',
'n_non_annotated_by_area_classified_negative',
]
for k in base_fields:
observed[k] = rng.binomial(original_observed[k], downsample_frac)
assert (observed[k] >= 0).all()
observed['n_annotated_by_area'] = (
observed['n_classified_positive_annotated_positive_by_area'] +
observed['n_classified_positive_annotated_negative_by_area'] +
observed['n_classified_negative_annotated_negative_by_area'] +
observed['n_classified_negative_annotated_positive_by_area']
)
observed['n_non_annotated_by_area'] = (
observed['n_non_annotated_by_area_classified_positive'] +
observed['n_non_annotated_by_area_classified_negative']
)
observed['n_images_by_area'] = observed['n_non_annotated_by_area'] + observed['n_annotated_by_area']
observed['n_classified_positive_by_area'] = (
observed['n_classified_positive_annotated_positive_by_area'] +
observed['n_classified_positive_annotated_negative_by_area'] +
observed['n_non_annotated_by_area_classified_positive']
)
observed['total_annotated_classified_positive'] = (
observed['n_classified_positive_annotated_positive_by_area'] +
observed['n_classified_positive_annotated_negative_by_area']
)
observed['total_annotated_classified_negative'] = (
observed['n_classified_negative_annotated_positive_by_area'] +
observed['n_classified_negative_annotated_negative_by_area']
)
self.logger.info(
f"Original total images sum: {original_observed['n_images_by_area'].sum()}; "
f"downsampled total images sum: {observed['n_images_by_area'].sum()}"
)
else:
original_observed['n_annotated_by_area'] = (
original_observed['n_classified_positive_annotated_positive_by_area'] +
original_observed['n_classified_positive_annotated_negative_by_area'] +
original_observed['n_classified_negative_annotated_negative_by_area'] +
original_observed['n_classified_negative_annotated_positive_by_area']
)
annotated_fields = [
'n_classified_positive_annotated_positive_by_area',
'n_classified_positive_annotated_negative_by_area',
'n_classified_negative_annotated_negative_by_area',
'n_classified_negative_annotated_positive_by_area'
]
for k in annotated_fields:
observed[k] = rng.binomial(
original_observed[k],
downsample_frac
)
assert (observed[k] >= 0).all()
observed['n_annotated_by_area'] = (
observed['n_classified_positive_annotated_positive_by_area'] +
observed['n_classified_positive_annotated_negative_by_area'] +
observed['n_classified_negative_annotated_negative_by_area'] +
observed['n_classified_negative_annotated_positive_by_area']
)
observed['n_images_by_area'] = (
observed['n_non_annotated_by_area'] +
observed['n_annotated_by_area']
)
observed['n_classified_positive_by_area'] = (
observed['n_classified_positive_annotated_positive_by_area'] +
observed['n_classified_positive_annotated_negative_by_area'] +
observed['n_non_annotated_by_area_classified_positive']
)
observed['total_annotated_classified_positive'] = (
observed['n_classified_positive_annotated_positive_by_area'] +
observed['n_classified_positive_annotated_negative_by_area']
)
observed['total_annotated_classified_negative'] = (
observed['n_classified_negative_annotated_positive_by_area'] +
observed['n_classified_negative_annotated_negative_by_area']
)
self.logger.info(f"Original annotated images: {original_observed['n_annotated_by_area'].sum()}")
self.logger.info(f"Downsampled annotated images: {observed['n_annotated_by_area'].sum()}")
self.logger.info(f"Total images after downsampling: {observed['n_images_by_area'].sum()}")
return downsampled_data
def iterative_trim_to_median(
self,
full_dataset,
remove_frac: float | None = None,
):
"""
Trim high-count tracts toward the current median count to fill a global removal budget.
This operates purely on per-tract count fields (no per-image sampling available).
We compute a global removal budget (\"moat\") as remove_frac * total_images,
and iteratively remove counts from high-count tracts until the budget is filled.
Each pass:
- Compute median_i (integer floor) from current n_images_by_area (pre-trim)
- Consider tracts with Ci > median_i, with per-tract capacity cap_i = Ci - median_i
- Allocate the pass removal target across high tracts proportionally to cap_i,
respecting cap_i (so we don't drop below the current median within a pass)
- For each tract, allocate removals across 6 base fields (without replacement):
- 4 annotated fields
- non-annotated classified positive
- non-annotated classified negative (inferred as n_non_annotated - n_non_annotated_pos)
- Recompute derived totals and record Wasserstein/EMD vs constant-at-median_i target.
"""
if not self.annotations_have_locations:
raise ValueError("iterative_trim_to_median requires annotations_have_locations=True.")
# Default: if remove_frac not provided, use trim_remove_frac, else fall back to (1 - downsample_frac)
if remove_frac is None:
if self.trim_remove_frac is not None:
remove_frac = self.trim_remove_frac
else:
remove_frac = 1.0 - float(self.downsample_frac)
if remove_frac <= 0 or remove_frac >= 1:
raise ValueError(f"remove_frac must be in (0, 1); got {remove_frac}.")
trimmed = deepcopy(full_dataset)
observed = trimmed["observed_data"]
required = [
"n_images_by_area",
"n_classified_positive_by_area",
"n_classified_positive_annotated_positive_by_area",
"n_classified_positive_annotated_negative_by_area",
"n_classified_negative_annotated_negative_by_area",
"n_classified_negative_annotated_positive_by_area",
"n_non_annotated_by_area",
"n_non_annotated_by_area_classified_positive",
]
missing = [k for k in required if k not in observed]
if missing:
raise ValueError(f"Missing required observed_data keys for trim_to_median: {missing}")
def _as_int_array(x):
arr = np.asarray(x)
if np.any(arr < 0):
raise ValueError("Negative counts encountered in observed_data before trimming.")
return arr.astype(np.int64, copy=True)
# Pull out base fields as int arrays we will mutate.
ann_pp = _as_int_array(observed["n_classified_positive_annotated_positive_by_area"])
ann_pn = _as_int_array(observed["n_classified_positive_annotated_negative_by_area"])
ann_nn = _as_int_array(observed["n_classified_negative_annotated_negative_by_area"])
ann_np = _as_int_array(observed["n_classified_negative_annotated_positive_by_area"])
non_total = _as_int_array(observed["n_non_annotated_by_area"])
non_pos = _as_int_array(observed["n_non_annotated_by_area_classified_positive"])
if np.any(non_pos > non_total):
raise ValueError("Found n_non_annotated_by_area_classified_positive > n_non_annotated_by_area.")
def _recompute_derived_fields():
observed["n_classified_positive_annotated_positive_by_area"] = ann_pp
observed["n_classified_positive_annotated_negative_by_area"] = ann_pn
observed["n_classified_negative_annotated_negative_by_area"] = ann_nn
observed["n_classified_negative_annotated_positive_by_area"] = ann_np
observed["n_non_annotated_by_area"] = non_total
observed["n_non_annotated_by_area_classified_positive"] = non_pos
observed["n_annotated_by_area"] = ann_pp + ann_pn + ann_nn + ann_np
observed["n_images_by_area"] = observed["n_annotated_by_area"] + non_total
observed["n_classified_positive_by_area"] = ann_pp + ann_pn + non_pos
# Keep parity with existing downsampling code, even though names are confusing.
observed["total_annotated_classified_positive"] = ann_pp + ann_pn
observed["total_annotated_classified_negative"] = ann_np + ann_nn
# Lightweight consistency checks
if np.any(observed["n_images_by_area"] < 0):
raise ValueError("Negative n_images_by_area after trimming.")
if np.any(observed["n_classified_positive_by_area"] < 0):
raise ValueError("Negative n_classified_positive_by_area after trimming.")
if np.any(non_total < 0) or np.any(non_pos < 0):
raise ValueError("Negative non-annotated counts after trimming.")
if np.any(non_pos > non_total):
raise ValueError("non_pos exceeded non_total after trimming.")
def _sample_multivariate_hypergeometric(counts6: np.ndarray, nremove: int) -> np.ndarray:
"""
Sample removal counts across categories *without replacement*.
Uses sequential hypergeometric draws (exact for multivariate hypergeometric).
"""
counts6 = counts6.astype(np.int64, copy=False)
if nremove <= 0:
return np.zeros_like(counts6)
total = int(counts6.sum())
nremove = min(int(nremove), total)
removed = np.zeros_like(counts6)
remaining_total = total
remaining_to_remove = nremove
for j in range(len(counts6) - 1):
if remaining_to_remove <= 0:
break
ngood = int(counts6[j])
if ngood <= 0:
remaining_total -= ngood
continue
nbad = remaining_total - ngood
draw = int(np.random.hypergeometric(ngood, nbad, remaining_to_remove))
draw = min(draw, ngood, remaining_to_remove)
removed[j] = draw
remaining_to_remove -= draw
remaining_total -= ngood
removed[-1] = remaining_to_remove
if removed[-1] > counts6[-1]:
raise ValueError("Internal sampling error: removal exceeded available count in last category.")
return removed
self.trim_history = []
_recompute_derived_fields()
total_images_start = int(_as_int_array(observed["n_images_by_area"]).sum())
removal_budget_target = int(np.ceil(float(remove_frac) * total_images_start))
remaining_budget = removal_budget_target
self.logger.info(
"trim_to_median: starting moat fill remove_frac=%.4f total_images=%d budget=%d"
% (float(remove_frac), total_images_start, removal_budget_target)
)
p = 0
safety_cap = 10_000 # hard safety cap to prevent infinite loops in case of unexpected data/pathology
while remaining_budget > 0:
if p >= safety_cap:
raise ValueError(f"trim_to_median: exceeded safety cap of {safety_cap} passes.")
if remaining_budget <= 0:
break
C_before = _as_int_array(observed["n_images_by_area"])
mean_before = float(C_before.mean())
median_target = int(np.median(C_before)) # integer floor if even N
cap = C_before - median_target
cap[cap < 0] = 0
sum_cap = int(cap.sum())
if sum_cap <= 0:
# Degenerate case: no tracts above median (e.g., uniform counts). To still fill the moat,
# allow removal from all tracts proportionally to their current counts.
cap = C_before.copy()
cap[cap < 0] = 0
sum_cap = int(cap.sum())
if sum_cap <= 0:
raise ValueError("trim_to_median: cannot fill moat (no images left to remove).")
pass_target = min(int(remaining_budget), sum_cap)
if pass_target <= 0:
break
# Allocate removals across tracts proportionally to cap, respecting per-tract caps.
desired = pass_target * (cap.astype(float) / float(sum_cap))
tract_remove = np.floor(desired).astype(np.int64)
tract_remove = np.minimum(tract_remove, cap.astype(np.int64))
remainder = int(pass_target - int(tract_remove.sum()))
if remainder > 0:
frac = desired - tract_remove.astype(float)
# distribute leftover 1s to largest fractional parts first, respecting cap
order = np.argsort(-frac)
for t in order:
if remainder <= 0:
break
if cap[t] <= tract_remove[t]:
continue
tract_remove[t] += 1
remainder -= 1
# if still remainder (due to caps), distribute to any tract with remaining cap
if remainder > 0:
avail = np.where(cap > tract_remove)[0]
for t in avail:
if remainder <= 0:
break
add = int(min(remainder, int(cap[t] - tract_remove[t])))
tract_remove[t] += add
remainder -= add
if int(tract_remove.sum()) != pass_target:
raise ValueError("Failed to allocate pass removal target across tracts.")
total_removed = 0
n_high = int((cap > 0).sum())
idxs = np.where(tract_remove > 0)[0]
for t in idxs:
nremove = int(tract_remove[t])
non_neg_t = int(non_total[t] - non_pos[t])
if non_neg_t < 0:
raise ValueError("Negative inferred non-annotated classified negative count.")
counts6 = np.array(
[
int(ann_pp[t]),
int(ann_pn[t]),
int(ann_nn[t]),
int(ann_np[t]),
int(non_pos[t]),
int(non_neg_t),
],
dtype=np.int64,
)
tract_total = int(counts6.sum())
if tract_total <= 0:
continue
nremove = min(nremove, tract_total)
removed6 = _sample_multivariate_hypergeometric(counts6, nremove)
if removed6.sum() != nremove:
raise ValueError("Removal allocation did not sum to requested nremove.")
ann_pp[t] -= removed6[0]
ann_pn[t] -= removed6[1]
ann_nn[t] -= removed6[2]
ann_np[t] -= removed6[3]
non_pos[t] -= removed6[4]
non_total[t] -= (removed6[4] + removed6[5])
total_removed += int(nremove)
_recompute_derived_fields()
C_after = np.asarray(observed["n_images_by_area"], dtype=float)
mean_after = float(C_after.mean())
emd = float(wasserstein_distance(C_after, np.full_like(C_after, median_target)))
self.trim_history.append(
{
"pass": int(p),
"mean_before": float(mean_before),
"median_target": float(median_target),
"mean_after": float(mean_after),
"n_high": int(n_high),
"total_removed": int(total_removed),
"remaining_budget_after": int(max(0, remaining_budget - total_removed)),
"emd_to_median_target": float(emd),
}
)
self.logger.info(
"trim_to_median pass=%d median_target=%d mean_before=%.3f mean_after=%.3f "
"n_high=%d removed=%d remaining_budget=%d emd=%.6f"
% (p, median_target, mean_before, mean_after, n_high, total_removed, max(0, remaining_budget - total_removed), emd)
)
if total_removed == 0:
self.logger.info("trim_to_median: stopping (no removals this iteration).")
break
remaining_budget -= int(total_removed)
p += 1
return trimmed
def construct_graph_laplacian_baseline(self, N, N_edges, node1, node2, y, alpha=0.01, iterations=1):
# https://www.math.fsu.edu/~bertram/lectures/Diffusion.pdf and ChatGPT seem to agree on this.
y = deepcopy(y)
A = np.zeros((N, N))
A[node1 - 1, node2 - 1] = 1
A[node2 - 1, node1 - 1] = 1
assert A.sum() == 2 * N_edges == 2 * len(node1) == 2 * len(node2)
assert (node1 != node2).all()
assert (A == (A.T)).all()
degrees = A.sum(axis=1)
D = np.diag(degrees)
L = D - A
for _ in range(iterations):
assert (L@y).shape == y.shape
y = y - alpha * (L @ y)
return y
def extract_baselines(self, data):
"""
extracts various simple baselines from the data.
We actually end up running this on both the train set (where it's genuinely used to create baselines)
and the test set (where it's used to create ground-truth measures to validate against).
"""
frac_positive_classifications_baseline = data['n_classified_positive_by_area'] / data['n_images_by_area']
is_na = np.isnan(frac_positive_classifications_baseline)
print("warning: fraction %2.3f entries of frac_positive_classifications_baseline are NA; imputing with mean" % (is_na.mean()))
frac_positive_classifications_baseline[is_na] = 1. * data['n_classified_positive_by_area'].sum() / data['n_images_by_area'].sum()
# not including fraction of positives among ground truth for now because
# there are too many NAs and it's not clear to me what the appropriate thing to fill that in with is.
# also include some more sophisticated ML methods that use the graph laplacian.
graph_laplacian_frac_pos_classifications_one_iter = self.construct_graph_laplacian_baseline(N=data['N'], N_edges=data['N_edges'], node1=np.array(data['node1']), node2=np.array(data['node2']),
y=frac_positive_classifications_baseline, iterations=1)
graph_laplacian_frac_pos_classifications_five_iter = self.construct_graph_laplacian_baseline(N=data['N'], N_edges=data['N_edges'], node1=np.array(data['node1']), node2=np.array(data['node2']),
y=frac_positive_classifications_baseline, iterations=5)
graph_laplacian_n_positive_ground_truth_one_iter = self.construct_graph_laplacian_baseline(N=data['N'], N_edges=data['N_edges'], node1=np.array(data['node1']), node2=np.array(data['node2']),
y=data['n_classified_positive_annotated_positive_by_area'] + data['n_classified_negative_annotated_positive_by_area'], iterations=1)
graph_laplacian_n_positive_ground_truth_five_iter = self.construct_graph_laplacian_baseline(N=data['N'], N_edges=data['N_edges'], node1=np.array(data['node1']), node2=np.array(data['node2']),
y=data['n_classified_positive_annotated_positive_by_area'] + data['n_classified_negative_annotated_positive_by_area'], iterations=5)
# supervised baselines which predict outcome from external covariates
assert (data['external_covariates'][:, 0] == 1).all()
# drop the intercept
X = data['external_covariates'][:, 1:]
OLS_pred_frac_positive_classifications = LinearRegression().fit(X, frac_positive_classifications_baseline).predict(X)
OLS_pred_n_positive_ground_truth = LinearRegression().fit(X, data['n_classified_positive_annotated_positive_by_area'] + data['n_classified_negative_annotated_positive_by_area']).predict(X)
RandomForest_pred_frac_positive_classifications = RandomForestRegressor(random_state=777).fit(X, frac_positive_classifications_baseline).predict(X)
RandomForest_pred_n_positive_ground_truth = RandomForestRegressor(random_state=777).fit(X, data['n_classified_positive_annotated_positive_by_area'] + data['n_classified_negative_annotated_positive_by_area']).predict(X)
estimates = {# heuristic baselines
'frac_positive_classifications':frac_positive_classifications_baseline,
'any_positive_classifications': 1. * (data['n_classified_positive_by_area'] > 0),
'n_positive_classifications':data['n_classified_positive_by_area'],
'any_positive_ground_truth':1. * ((data['n_classified_positive_annotated_positive_by_area'] + data['n_classified_negative_annotated_positive_by_area']) > 0),
'n_positive_ground_truth':data['n_classified_positive_annotated_positive_by_area'] + data['n_classified_negative_annotated_positive_by_area'],
# graph laplacian baselines
'graph_laplacian_frac_pos_classifications_one_iter':graph_laplacian_frac_pos_classifications_one_iter,
'graph_laplacian_frac_pos_classifications_five_iter':graph_laplacian_frac_pos_classifications_five_iter,
'graph_laplacian_n_positive_ground_truth_one_iter':graph_laplacian_n_positive_ground_truth_one_iter,
'graph_laplacian_n_positive_ground_truth_five_iter':graph_laplacian_n_positive_ground_truth_five_iter,
# supervised learning baselines
'OLS_pred_frac_positive_classifications':OLS_pred_frac_positive_classifications,
'OLS_pred_n_positive_ground_truth':OLS_pred_n_positive_ground_truth,
'RandomForest_pred_frac_positive_classifications':RandomForest_pred_frac_positive_classifications,
'RandomForest_pred_n_positive_ground_truth':RandomForest_pred_n_positive_ground_truth
}
return estimates
def compare_to_baselines(self, train_frac=0.2, save=True):
"""
fit on train set, assess on test set, compare to baselines estimated in extract_baselines.
"""
pd.set_option('display.width', 1000)
pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 50)
self.RUNID = self.RUNID + "_" + datetime.datetime.now().strftime("%Y%m%d-%H%M")
# add parent dirs that split runs based on simulated or empirical, annotations_have_locations, and icar_prior_setting
self.RUNID = f"icar_{self.icar_prior_setting}/simulated_{self.use_simulated_data}/ahl_{self.annotations_have_locations}/covariates_{self.use_external_covariates}/{self.RUNID}"
os.makedirs(f"runs/{self.RUNID}", exist_ok=True)
self.load_data()
train_data, test_data = self.divide_data_into_train_and_test_set(self.data_to_use, train_frac=train_frac)
method_and_baselines = self.extract_baselines(train_data)
ground_truth = self.extract_baselines(test_data)
self.data_to_use = {'observed_data':train_data}
fit, df = self.fit(CYCLES=1, WARMUP=12000, SAMPLES=12000, data_already_loaded=True)
self.plot_results(fit, df)
p_y_bayesian_estimate = np.array([df['p_y.%i' % i].mean() for i in range(1, train_data['N'] + 1)])
at_least_one_positive_by_area_bayesian_estimate = np.array([df['at_least_one_positive_image_by_area.%i' % i].mean() for i in range(1, train_data['N'] + 1)])
method_and_baselines['bayesian_model_p_y'] = p_y_bayesian_estimate
method_and_baselines['bayesian_model_at_least_one_positive_by_area'] = at_least_one_positive_by_area_bayesian_estimate
performance = {}
no_images_in_test = test_data['n_images_by_area'] == 0
print("warning: test set has fraction %2.3f tracts with no images; not using these in evals" % no_images_in_test.mean())
for estimate in method_and_baselines:
performance[estimate] = {}
performance[estimate]['pearson r, frac_positive_classifications'] = pearsonr(method_and_baselines[estimate][~no_images_in_test], ground_truth['frac_positive_classifications'][~no_images_in_test])[0]
performance[estimate]['AUC, any ground truth positive'] = roc_auc_score(ground_truth['any_positive_ground_truth'][~no_images_in_test], method_and_baselines[estimate][~no_images_in_test])
performance[estimate]['AUC, any classified positive'] = roc_auc_score(ground_truth['any_positive_classifications'][~no_images_in_test], method_and_baselines[estimate][~no_images_in_test])
print(pd.DataFrame(performance).transpose())
if save:
self.logger.info(f"Saving performance csv to runs/{self.RUNID}/performance_on_baselines.csv")
pd.DataFrame(performance).transpose().to_csv(
f"runs/{self.RUNID}/performance_on_baselines.csv"
)