Skip to content

Data sources

Data source loaders for attribute assignment system.

This module handles loading demographic data from CSV files with: - Regional routing (England/Wales, Scotland, Northern Ireland) - Caching for performance - Normalization of probability distributions

DataSource

Base class for data sources.

Data sources load demographic data from CSV files and provide probability distributions based on context (e.g., geographical unit code).

Source code in may/attribute_assignment/data_sources.py
 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
class DataSource:
    """
    Base class for data sources.

    Data sources load demographic data from CSV files and provide
    probability distributions based on context (e.g., geographical unit code).
    """

    def __init__(self, name: str, config: Dict[str, Any]):
        """
        Initialize data source.

        Args:
            name: Identifier for this data source
            config: Configuration dict from YAML
        """
        self.name = name
        self.config = config
        self.cache: Dict[str, Any] = {}
        self._data_loaded = False
        # Loaded geo unit names keyed by hierarchy level, set by the manager
        # before load_data. Only sources that declare a level for their values
        # read it.
        self.geo_units_by_level: Optional[Dict[str, set]] = None

    def load_data(self, geo_units: Optional[set] = None):
        """
        Load data from CSV files.

        Args:
            geo_units: Optional set of geographical unit codes to filter by (for efficiency)
        """
        raise NotImplementedError("Subclasses must implement load_data()")

    def lookup(self, *args, **kwargs) -> Dict[str, float]:
        """
        Look up probability distribution for given context.

        Returns:
            Dict mapping attribute values to probabilities
        """
        raise NotImplementedError("Subclasses must implement lookup()")

    def _normalize_probabilities(self, probs: Dict[str, float]) -> Dict[str, float]:
        """
        Normalize probabilities to ensure they sum to 1.0.

        Args:
            probs: Dictionary of probabilities

        Returns:
            Normalized probabilities that sum to 1.0
        """
        if not probs:
            raise ValueError(
                f"Empty probability distribution in source '{self.name}'. No fallbacks. "
                "Fix the data/config."
            )

        # Clamp negative values to 0, since negative probabilities are invalid
        has_negatives = False
        for v in probs.values():
            if v < 0:
                has_negatives = True
                break

        if has_negatives:
            neg_keys = [k for k, v in probs.items() if v < 0]
            logger.warning(
                f"Negative probability values in source '{self.name}' "
                f"for keys {neg_keys} — clamping to 0"
            )
            probs = {k: max(0.0, v) for k, v in probs.items()}

        total = sum(probs.values())

        if abs(total - 1.0) < 1e-10:  # Already normalized
            return probs
        elif total > 0:
            return {k: v / total for k, v in probs.items()}
        else:
            raise ValueError(
                f"All-zero probability distribution in source '{self.name}' "
                f"({len(probs)} keys). No fallbacks. Fix the data."
            )

__init__(name, config)

Initialize data source.

Parameters:

Name Type Description Default
name str

Identifier for this data source

required
config Dict[str, Any]

Configuration dict from YAML

required
Source code in may/attribute_assignment/data_sources.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def __init__(self, name: str, config: Dict[str, Any]):
    """
    Initialize data source.

    Args:
        name: Identifier for this data source
        config: Configuration dict from YAML
    """
    self.name = name
    self.config = config
    self.cache: Dict[str, Any] = {}
    self._data_loaded = False
    # Loaded geo unit names keyed by hierarchy level, set by the manager
    # before load_data. Only sources that declare a level for their values
    # read it.
    self.geo_units_by_level: Optional[Dict[str, set]] = None

load_data(geo_units=None)

Load data from CSV files.

Parameters:

Name Type Description Default
geo_units Optional[set]

Optional set of geographical unit codes to filter by (for efficiency)

None
Source code in may/attribute_assignment/data_sources.py
44
45
46
47
48
49
50
51
def load_data(self, geo_units: Optional[set] = None):
    """
    Load data from CSV files.

    Args:
        geo_units: Optional set of geographical unit codes to filter by (for efficiency)
    """
    raise NotImplementedError("Subclasses must implement load_data()")

lookup(*args, **kwargs)

Look up probability distribution for given context.

Returns:

Type Description
Dict[str, float]

Dict mapping attribute values to probabilities

Source code in may/attribute_assignment/data_sources.py
53
54
55
56
57
58
59
60
def lookup(self, *args, **kwargs) -> Dict[str, float]:
    """
    Look up probability distribution for given context.

    Returns:
        Dict mapping attribute values to probabilities
    """
    raise NotImplementedError("Subclasses must implement lookup()")

DataSourceManager

Manager for all data sources.

Coordinates loading and access to multiple data sources.

Source code in may/attribute_assignment/data_sources.py
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
class DataSourceManager:
    """
    Manager for all data sources.

    Coordinates loading and access to multiple data sources.
    """

    def __init__(self, config):
        """
        Initialize data source manager.

        Args:
            config: AttributeAssignmentConfig instance
        """
        self.config = config
        self.sources: Dict[str, DataSource] = {}
        self._initialize_sources()

    # csv_lookup `format` → source class. Chosen explicitly in config.
    _CSV_FORMATS = {
        'geo_distribution': GeoDistributionSource,
        'diversity': DiversitySource,
        'pair': PairProbabilitySource,
        'multi_key': MultiKeyLookupSource,
        'origin_destination_matrix': OriginDestinationMatrixSource,
        'gu_sampler': GUSamplerSource,
    }

    def _initialize_sources(self):
        """Initialize data sources from config (explicit type/format dispatch)."""
        for source_name, source_config in self.config.data_sources.items():
            source_type = source_config.type

            if source_type == 'constant':
                logger.debug(f"Skipping constant source: {source_name}")
                continue
            if source_type != 'csv_lookup':
                raise ValueError(
                    f"Data source '{source_name}': unknown type '{source_type}' "
                    "(expected 'csv_lookup')."
                )

            fmt = source_config.config.get('format')
            cls = self._CSV_FORMATS.get(fmt)
            if cls is None:
                raise ValueError(
                    f"Data source '{source_name}' needs an explicit 'format' "
                    f"(one of {sorted(self._CSV_FORMATS)}), got {fmt!r}."
                )

            # MultiKeyLookupSource needs the assignment config for key/category resolution.
            if cls is MultiKeyLookupSource:
                self.sources[source_name] = cls(source_name, source_config.config, self.config)
            else:
                self.sources[source_name] = cls(source_name, source_config.config)

    def load_all(self, geo_units: Optional[set] = None,
                 geo_units_by_level: Optional[Dict[str, set]] = None):
        """
        Load all data sources.

        Args:
            geo_units: Optional set of geographical unit codes to preload
            geo_units_by_level: The same names keyed by hierarchy level, for
                sources that declare which level their values live at.
        """
        logger.info("Loading all data sources...")
        for source_name, source in self.sources.items():
            source.geo_units_by_level = geo_units_by_level
            source.load_data(geo_units)
        logger.info("✓ All data sources loaded")

    def get_source(self, source_name: str) -> Optional[DataSource]:
        """Get a data source by name."""
        return self.sources.get(source_name)

    def lookup(self, source_name: str, *args, **kwargs) -> Dict[str, float]:
        """
        Look up probabilities from a data source.

        Args:
            source_name: Name of data source
            *args, **kwargs: Arguments to pass to source's lookup method

        Returns:
            Probability distribution
        """
        source = self.get_source(source_name)
        if not source:
            raise KeyError(
                f"Data source '{source_name}' is not registered. No fallbacks. "
                "Fix the source name in the config."
            )
        return source.lookup(*args, **kwargs)

__init__(config)

Initialize data source manager.

Parameters:

Name Type Description Default
config

AttributeAssignmentConfig instance

required
Source code in may/attribute_assignment/data_sources.py
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
def __init__(self, config):
    """
    Initialize data source manager.

    Args:
        config: AttributeAssignmentConfig instance
    """
    self.config = config
    self.sources: Dict[str, DataSource] = {}
    self._initialize_sources()

get_source(source_name)

Get a data source by name.

Source code in may/attribute_assignment/data_sources.py
1255
1256
1257
def get_source(self, source_name: str) -> Optional[DataSource]:
    """Get a data source by name."""
    return self.sources.get(source_name)

load_all(geo_units=None, geo_units_by_level=None)

Load all data sources.

Parameters:

Name Type Description Default
geo_units Optional[set]

Optional set of geographical unit codes to preload

None
geo_units_by_level Optional[Dict[str, set]]

The same names keyed by hierarchy level, for sources that declare which level their values live at.

None
Source code in may/attribute_assignment/data_sources.py
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
def load_all(self, geo_units: Optional[set] = None,
             geo_units_by_level: Optional[Dict[str, set]] = None):
    """
    Load all data sources.

    Args:
        geo_units: Optional set of geographical unit codes to preload
        geo_units_by_level: The same names keyed by hierarchy level, for
            sources that declare which level their values live at.
    """
    logger.info("Loading all data sources...")
    for source_name, source in self.sources.items():
        source.geo_units_by_level = geo_units_by_level
        source.load_data(geo_units)
    logger.info("✓ All data sources loaded")

lookup(source_name, *args, **kwargs)

Look up probabilities from a data source.

Parameters:

Name Type Description Default
source_name str

Name of data source

required
*args, **kwargs

Arguments to pass to source's lookup method

required

Returns:

Type Description
Dict[str, float]

Probability distribution

Source code in may/attribute_assignment/data_sources.py
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
def lookup(self, source_name: str, *args, **kwargs) -> Dict[str, float]:
    """
    Look up probabilities from a data source.

    Args:
        source_name: Name of data source
        *args, **kwargs: Arguments to pass to source's lookup method

    Returns:
        Probability distribution
    """
    source = self.get_source(source_name)
    if not source:
        raise KeyError(
            f"Data source '{source_name}' is not registered. No fallbacks. "
            "Fix the source name in the config."
        )
    return source.lookup(*args, **kwargs)

DiversitySource

Bases: DataSource

Data source for venue diversity (single vs mixed attribute values).

Provides probabilities for whether a venue has: - Single attribute value (all members same) - Two attribute values - Three or more attribute values

Source code in may/attribute_assignment/data_sources.py
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
class DiversitySource(DataSource):
    """
    Data source for venue diversity (single vs mixed attribute values).

    Provides probabilities for whether a venue has:
    - Single attribute value (all members same)
    - Two attribute values
    - Three or more attribute values
    """

    def __init__(self, name: str, config: Dict[str, Any]):
        """Initialize diversity source."""
        super().__init__(name, config)
        self._lookup: Dict[str, Dict[str, float]] = {}
        self._file_configs = config.get('files', [])

    def load_data(self, geo_units: Optional[set] = None):
        """Load diversity data from CSV file."""
        logger.info(f"Loading data for source '{self.name}'...")

        merged: Dict[str, Dict[str, float]] = {}
        for file_config in self._file_configs:
            file_path = Path(pr.resolve(file_config['path']))

            if file_path.exists():
                try:
                    df = pd.read_csv(file_path)
                    key_column = _ordered_key_columns(file_config, self.name, expected=1)[0]

                    if geo_units and key_column in df.columns:
                        df = df[df[key_column].isin(geo_units)]

                    value_columns = file_config.get('value_columns', {})
                    lookup = self._parse_diversity_dataframe(df, key_column, value_columns)

                    logger.info(f"  ✓ Loaded {len(lookup)} geographical units from {file_path.name}")

                except Exception as e:
                    # Fail loud on a load/parse error.
                    raise RuntimeError(
                        f"failed to load data source file {file_path}: {e}"
                    ) from e
                _merge_disjoint(merged, lookup, self.name, file_path)
            else:
                raise FileNotFoundError(f"data source file not found: {file_path}")
        self._lookup = merged

        self._data_loaded = True

    def _parse_diversity_dataframe(self, df: pd.DataFrame, key_column: str,
                                   value_columns: Dict[str, str]) -> Dict[str, Dict[str, float]]:
        """Parse diversity DataFrame."""
        lookup = {}

        for _, row in df.iterrows():
            geo_unit = row[key_column]

            # Get diversity counts
            counts = {}
            for output_key, df_column in value_columns.items():
                if df_column in df.columns:
                    counts[output_key] = float(row[df_column])

            # Normalize to probabilities
            total = sum(counts.values())
            if total <= 0:
                raise ValueError(
                    f"Source '{self.name}': zero-total diversity counts for geo unit "
                    f"'{geo_unit}'. No fallbacks. Fix the data."
                )
            probs = {k: v / total for k, v in counts.items()}

            lookup[geo_unit] = self._normalize_probabilities(probs)

        return lookup

    def lookup(self, geo_unit: str) -> Dict[str, float]:
        """Look up diversity probabilities for a geographical unit."""
        if not self._data_loaded:
            raise RuntimeError(
                f"Data not loaded for source '{self.name}'. No fallbacks."
            )

        if geo_unit in self._lookup:
            return self._lookup[geo_unit]

        raise KeyError(
            f"Source '{self.name}' has no diversity row for geo unit '{geo_unit}'. "
            "No fallbacks."
        )

__init__(name, config)

Initialize diversity source.

Source code in may/attribute_assignment/data_sources.py
315
316
317
318
319
def __init__(self, name: str, config: Dict[str, Any]):
    """Initialize diversity source."""
    super().__init__(name, config)
    self._lookup: Dict[str, Dict[str, float]] = {}
    self._file_configs = config.get('files', [])

load_data(geo_units=None)

Load diversity data from CSV file.

Source code in may/attribute_assignment/data_sources.py
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
def load_data(self, geo_units: Optional[set] = None):
    """Load diversity data from CSV file."""
    logger.info(f"Loading data for source '{self.name}'...")

    merged: Dict[str, Dict[str, float]] = {}
    for file_config in self._file_configs:
        file_path = Path(pr.resolve(file_config['path']))

        if file_path.exists():
            try:
                df = pd.read_csv(file_path)
                key_column = _ordered_key_columns(file_config, self.name, expected=1)[0]

                if geo_units and key_column in df.columns:
                    df = df[df[key_column].isin(geo_units)]

                value_columns = file_config.get('value_columns', {})
                lookup = self._parse_diversity_dataframe(df, key_column, value_columns)

                logger.info(f"  ✓ Loaded {len(lookup)} geographical units from {file_path.name}")

            except Exception as e:
                # Fail loud on a load/parse error.
                raise RuntimeError(
                    f"failed to load data source file {file_path}: {e}"
                ) from e
            _merge_disjoint(merged, lookup, self.name, file_path)
        else:
            raise FileNotFoundError(f"data source file not found: {file_path}")
    self._lookup = merged

    self._data_loaded = True

lookup(geo_unit)

Look up diversity probabilities for a geographical unit.

Source code in may/attribute_assignment/data_sources.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def lookup(self, geo_unit: str) -> Dict[str, float]:
    """Look up diversity probabilities for a geographical unit."""
    if not self._data_loaded:
        raise RuntimeError(
            f"Data not loaded for source '{self.name}'. No fallbacks."
        )

    if geo_unit in self._lookup:
        return self._lookup[geo_unit]

    raise KeyError(
        f"Source '{self.name}' has no diversity row for geo unit '{geo_unit}'. "
        "No fallbacks."
    )

GUSamplerSource

Bases: DataSource

Data source for sampling geographical units within a parent GU weighted by distribution. Generic source that works with any geographical hierarchy level.

Returns GU codes as categorical values with distribution-based weights.

Source code in may/attribute_assignment/data_sources.py
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
class GUSamplerSource(DataSource):
    """
    Data source for sampling geographical units within a parent GU weighted by distribution.
    Generic source that works with any geographical hierarchy level.

    Returns GU codes as categorical values with distribution-based weights.
    """

    def __init__(self, name: str, config: Dict[str, Any]):
        """Initialize geographical unit sampler source."""
        super().__init__(name, config)
        # Lookup: parent_gu_name -> {child_gu_code: weight}
        self._lookup: Dict[str, Dict[str, float]] = {}
        self._file_configs = config.get('files', [])
        # Person attribute that supplies the parent GU to sample within, read
        # from config (key_columns value), so the sampler is generic over any
        # parent attribute / hierarchy level.
        self._parent_attribute: Optional[str] = None

    def load_data(self, geo_units: Optional[set] = None):
        """Load GU distribution by parent GU."""
        logger.info(f"Loading data for source '{self.name}'...")

        for file_config in self._file_configs:
            file_path = Path(pr.resolve(file_config['path']))

            if file_path.exists():
                try:
                    df = pd.read_csv(file_path)

                    # Parent-GU lookup key: canonical one-entry key_columns mapping.
                    # Its value names the person attribute that supplies the parent GU,
                    # which keeps this generic over any parent attribute.
                    parent_column = _ordered_key_columns(file_config, self.name, expected=1)[0]
                    key_resolution = file_config['key_columns'][parent_column]
                    if not isinstance(key_resolution, dict) or not key_resolution.get('attribute'):
                        raise ValueError(
                            f"GU sampler source '{self.name}': key column '{parent_column}' "
                            "must map to a resolution with an 'attribute' naming the person "
                            "attribute that holds the parent GU, e.g. "
                            f"{{{parent_column}: {{attribute: workplace_location}}}}."
                        )
                    self._parent_attribute = key_resolution['attribute']
                    weight_column = file_config.get('weight_column', 'Total')

                    # The sampled child-GU output column (distinct from the lookup
                    # key above), format: {name: ..., level: ...}. `level` is the
                    # user-facing label, used only for logging.
                    geo_unit_config = file_config.get('geographical_unit_column')
                    if geo_unit_config:
                        geo_unit_column = geo_unit_config.get('name')
                        geo_unit_level = geo_unit_config.get('level')

                    # Filter to only relevant geographical units
                    if geo_units and geo_unit_column and geo_unit_column in df.columns:
                        original_len = len(df)
                        df = df[df[geo_unit_column].isin(geo_units)]
                        logger.info(f"  Filtered CSV from {original_len} to {len(df)} rows based on {len(geo_units)} geographical units")

                    # Handle exclude_rows (list format)
                    exclude_rows_config = file_config.get('exclude_rows', [])
                    if isinstance(exclude_rows_config, list):
                        # format: [{column: "col", values: [vals]}]
                        for exclude_rule in exclude_rows_config:
                            col = exclude_rule.get('column')
                            exclude_values = exclude_rule.get('values', [])
                            if col and col in df.columns:
                                df = df[~df[col].isin(exclude_values)]

                    # Group by parent GU and build child GU distribution
                    file_lookup = {}
                    for parent_name, group in df.groupby(parent_column):
                        geo_dist = {}
                        for _, row in group.iterrows():
                            geo_code = row[geo_unit_column]
                            weight = float(row[weight_column])
                            if weight > 0:  # Only include GUs with workers
                                geo_dist[geo_code] = weight

                        # Normalize to probabilities
                        if geo_dist:
                            file_lookup[parent_name] = self._normalize_probabilities(geo_dist)

                    logger.info(f"  ✓ Loaded {geo_unit_level} distributions for {len(file_lookup)} parent GUs from {file_path.name}")

                except Exception as e:
                    # Fail loud on a load/parse error.
                    raise RuntimeError(
                        f"failed to load data source file {file_path}: {e}"
                    ) from e
                _merge_disjoint(self._lookup, file_lookup, self.name, file_path)
            else:
                raise FileNotFoundError(f"data source file not found: {file_path}")

        self._data_loaded = True

    def lookup(self, person, household=None, context=None) -> Dict[str, float]:
        """
        Look up the child-GU distribution for the person's parent GU.

        Resolves the key itself: the parent GU is the person's already
        assigned `workplace_location`.
        """
        if not self._data_loaded:
            raise RuntimeError(
                f"Data not loaded for source '{self.name}'. No fallbacks."
            )
        parent_gu_name = get_person_attribute(person, self._parent_attribute)
        if not parent_gu_name:
            raise KeyError(
                f"Source '{self.name}': person {person.id} has no '{self._parent_attribute}' "
                "to sample a child GU within. No fallbacks."
            )
        if parent_gu_name not in self._lookup:
            raise KeyError(
                f"Source '{self.name}' has no child-GU distribution for parent "
                f"'{parent_gu_name}'. No fallbacks."
            )
        return self._lookup[parent_gu_name]

__init__(name, config)

Initialize geographical unit sampler source.

Source code in may/attribute_assignment/data_sources.py
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
def __init__(self, name: str, config: Dict[str, Any]):
    """Initialize geographical unit sampler source."""
    super().__init__(name, config)
    # Lookup: parent_gu_name -> {child_gu_code: weight}
    self._lookup: Dict[str, Dict[str, float]] = {}
    self._file_configs = config.get('files', [])
    # Person attribute that supplies the parent GU to sample within, read
    # from config (key_columns value), so the sampler is generic over any
    # parent attribute / hierarchy level.
    self._parent_attribute: Optional[str] = None

load_data(geo_units=None)

Load GU distribution by parent GU.

Source code in may/attribute_assignment/data_sources.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
def load_data(self, geo_units: Optional[set] = None):
    """Load GU distribution by parent GU."""
    logger.info(f"Loading data for source '{self.name}'...")

    for file_config in self._file_configs:
        file_path = Path(pr.resolve(file_config['path']))

        if file_path.exists():
            try:
                df = pd.read_csv(file_path)

                # Parent-GU lookup key: canonical one-entry key_columns mapping.
                # Its value names the person attribute that supplies the parent GU,
                # which keeps this generic over any parent attribute.
                parent_column = _ordered_key_columns(file_config, self.name, expected=1)[0]
                key_resolution = file_config['key_columns'][parent_column]
                if not isinstance(key_resolution, dict) or not key_resolution.get('attribute'):
                    raise ValueError(
                        f"GU sampler source '{self.name}': key column '{parent_column}' "
                        "must map to a resolution with an 'attribute' naming the person "
                        "attribute that holds the parent GU, e.g. "
                        f"{{{parent_column}: {{attribute: workplace_location}}}}."
                    )
                self._parent_attribute = key_resolution['attribute']
                weight_column = file_config.get('weight_column', 'Total')

                # The sampled child-GU output column (distinct from the lookup
                # key above), format: {name: ..., level: ...}. `level` is the
                # user-facing label, used only for logging.
                geo_unit_config = file_config.get('geographical_unit_column')
                if geo_unit_config:
                    geo_unit_column = geo_unit_config.get('name')
                    geo_unit_level = geo_unit_config.get('level')

                # Filter to only relevant geographical units
                if geo_units and geo_unit_column and geo_unit_column in df.columns:
                    original_len = len(df)
                    df = df[df[geo_unit_column].isin(geo_units)]
                    logger.info(f"  Filtered CSV from {original_len} to {len(df)} rows based on {len(geo_units)} geographical units")

                # Handle exclude_rows (list format)
                exclude_rows_config = file_config.get('exclude_rows', [])
                if isinstance(exclude_rows_config, list):
                    # format: [{column: "col", values: [vals]}]
                    for exclude_rule in exclude_rows_config:
                        col = exclude_rule.get('column')
                        exclude_values = exclude_rule.get('values', [])
                        if col and col in df.columns:
                            df = df[~df[col].isin(exclude_values)]

                # Group by parent GU and build child GU distribution
                file_lookup = {}
                for parent_name, group in df.groupby(parent_column):
                    geo_dist = {}
                    for _, row in group.iterrows():
                        geo_code = row[geo_unit_column]
                        weight = float(row[weight_column])
                        if weight > 0:  # Only include GUs with workers
                            geo_dist[geo_code] = weight

                    # Normalize to probabilities
                    if geo_dist:
                        file_lookup[parent_name] = self._normalize_probabilities(geo_dist)

                logger.info(f"  ✓ Loaded {geo_unit_level} distributions for {len(file_lookup)} parent GUs from {file_path.name}")

            except Exception as e:
                # Fail loud on a load/parse error.
                raise RuntimeError(
                    f"failed to load data source file {file_path}: {e}"
                ) from e
            _merge_disjoint(self._lookup, file_lookup, self.name, file_path)
        else:
            raise FileNotFoundError(f"data source file not found: {file_path}")

    self._data_loaded = True

lookup(person, household=None, context=None)

Look up the child-GU distribution for the person's parent GU.

Resolves the key itself: the parent GU is the person's already assigned workplace_location.

Source code in may/attribute_assignment/data_sources.py
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
def lookup(self, person, household=None, context=None) -> Dict[str, float]:
    """
    Look up the child-GU distribution for the person's parent GU.

    Resolves the key itself: the parent GU is the person's already
    assigned `workplace_location`.
    """
    if not self._data_loaded:
        raise RuntimeError(
            f"Data not loaded for source '{self.name}'. No fallbacks."
        )
    parent_gu_name = get_person_attribute(person, self._parent_attribute)
    if not parent_gu_name:
        raise KeyError(
            f"Source '{self.name}': person {person.id} has no '{self._parent_attribute}' "
            "to sample a child GU within. No fallbacks."
        )
    if parent_gu_name not in self._lookup:
        raise KeyError(
            f"Source '{self.name}' has no child-GU distribution for parent "
            f"'{parent_gu_name}'. No fallbacks."
        )
    return self._lookup[parent_gu_name]

GeoDistributionSource

Bases: DataSource

Data source for geographical unit-specific attribute distributions.

Loads attribute distributions from CSV file.

Source code in may/attribute_assignment/data_sources.py
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
class GeoDistributionSource(DataSource):
    """
    Data source for geographical unit-specific attribute distributions.

    Loads attribute distributions from CSV file.
    """

    def __init__(self, name: str, config: Dict[str, Any]):
        """
        Initialize geo distribution source.

        Args:
            name: Source name
            config: Configuration with files and fallback
        """
        super().__init__(name, config)

        # Data lookup: geo_unit -> {ethnicity -> probability}
        self._lookup: Dict[str, Dict[str, float]] = {}

        # Parse file configurations
        self._file_configs = config.get('files', [])

    def load_data(self, geo_units: Optional[set] = None):
        """
        Load geographical unit distribution data from CSV file.

        Args:
            geo_units: Set of geographical unit codes to load (for efficiency)
        """
        logger.info(f"Loading data for source '{self.name}'...")

        # Each file contributes its own geo units; the merged lookup must be
        # key-disjoint across files.
        merged: Dict[str, Dict[str, float]] = {}
        for file_config in self._file_configs:
            file_path = Path(pr.resolve(file_config['path']))

            # Load and process CSV
            if file_path.exists():
                try:
                    df = pd.read_csv(file_path)

                    # Filter to needed areas
                    key_column = _ordered_key_columns(file_config, self.name, expected=1)[0]
                    if geo_units and key_column in df.columns:
                        df = df[df[key_column].isin(geo_units)]

                    # Parse value columns
                    value_columns = file_config.get('value_columns', {})
                    total_column = file_config.get('total_column')

                    lookup = self._parse_dataframe(
                        df, key_column, value_columns, total_column
                    )

                    logger.info(f"  ✓ Loaded {len(lookup)} geographical units from {file_path.name}")

                except Exception as e:
                    # Fail loud on a load/parse error.
                    raise RuntimeError(
                        f"failed to load data source file {file_path}: {e}"
                    ) from e
                _merge_disjoint(merged, lookup, self.name, file_path)
            else:
                raise FileNotFoundError(f"data source file not found: {file_path}")
        self._lookup = merged

        self._data_loaded = True

    def _parse_dataframe(self, df: pd.DataFrame, key_column: str,
                        value_columns: Dict[str, str],
                        total_column: Optional[str] = None) -> Dict[str, Dict[str, float]]:
        """
        Parse DataFrame into lookup dictionary.

        Args:
            df: DataFrame to parse
            key_column: Column with geographical unit codes
            value_columns: Mapping of output keys to DataFrame columns
            total_column: Optional column with totals (for normalization)

        Returns:
            Dictionary mapping geographical unit codes to probability distributions
        """
        lookup = {}

        for _, row in df.iterrows():
            geo_unit = row[key_column]

            # Get total if available
            if total_column and total_column in df.columns:
                total = row[total_column]
            else:
                total = None

            # Build probability distribution
            probs = {}
            for output_key, df_column in value_columns.items():
                if df_column in df.columns:
                    value = row[df_column]

                    # Normalize by total if provided
                    if total is not None and total > 0:
                        probs[output_key] = value / total
                    else:
                        probs[output_key] = value

            # Normalize probabilities
            probs = self._normalize_probabilities(probs)
            lookup[geo_unit] = probs

        return lookup

    def lookup(self, person, household=None, context=None) -> Dict[str, float]:
        """
        Look up the distribution for a person's residence geographical unit.

        Resolves the key itself: the residence venue's geo unit first,
        then the person's own.
        """
        if not self._data_loaded:
            raise RuntimeError(
                f"Data not loaded for source '{self.name}'. No fallbacks. "
                "Fix the source/data so it loads."
            )

        geo_unit = None
        if household is not None and getattr(household, 'geographical_unit', None):
            geo_unit = household.geographical_unit.name
        if not geo_unit and getattr(person, 'geographical_unit', None):
            geo_unit = person.geographical_unit.name
        if not geo_unit:
            raise KeyError(
                f"Source '{self.name}': no residence geographical_unit for person "
                f"{person.id} (no venue geo and no person-level geo). No fallbacks."
            )

        if geo_unit in self._lookup:
            return self._lookup[geo_unit]

        raise KeyError(
            f"Source '{self.name}' has no row for geo unit '{geo_unit}'. No fallbacks. "
            "The data must cover every keyed unit, or it's a real gap."
        )

__init__(name, config)

Initialize geo distribution source.

Parameters:

Name Type Description Default
name str

Source name

required
config Dict[str, Any]

Configuration with files and fallback

required
Source code in may/attribute_assignment/data_sources.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def __init__(self, name: str, config: Dict[str, Any]):
    """
    Initialize geo distribution source.

    Args:
        name: Source name
        config: Configuration with files and fallback
    """
    super().__init__(name, config)

    # Data lookup: geo_unit -> {ethnicity -> probability}
    self._lookup: Dict[str, Dict[str, float]] = {}

    # Parse file configurations
    self._file_configs = config.get('files', [])

load_data(geo_units=None)

Load geographical unit distribution data from CSV file.

Parameters:

Name Type Description Default
geo_units Optional[set]

Set of geographical unit codes to load (for efficiency)

None
Source code in may/attribute_assignment/data_sources.py
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
def load_data(self, geo_units: Optional[set] = None):
    """
    Load geographical unit distribution data from CSV file.

    Args:
        geo_units: Set of geographical unit codes to load (for efficiency)
    """
    logger.info(f"Loading data for source '{self.name}'...")

    # Each file contributes its own geo units; the merged lookup must be
    # key-disjoint across files.
    merged: Dict[str, Dict[str, float]] = {}
    for file_config in self._file_configs:
        file_path = Path(pr.resolve(file_config['path']))

        # Load and process CSV
        if file_path.exists():
            try:
                df = pd.read_csv(file_path)

                # Filter to needed areas
                key_column = _ordered_key_columns(file_config, self.name, expected=1)[0]
                if geo_units and key_column in df.columns:
                    df = df[df[key_column].isin(geo_units)]

                # Parse value columns
                value_columns = file_config.get('value_columns', {})
                total_column = file_config.get('total_column')

                lookup = self._parse_dataframe(
                    df, key_column, value_columns, total_column
                )

                logger.info(f"  ✓ Loaded {len(lookup)} geographical units from {file_path.name}")

            except Exception as e:
                # Fail loud on a load/parse error.
                raise RuntimeError(
                    f"failed to load data source file {file_path}: {e}"
                ) from e
            _merge_disjoint(merged, lookup, self.name, file_path)
        else:
            raise FileNotFoundError(f"data source file not found: {file_path}")
    self._lookup = merged

    self._data_loaded = True

lookup(person, household=None, context=None)

Look up the distribution for a person's residence geographical unit.

Resolves the key itself: the residence venue's geo unit first, then the person's own.

Source code in may/attribute_assignment/data_sources.py
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
def lookup(self, person, household=None, context=None) -> Dict[str, float]:
    """
    Look up the distribution for a person's residence geographical unit.

    Resolves the key itself: the residence venue's geo unit first,
    then the person's own.
    """
    if not self._data_loaded:
        raise RuntimeError(
            f"Data not loaded for source '{self.name}'. No fallbacks. "
            "Fix the source/data so it loads."
        )

    geo_unit = None
    if household is not None and getattr(household, 'geographical_unit', None):
        geo_unit = household.geographical_unit.name
    if not geo_unit and getattr(person, 'geographical_unit', None):
        geo_unit = person.geographical_unit.name
    if not geo_unit:
        raise KeyError(
            f"Source '{self.name}': no residence geographical_unit for person "
            f"{person.id} (no venue geo and no person-level geo). No fallbacks."
        )

    if geo_unit in self._lookup:
        return self._lookup[geo_unit]

    raise KeyError(
        f"Source '{self.name}' has no row for geo unit '{geo_unit}'. No fallbacks. "
        "The data must cover every keyed unit, or it's a real gap."
    )

MultiKeyLookupSource

Bases: DataSource

Data source for multi-key CSV lookups.

Supports lookups based on multiple keys (e.g., sex + age + ethnicity + region). Uses a pure Python dictionary for maximum performance.

Source code in may/attribute_assignment/data_sources.py
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
class MultiKeyLookupSource(DataSource):
    """
    Data source for multi-key CSV lookups.

    Supports lookups based on multiple keys (e.g., sex + age + ethnicity + region).
    Uses a pure Python dictionary for maximum performance.
    """

    def __init__(self, name: str, config: Dict[str, Any], assignment_config):
        """
        Initialize multi-key lookup source.

        Args:
            name: Source name
            config: Configuration with files and fallback
            assignment_config: Parent AttributeAssignmentConfig for category lookups
        """
        super().__init__(name, config)
        self.assignment_config = assignment_config
        self._file_configs = config.get('files', [])
        self._lookup_dict = {}  # Dict mapping tuple keys to value dicts
        self._key_columns = []
        self._value_columns = {}
        self._key_columns_config = None  # Cache key columns config for fast lookup

        self._lookup_cache = {}  # Cache for lookup() results by tuple key

    def load_data(self, geo_units: Optional[set] = None):
        """Load CSV data and convert to dictionary for fast lookups."""
        logger.info(f"Loading data for source '{self.name}'...")

        merged: Dict = {}
        for file_config in self._file_configs:
            file_path = Path(pr.resolve(file_config['path']))

            if file_path.exists():
                try:
                    df = pd.read_csv(file_path)

                    # Apply row filters if specified
                    row_filter = file_config.get('row_filter', {})
                    if row_filter:
                        for col, value in row_filter.items():
                            if col in df.columns:
                                df = df[df[col] == value]
                                logger.info(f"  Applied filter: {col} == '{value}' ({len(df)} rows remaining)")

                    # Key/value column config must agree across a source's
                    # files, so the lookup has one shape.
                    key_columns = list(file_config.get('key_columns', {}).keys())
                    if self._key_columns and key_columns != self._key_columns:
                        raise ValueError(
                            f"key_columns differ between files: {self._key_columns} "
                            f"vs {key_columns}."
                        )
                    self._key_columns = key_columns
                    self._key_columns_config = file_config.get('key_columns', {})
                    self._value_columns = file_config.get('value_columns', {})

                    # Build dictionary: {(key1, key2, ...): {col1: val1, col2: val2, ...}}
                    logger.info(f"  Building lookup dictionary from {len(df)} rows...")

                    # Read the frame column-wise. Row-wise iteration costs a
                    # Series object and a boxed scalar lookup per cell, which
                    # dominates load time on the larger sources.
                    key_cols = [df[col].tolist() for col in self._key_columns]
                    value_names = list(self._value_columns.keys())
                    value_cols = [
                        df[csv_col].astype(float).tolist()
                        for csv_col in self._value_columns.values()
                    ]

                    file_lookup = {
                        key: dict(zip(value_names, values))
                        for key, values in zip(zip(*key_cols), zip(*value_cols))
                    }

                    logger.info(f"  ✓ Loaded {len(file_lookup)} rows from {file_path.name} into dictionary")
                except Exception as e:
                    # Fail loud on a load/parse error.
                    raise RuntimeError(
                        f"failed to load data source file {file_path}: {e}"
                    ) from e
                _merge_disjoint(merged, file_lookup, self.name, file_path)
            else:
                raise FileNotFoundError(f"data source file not found: {file_path}")
        self._lookup_dict = merged

        self._data_loaded = True

    def lookup(self, person, household=None, context=None) -> Dict[str, float]:
        """
        Look up probabilities based on person demographics using dictionary lookup.

        Uses caching for repeated lookups with same keys.

        Args:
            person: Person object
            household: Optional household object
            context: Optional additional context

        Returns:
            Dict of value columns (e.g., {'cvd': 0.05, 'crd': 0.03, ...})
        """
        debug = context and context.get('debug', False)

        if not self._lookup_dict:
            raise RuntimeError(
                f"Source '{self.name}' has no data loaded. No fallbacks."
            )

        # Build key tuple directly (faster than building intermediate dict)
        key_values = []
        for csv_col_name, col_config in self._key_columns_config.items():
            value = self._resolve_key_value(col_config, person, household, context)
            if value is None:
                raise KeyError(
                    f"Source '{self.name}': could not resolve key column "
                    f"'{csv_col_name}' for person {person.id}. No fallbacks. "
                    "The person is missing an attribute the key needs, or the key config "
                    "is wrong."
                )
            key_values.append(value)

        # Direct dictionary lookup with tuple key
        lookup_key = tuple(key_values)

        # Check cache first
        if lookup_key in self._lookup_cache:
            return self._lookup_cache[lookup_key]

        if debug:
            logger.debug(f"    [LOOKUP] Key: {lookup_key}")

        # dictionary lookup
        result = self._lookup_dict.get(lookup_key)

        if result is None:
            raise KeyError(
                f"Source '{self.name}' has no row for key {lookup_key}. No fallbacks. "
                "The data must cover every demographic combination the "
                "model produces, or this is a real gap."
            )

        if debug:
            logger.debug(f"    [LOOKUP] ✓ Found data: {list(result.keys())[:3]}...")

        # Normalize the result (convert counts to probabilities)
        result = self._normalize_probabilities(result)

        # Cache the normalized result
        self._lookup_cache[lookup_key] = result

        return result

    def _resolve_key_value(self, col_config, person, household, context):
        """
        Resolve a key value based on column configuration.

        Args:
            col_config: Column configuration dict
            person: Person object
            household: Optional household object
            context: Optional context dict

        Returns:
            Resolved value or None if can't resolve
        """
        attr_name = col_config.get('attribute')
        col_type = col_config.get('type', 'direct')

        if col_type == 'direct':
            return get_person_attribute(person, attr_name)

        elif col_type == 'category_lookup':
            # Get attribute value, find matching category
            value = get_person_attribute(person, attr_name)
            category = self.assignment_config.get_category_for_value(value, attr_name)
            return category.get('csv_value') if category else None

        elif col_type == 'ancestor_lookup':
            # Traverse hierarchy
            geo_unit = get_person_attribute(person, attr_name)
            if geo_unit is None and household:
                # Use the household's geo unit when the person has none
                geo_unit = get_nested_value(household, attr_name)

            if geo_unit is None:
                return None

            level = col_config.get('level')
            ancestor = geo_unit.get_ancestor_by_level(level)

            if ancestor is None:
                return None

            property_name = col_config.get('property', 'name')
            return getattr(ancestor, property_name)

        return None

__init__(name, config, assignment_config)

Initialize multi-key lookup source.

Parameters:

Name Type Description Default
name str

Source name

required
config Dict[str, Any]

Configuration with files and fallback

required
assignment_config

Parent AttributeAssignmentConfig for category lookups

required
Source code in may/attribute_assignment/data_sources.py
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def __init__(self, name: str, config: Dict[str, Any], assignment_config):
    """
    Initialize multi-key lookup source.

    Args:
        name: Source name
        config: Configuration with files and fallback
        assignment_config: Parent AttributeAssignmentConfig for category lookups
    """
    super().__init__(name, config)
    self.assignment_config = assignment_config
    self._file_configs = config.get('files', [])
    self._lookup_dict = {}  # Dict mapping tuple keys to value dicts
    self._key_columns = []
    self._value_columns = {}
    self._key_columns_config = None  # Cache key columns config for fast lookup

    self._lookup_cache = {}  # Cache for lookup() results by tuple key

load_data(geo_units=None)

Load CSV data and convert to dictionary for fast lookups.

Source code in may/attribute_assignment/data_sources.py
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
def load_data(self, geo_units: Optional[set] = None):
    """Load CSV data and convert to dictionary for fast lookups."""
    logger.info(f"Loading data for source '{self.name}'...")

    merged: Dict = {}
    for file_config in self._file_configs:
        file_path = Path(pr.resolve(file_config['path']))

        if file_path.exists():
            try:
                df = pd.read_csv(file_path)

                # Apply row filters if specified
                row_filter = file_config.get('row_filter', {})
                if row_filter:
                    for col, value in row_filter.items():
                        if col in df.columns:
                            df = df[df[col] == value]
                            logger.info(f"  Applied filter: {col} == '{value}' ({len(df)} rows remaining)")

                # Key/value column config must agree across a source's
                # files, so the lookup has one shape.
                key_columns = list(file_config.get('key_columns', {}).keys())
                if self._key_columns and key_columns != self._key_columns:
                    raise ValueError(
                        f"key_columns differ between files: {self._key_columns} "
                        f"vs {key_columns}."
                    )
                self._key_columns = key_columns
                self._key_columns_config = file_config.get('key_columns', {})
                self._value_columns = file_config.get('value_columns', {})

                # Build dictionary: {(key1, key2, ...): {col1: val1, col2: val2, ...}}
                logger.info(f"  Building lookup dictionary from {len(df)} rows...")

                # Read the frame column-wise. Row-wise iteration costs a
                # Series object and a boxed scalar lookup per cell, which
                # dominates load time on the larger sources.
                key_cols = [df[col].tolist() for col in self._key_columns]
                value_names = list(self._value_columns.keys())
                value_cols = [
                    df[csv_col].astype(float).tolist()
                    for csv_col in self._value_columns.values()
                ]

                file_lookup = {
                    key: dict(zip(value_names, values))
                    for key, values in zip(zip(*key_cols), zip(*value_cols))
                }

                logger.info(f"  ✓ Loaded {len(file_lookup)} rows from {file_path.name} into dictionary")
            except Exception as e:
                # Fail loud on a load/parse error.
                raise RuntimeError(
                    f"failed to load data source file {file_path}: {e}"
                ) from e
            _merge_disjoint(merged, file_lookup, self.name, file_path)
        else:
            raise FileNotFoundError(f"data source file not found: {file_path}")
    self._lookup_dict = merged

    self._data_loaded = True

lookup(person, household=None, context=None)

Look up probabilities based on person demographics using dictionary lookup.

Uses caching for repeated lookups with same keys.

Parameters:

Name Type Description Default
person

Person object

required
household

Optional household object

None
context

Optional additional context

None

Returns:

Type Description
Dict[str, float]

Dict of value columns (e.g., {'cvd': 0.05, 'crd': 0.03, ...})

Source code in may/attribute_assignment/data_sources.py
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
def lookup(self, person, household=None, context=None) -> Dict[str, float]:
    """
    Look up probabilities based on person demographics using dictionary lookup.

    Uses caching for repeated lookups with same keys.

    Args:
        person: Person object
        household: Optional household object
        context: Optional additional context

    Returns:
        Dict of value columns (e.g., {'cvd': 0.05, 'crd': 0.03, ...})
    """
    debug = context and context.get('debug', False)

    if not self._lookup_dict:
        raise RuntimeError(
            f"Source '{self.name}' has no data loaded. No fallbacks."
        )

    # Build key tuple directly (faster than building intermediate dict)
    key_values = []
    for csv_col_name, col_config in self._key_columns_config.items():
        value = self._resolve_key_value(col_config, person, household, context)
        if value is None:
            raise KeyError(
                f"Source '{self.name}': could not resolve key column "
                f"'{csv_col_name}' for person {person.id}. No fallbacks. "
                "The person is missing an attribute the key needs, or the key config "
                "is wrong."
            )
        key_values.append(value)

    # Direct dictionary lookup with tuple key
    lookup_key = tuple(key_values)

    # Check cache first
    if lookup_key in self._lookup_cache:
        return self._lookup_cache[lookup_key]

    if debug:
        logger.debug(f"    [LOOKUP] Key: {lookup_key}")

    # dictionary lookup
    result = self._lookup_dict.get(lookup_key)

    if result is None:
        raise KeyError(
            f"Source '{self.name}' has no row for key {lookup_key}. No fallbacks. "
            "The data must cover every demographic combination the "
            "model produces, or this is a real gap."
        )

    if debug:
        logger.debug(f"    [LOOKUP] ✓ Found data: {list(result.keys())[:3]}...")

    # Normalize the result (convert counts to probabilities)
    result = self._normalize_probabilities(result)

    # Cache the normalized result
    self._lookup_cache[lookup_key] = result

    return result

OriginDestinationMatrixSource

Bases: DataSource

Data source for origin-destination flow matrices.

Used for commuting patterns, migration flows, etc. Returns all possible destinations for a given origin with associated likelihoods.

Source code in may/attribute_assignment/data_sources.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
class OriginDestinationMatrixSource(DataSource):
    """
    Data source for origin-destination flow matrices.

    Used for commuting patterns, migration flows, etc.
    Returns all possible destinations for a given origin with associated likelihoods.
    """

    def __init__(self, name: str, config: Dict[str, Any]):
        """Initialize O-D matrix source."""
        super().__init__(name, config)
        # Lookup: origin_code -> [(destination, metadata_dict, likelihood), ...]
        self._lookup: Dict[str, List[Tuple[str, Dict[str, Any], float]]] = {}
        self._file_configs = config.get('files', [])

        # Out-of-boundary destination policy. Required, with no default, because
        # a destination drawn outside the loaded world boundary is routine in
        # region runs and impossible in whole-country runs, so the engine refuses
        # to guess what to do with it.
        self._out_of_boundary = config.get('out_of_boundary')
        if self._out_of_boundary is None:
            raise ValueError(
                f"O-D source '{self.name}' must declare 'out_of_boundary' "
                "(error | redistribute | outside). It is required, with no "
                "default. Silence is never interpreted."
            )
        if self._out_of_boundary not in ('error', 'redistribute', 'outside'):
            raise ValueError(
                f"O-D source '{self.name}': out_of_boundary='{self._out_of_boundary}' "
                "is not one of error | redistribute | outside."
            )
        self._outside_value = config.get('outside_value')
        self._on_empty = config.get('on_empty')
        if self._out_of_boundary == 'redistribute':
            if self._on_empty not in ('error', 'outside'):
                raise ValueError(
                    f"O-D source '{self.name}': out_of_boundary='redistribute' "
                    "requires 'on_empty' (error | outside) for origins whose entire "
                    "distribution is out-of-boundary."
                )
        # The sentinel value is required whenever the 'outside' outcome can occur.
        outside_can_occur = (
            self._out_of_boundary == 'outside'
            or (self._out_of_boundary == 'redistribute' and self._on_empty == 'outside')
        )
        if outside_can_occur and not self._outside_value:
            raise ValueError(
                f"O-D source '{self.name}': 'outside_value' is required when the "
                "'outside' outcome can occur."
            )

        # Optional marker for redistributed assignments. Names the person
        # property set true when an assignment was bounced back in-boundary, so
        # the venue layer can deprioritise it. Config-named, so the engine carries
        # whatever the scenario calls it. Only meaningful under 'redistribute':
        # flagging it elsewhere raises (no silent no-ops).
        self._redistributed_flag = config.get('redistributed_flag')
        if self._redistributed_flag is not None and self._out_of_boundary != 'redistribute':
            raise ValueError(
                f"O-D source '{self.name}': 'redistributed_flag' is only valid under "
                f"out_of_boundary='redistribute', not '{self._out_of_boundary}'."
            )
        # Per-origin fraction of flow that was bounced back in-boundary, populated
        # by the redistribute branch of _apply_boundary_policy. Empty otherwise.
        self._redistributed_fraction: Dict[str, float] = {}

    def load_data(self, geo_units: Optional[set] = None):
        """Load origin-destination flow data from CSV."""
        logger.info(f"Loading data for source '{self.name}'...")

        # Merged across files on origin keys; origins must be file-disjoint.
        merged: Dict = {}
        for file_config in self._file_configs:
            file_path = Path(pr.resolve(file_config['path']))

            if file_path.exists():
                try:
                    df = pd.read_csv(file_path)

                    # Get column configuration
                    key_columns_config = file_config.get('key_columns', {})
                    destination_column = file_config.get('destination_column')
                    likelihood_column = file_config.get('likelihood_column')
                    metadata_columns = file_config.get('metadata_columns', {})
                    exclude_destinations = file_config.get('exclude_destinations', [])

                    # Origin column is the first key in key_columns
                    if not key_columns_config:
                        raise ValueError(
                            f"O-D source '{self.name}' has no 'key_columns'; cannot "
                            "determine the origin column."
                        )
                    origin_column = list(key_columns_config.keys())[0]

                    # Filter to only relevant geographical units
                    # Only filter if geo_units values actually match origin column values
                    if geo_units and origin_column and origin_column in df.columns:
                        # Check if there's any overlap between geo_units and origin values
                        origin_values = set(df[origin_column].unique())
                        overlap = origin_values.intersection(geo_units)

                        if overlap:  # Only filter if there's matching values
                            original_len = len(df)
                            df = df[df[origin_column].isin(geo_units)]
                            logger.info(f"  Filtered O-D matrix from {original_len} to {len(df)} rows based on {len(overlap)} matching origins")

                    # Parse DataFrame
                    lookup = self._parse_od_dataframe(
                        df,
                        origin_column,
                        destination_column,
                        likelihood_column,
                        metadata_columns,
                        exclude_destinations
                    )

                    logger.info(f"  ✓ Loaded {len(lookup)} origins from {file_path.name}")

                except Exception as e:
                    # Fail loud on a load/parse error.
                    raise RuntimeError(
                        f"failed to load data source file {file_path}: {e}"
                    ) from e
                _merge_disjoint(merged, lookup, self.name, file_path)
            else:
                raise FileNotFoundError(f"data source file not found: {file_path}")
        self._lookup = merged

        # Apply the out-of-boundary policy AFTER parsing and OUTSIDE the
        # per-file try/except above, since policy violations must fail loud.
        self._apply_boundary_policy(geo_units)

        self._data_loaded = True

    def _boundary_units(self, geo_units: set) -> set:
        """Narrow the loaded geo units to the level destinations are declared at.

        Every file entry must agree on `destination_level`; a source mixing
        levels in one destination column has no single answer here. When the
        caller supplied no level breakdown (a direct programmatic load rather
        than a World run) the flat set stands in.
        """
        levels = {fc.get('destination_level') for fc in self._file_configs}
        levels.discard(None)
        if not levels:
            return geo_units
        if len(levels) > 1:
            raise ValueError(
                f"O-D source '{self.name}': files disagree on 'destination_level' "
                f"({sorted(levels)}). All destinations in one source must live at "
                "the same hierarchy level."
            )
        level = levels.pop()
        if not self.geo_units_by_level:
            return geo_units
        if level not in self.geo_units_by_level:
            raise ValueError(
                f"O-D source '{self.name}': destination_level='{level}' is not a "
                f"level in the loaded geography ({sorted(self.geo_units_by_level)})."
            )
        return self.geo_units_by_level[level]

    def _apply_boundary_policy(self, geo_units: Optional[set]):
        """
        Resolve destinations that fall outside the loaded world boundary
        according to the configured `out_of_boundary` policy.

        Boundary membership is "destination value is among the loaded geo units
        AT `destination_level`". Scoping to the declared level matters because
        names repeat across levels: a census O-D table lists whole-country
        catch-alls ("Wales", "England") next to real LADs, and an unscoped check
        would call "Wales" in-boundary whenever any Welsh unit is loaded, then
        hand a non-existent LAD to the steps that sample within it.

        With no geo_units (an unbounded / whole-world run) there is no boundary,
        so the policy is a no-op.
        """
        if not geo_units:
            return

        geo_units = self._boundary_units(geo_units)

        # Metadata keys carried per destination (e.g. work_mode). The sentinel
        # destination must carry the same keys so output wiring still resolves.
        meta_keys = []
        for fc in self._file_configs:
            for k in fc.get('metadata_columns', {}).keys():
                if k not in meta_keys:
                    meta_keys.append(k)

        new_lookup: Dict[str, List[Tuple[str, Dict[str, Any], float]]] = {}
        error_offenders: Dict[str, List[str]] = {}
        empty_origins: List[str] = []
        origins_with_out = 0
        dropped_options = 0
        out_mass_total = 0.0
        outside_origins = 0

        for origin, dests in self._lookup.items():
            in_b = [(d, m, l) for (d, m, l) in dests if d in geo_units]
            out_b = [(d, m, l) for (d, m, l) in dests if d not in geo_units]
            if not out_b:
                new_lookup[origin] = dests
                continue

            origins_with_out += 1
            out_mass = sum(l for _, _, l in out_b)
            out_mass_total += out_mass

            if self._out_of_boundary == 'error':
                error_offenders[origin] = [d for d, _, _ in out_b]
                new_lookup[origin] = dests
            elif self._out_of_boundary == 'redistribute':
                dropped_options += len(out_b)
                in_total = sum(l for _, _, l in in_b)
                if in_total <= 0:
                    empty_origins.append(origin)
                    new_lookup[origin] = []  # resolved by on_empty below
                else:
                    new_lookup[origin] = [(d, m, l / in_total) for (d, m, l) in in_b]
                    # Probability a worker from this origin was bounced back in
                    # (= the out-of-boundary mass that got redistributed). Drives
                    # the per-person Bernoulli mark in the strategy.
                    self._redistributed_fraction[origin] = out_mass
            else:  # 'outside'
                outside_origins += 1
                # Each out-of-boundary row takes the sentinel as its destination
                # but keeps its own metadata; rows with identical metadata merge.
                # Collapsing them all onto one row stamped with the sentinel
                # would erase the distinctions a downstream draw may condition on, and
                # a draw restricted to travelling work modes would then find no
                # sentinel row at all and silently renormalise the out-of-area
                # mass onto in-world destinations.
                merged_out: Dict[Tuple, Tuple[Dict[str, Any], float]] = {}
                for _, m, l in out_b:
                    meta = {k: m.get(k) for k in meta_keys}
                    key = tuple(sorted((k, str(v)) for k, v in meta.items()))
                    _, carried = merged_out.get(key, (None, 0.0))
                    merged_out[key] = (meta, carried + l)
                new_lookup[origin] = in_b + [
                    (self._outside_value, meta, mass) for meta, mass in merged_out.values()
                ]

        if self._out_of_boundary == 'error' and error_offenders:
            sample = sorted({d for ds in error_offenders.values() for d in ds})[:15]
            raise ValueError(
                f"O-D source '{self.name}': out_of_boundary='error' but "
                f"{len(error_offenders)} origin(s) have out-of-boundary destinations "
                f"(e.g. {sample}). Set out_of_boundary to 'redistribute' or 'outside', "
                "or load those destinations into the world."
            )

        if self._out_of_boundary == 'redistribute':
            if empty_origins:
                logger.warning(
                    f"  [out_of_boundary] {len(empty_origins)} origin(s) have NO "
                    f"in-boundary destination (e.g. {empty_origins[:15]})."
                )
                if self._on_empty == 'error':
                    raise ValueError(
                        f"O-D source '{self.name}': {len(empty_origins)} origin(s) have "
                        f"no in-boundary destination and on_empty='error' "
                        f"(e.g. {empty_origins[:15]}). Switch on_empty to 'outside', or "
                        "shrink/extend the world."
                    )
                for origin in empty_origins:
                    sentinel_meta = {k: self._outside_value for k in meta_keys}
                    new_lookup[origin] = [(self._outside_value, sentinel_meta, 1.0)]
            mean_pct = 100.0 * out_mass_total / origins_with_out if origins_with_out else 0.0
            logger.info(
                f"  [out_of_boundary=redistribute] dropped {dropped_options} out-of-boundary "
                f"destination option(s) across {origins_with_out} origin(s); mean "
                f"{mean_pct:.1f}% of flow redistributed inward per affected origin."
            )
        elif self._out_of_boundary == 'outside':
            logger.info(
                f"  [out_of_boundary=outside] {outside_origins} origin(s) route "
                f"out-of-boundary flow to sentinel '{self._outside_value}'."
            )

        self._lookup = new_lookup

    def _parse_od_dataframe(self, df: pd.DataFrame,
                           origin_column: str,
                           destination_column: str,
                           likelihood_column: str,
                           metadata_columns: Dict[str, str],
                           exclude_destinations: List[str]) -> Dict[str, List[Tuple[str, Dict[str, Any], float]]]:
        """
        Parse O-D DataFrame into lookup dictionary.

        Args:
            df: DataFrame to parse
            origin_column: Column with origin codes
            destination_column: Column with destination codes
            likelihood_column: Column with likelihood/probability values
            metadata_columns: Additional columns to include (e.g., work_mode)
            exclude_destinations: List of destination codes to exclude

        Returns:
            Dictionary mapping origin codes to list of (destination, metadata, likelihood) tuples
        """
        lookup = {}

        # Group by origin
        for origin, group in df.groupby(origin_column):
            destinations = []

            for _, row in group.iterrows():
                destination = row[destination_column]

                # Skip excluded destinations
                if destination in exclude_destinations:
                    continue

                likelihood = float(row[likelihood_column])

                # Collect metadata
                metadata = {}
                for meta_key, meta_column in metadata_columns.items():
                    if meta_column in df.columns:
                        metadata[meta_key] = row[meta_column]

                destinations.append((destination, metadata, likelihood))

            # Normalize likelihoods to sum to 1.0
            total_likelihood = sum(lik for _, _, lik in destinations)
            if total_likelihood > 0:
                destinations = [
                    (dest, meta, lik / total_likelihood)
                    for dest, meta, lik in destinations
                ]

            lookup[origin] = destinations

        return lookup

    def lookup(self, origin: str) -> List[Tuple[str, Dict[str, Any], float]]:
        """
        Look up possible destinations for a given origin.

        Args:
            origin: Origin code (e.g., SGU code)

        Returns:
            List of (destination, metadata, likelihood) tuples
        """
        if not self._data_loaded:
            raise RuntimeError(
                f"Data not loaded for source '{self.name}'. No fallbacks."
            )
        if origin not in self._lookup:
            raise KeyError(
                f"Source '{self.name}' has no destinations for origin '{origin}'. "
                "No fallbacks. The O-D matrix must cover every origin."
            )
        return self._lookup[origin]

__init__(name, config)

Initialize O-D matrix source.

Source code in may/attribute_assignment/data_sources.py
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
def __init__(self, name: str, config: Dict[str, Any]):
    """Initialize O-D matrix source."""
    super().__init__(name, config)
    # Lookup: origin_code -> [(destination, metadata_dict, likelihood), ...]
    self._lookup: Dict[str, List[Tuple[str, Dict[str, Any], float]]] = {}
    self._file_configs = config.get('files', [])

    # Out-of-boundary destination policy. Required, with no default, because
    # a destination drawn outside the loaded world boundary is routine in
    # region runs and impossible in whole-country runs, so the engine refuses
    # to guess what to do with it.
    self._out_of_boundary = config.get('out_of_boundary')
    if self._out_of_boundary is None:
        raise ValueError(
            f"O-D source '{self.name}' must declare 'out_of_boundary' "
            "(error | redistribute | outside). It is required, with no "
            "default. Silence is never interpreted."
        )
    if self._out_of_boundary not in ('error', 'redistribute', 'outside'):
        raise ValueError(
            f"O-D source '{self.name}': out_of_boundary='{self._out_of_boundary}' "
            "is not one of error | redistribute | outside."
        )
    self._outside_value = config.get('outside_value')
    self._on_empty = config.get('on_empty')
    if self._out_of_boundary == 'redistribute':
        if self._on_empty not in ('error', 'outside'):
            raise ValueError(
                f"O-D source '{self.name}': out_of_boundary='redistribute' "
                "requires 'on_empty' (error | outside) for origins whose entire "
                "distribution is out-of-boundary."
            )
    # The sentinel value is required whenever the 'outside' outcome can occur.
    outside_can_occur = (
        self._out_of_boundary == 'outside'
        or (self._out_of_boundary == 'redistribute' and self._on_empty == 'outside')
    )
    if outside_can_occur and not self._outside_value:
        raise ValueError(
            f"O-D source '{self.name}': 'outside_value' is required when the "
            "'outside' outcome can occur."
        )

    # Optional marker for redistributed assignments. Names the person
    # property set true when an assignment was bounced back in-boundary, so
    # the venue layer can deprioritise it. Config-named, so the engine carries
    # whatever the scenario calls it. Only meaningful under 'redistribute':
    # flagging it elsewhere raises (no silent no-ops).
    self._redistributed_flag = config.get('redistributed_flag')
    if self._redistributed_flag is not None and self._out_of_boundary != 'redistribute':
        raise ValueError(
            f"O-D source '{self.name}': 'redistributed_flag' is only valid under "
            f"out_of_boundary='redistribute', not '{self._out_of_boundary}'."
        )
    # Per-origin fraction of flow that was bounced back in-boundary, populated
    # by the redistribute branch of _apply_boundary_policy. Empty otherwise.
    self._redistributed_fraction: Dict[str, float] = {}

load_data(geo_units=None)

Load origin-destination flow data from CSV.

Source code in may/attribute_assignment/data_sources.py
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
def load_data(self, geo_units: Optional[set] = None):
    """Load origin-destination flow data from CSV."""
    logger.info(f"Loading data for source '{self.name}'...")

    # Merged across files on origin keys; origins must be file-disjoint.
    merged: Dict = {}
    for file_config in self._file_configs:
        file_path = Path(pr.resolve(file_config['path']))

        if file_path.exists():
            try:
                df = pd.read_csv(file_path)

                # Get column configuration
                key_columns_config = file_config.get('key_columns', {})
                destination_column = file_config.get('destination_column')
                likelihood_column = file_config.get('likelihood_column')
                metadata_columns = file_config.get('metadata_columns', {})
                exclude_destinations = file_config.get('exclude_destinations', [])

                # Origin column is the first key in key_columns
                if not key_columns_config:
                    raise ValueError(
                        f"O-D source '{self.name}' has no 'key_columns'; cannot "
                        "determine the origin column."
                    )
                origin_column = list(key_columns_config.keys())[0]

                # Filter to only relevant geographical units
                # Only filter if geo_units values actually match origin column values
                if geo_units and origin_column and origin_column in df.columns:
                    # Check if there's any overlap between geo_units and origin values
                    origin_values = set(df[origin_column].unique())
                    overlap = origin_values.intersection(geo_units)

                    if overlap:  # Only filter if there's matching values
                        original_len = len(df)
                        df = df[df[origin_column].isin(geo_units)]
                        logger.info(f"  Filtered O-D matrix from {original_len} to {len(df)} rows based on {len(overlap)} matching origins")

                # Parse DataFrame
                lookup = self._parse_od_dataframe(
                    df,
                    origin_column,
                    destination_column,
                    likelihood_column,
                    metadata_columns,
                    exclude_destinations
                )

                logger.info(f"  ✓ Loaded {len(lookup)} origins from {file_path.name}")

            except Exception as e:
                # Fail loud on a load/parse error.
                raise RuntimeError(
                    f"failed to load data source file {file_path}: {e}"
                ) from e
            _merge_disjoint(merged, lookup, self.name, file_path)
        else:
            raise FileNotFoundError(f"data source file not found: {file_path}")
    self._lookup = merged

    # Apply the out-of-boundary policy AFTER parsing and OUTSIDE the
    # per-file try/except above, since policy violations must fail loud.
    self._apply_boundary_policy(geo_units)

    self._data_loaded = True

lookup(origin)

Look up possible destinations for a given origin.

Parameters:

Name Type Description Default
origin str

Origin code (e.g., SGU code)

required

Returns:

Type Description
List[Tuple[str, Dict[str, Any], float]]

List of (destination, metadata, likelihood) tuples

Source code in may/attribute_assignment/data_sources.py
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
def lookup(self, origin: str) -> List[Tuple[str, Dict[str, Any], float]]:
    """
    Look up possible destinations for a given origin.

    Args:
        origin: Origin code (e.g., SGU code)

    Returns:
        List of (destination, metadata, likelihood) tuples
    """
    if not self._data_loaded:
        raise RuntimeError(
            f"Data not loaded for source '{self.name}'. No fallbacks."
        )
    if origin not in self._lookup:
        raise KeyError(
            f"Source '{self.name}' has no destinations for origin '{origin}'. "
            "No fallbacks. The O-D matrix must cover every origin."
        )
    return self._lookup[origin]

PairProbabilitySource

Bases: DataSource

Data source for pair probabilities.

Provides conditional probabilities: given first person's attribute value, what is the probability of second person having each value?

Source code in may/attribute_assignment/data_sources.py
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
class PairProbabilitySource(DataSource):
    """
    Data source for pair probabilities.

    Provides conditional probabilities: given first person's attribute value,
    what is the probability of second person having each value?
    """

    def __init__(self, name: str, config: Dict[str, Any]):
        """Initialize pair probability source."""
        super().__init__(name, config)
        # Nested lookup: geo_unit -> first_ethnicity -> partner_ethnicity -> probability
        self._lookups: Dict[str, Dict[str, Dict[str, float]]] = {}
        self._file_configs = config.get('files', [])

    def load_data(self, geo_units: Optional[set] = None):
        """Load pair probability data."""
        logger.info(f"Loading data for source '{self.name}'...")

        merged: Dict[str, Dict[str, Dict[str, float]]] = {}
        for file_config in self._file_configs:
            file_path = Path(pr.resolve(file_config['path']))

            if file_path.exists():
                try:
                    df = pd.read_csv(file_path)

                    # Filter to needed areas if specified
                    key_columns = _ordered_key_columns(file_config, self.name, expected=2)
                    if geo_units and key_columns[0] in df.columns:
                        df = df[df[key_columns[0]].isin(geo_units)]

                    value_columns = file_config.get('value_columns', {})
                    lookups = self._parse_pair_dataframe(df, key_columns, value_columns)

                    logger.info(f"  ✓ Loaded {len(lookups)} geographical units from {file_path.name}")

                except Exception as e:
                    # Fail loud on a load/parse error.
                    raise RuntimeError(
                        f"failed to load data source file {file_path}: {e}"
                    ) from e
                _merge_disjoint(merged, lookups, self.name, file_path)
            else:
                raise FileNotFoundError(f"data source file not found: {file_path}")
        self._lookups = merged

        self._data_loaded = True

    def _parse_pair_dataframe(self, df: pd.DataFrame, key_columns: List[str],
                              value_columns: Dict[str, str]) -> Dict[str, Dict[str, Dict[str, float]]]:
        """Parse pair probability DataFrame into nested lookup."""
        lookup = {}

        geo_col, first_value_col = key_columns[0], key_columns[1]

        for _, row in df.iterrows():
            geo_unit = row[geo_col]
            first_value = row[first_value_col]

            # Build second person probability distribution
            second_probs = {}
            for output_key, df_column in value_columns.items():
                if df_column in df.columns:
                    second_probs[output_key] = float(row[df_column])

            # Normalize
            second_probs = self._normalize_probabilities(second_probs)

            # Store in nested structure
            if geo_unit not in lookup:
                lookup[geo_unit] = {}
            lookup[geo_unit][first_value] = second_probs

        return lookup

    def lookup(self, geo_unit: str, first_value: str) -> Dict[str, float]:
        """
        Look up pair probabilities.

        Args:
            geo_unit: Geographical unit code
            first_value: Attribute value of first person

        Returns:
            Probability distribution for second person's attribute value
        """
        if not self._data_loaded:
            raise RuntimeError(
                f"Data not loaded for source '{self.name}'. No fallbacks."
            )

        # Look up geographical unit
        if geo_unit in self._lookups:
            # Look up first value within unit
            if first_value in self._lookups[geo_unit]:
                return self._lookups[geo_unit][first_value]

        raise KeyError(
            f"Source '{self.name}' has no pair row for (geo='{geo_unit}', "
            f"first='{first_value}'). No fallbacks. The pair data must cover "
            "every (unit, first-value) combination the model produces."
        )

__init__(name, config)

Initialize pair probability source.

Source code in may/attribute_assignment/data_sources.py
405
406
407
408
409
410
def __init__(self, name: str, config: Dict[str, Any]):
    """Initialize pair probability source."""
    super().__init__(name, config)
    # Nested lookup: geo_unit -> first_ethnicity -> partner_ethnicity -> probability
    self._lookups: Dict[str, Dict[str, Dict[str, float]]] = {}
    self._file_configs = config.get('files', [])

load_data(geo_units=None)

Load pair probability data.

Source code in may/attribute_assignment/data_sources.py
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
def load_data(self, geo_units: Optional[set] = None):
    """Load pair probability data."""
    logger.info(f"Loading data for source '{self.name}'...")

    merged: Dict[str, Dict[str, Dict[str, float]]] = {}
    for file_config in self._file_configs:
        file_path = Path(pr.resolve(file_config['path']))

        if file_path.exists():
            try:
                df = pd.read_csv(file_path)

                # Filter to needed areas if specified
                key_columns = _ordered_key_columns(file_config, self.name, expected=2)
                if geo_units and key_columns[0] in df.columns:
                    df = df[df[key_columns[0]].isin(geo_units)]

                value_columns = file_config.get('value_columns', {})
                lookups = self._parse_pair_dataframe(df, key_columns, value_columns)

                logger.info(f"  ✓ Loaded {len(lookups)} geographical units from {file_path.name}")

            except Exception as e:
                # Fail loud on a load/parse error.
                raise RuntimeError(
                    f"failed to load data source file {file_path}: {e}"
                ) from e
            _merge_disjoint(merged, lookups, self.name, file_path)
        else:
            raise FileNotFoundError(f"data source file not found: {file_path}")
    self._lookups = merged

    self._data_loaded = True

lookup(geo_unit, first_value)

Look up pair probabilities.

Parameters:

Name Type Description Default
geo_unit str

Geographical unit code

required
first_value str

Attribute value of first person

required

Returns:

Type Description
Dict[str, float]

Probability distribution for second person's attribute value

Source code in may/attribute_assignment/data_sources.py
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
def lookup(self, geo_unit: str, first_value: str) -> Dict[str, float]:
    """
    Look up pair probabilities.

    Args:
        geo_unit: Geographical unit code
        first_value: Attribute value of first person

    Returns:
        Probability distribution for second person's attribute value
    """
    if not self._data_loaded:
        raise RuntimeError(
            f"Data not loaded for source '{self.name}'. No fallbacks."
        )

    # Look up geographical unit
    if geo_unit in self._lookups:
        # Look up first value within unit
        if first_value in self._lookups[geo_unit]:
            return self._lookups[geo_unit][first_value]

    raise KeyError(
        f"Source '{self.name}' has no pair row for (geo='{geo_unit}', "
        f"first='{first_value}'). No fallbacks. The pair data must cover "
        "every (unit, first-value) combination the model produces."
    )