Skip to content

openavmkit.condos

Condo resolution: bring condo units into the "one row per parcel" model.

Condo units are assessment parcels with no geometry of their own -- they physically sit inside a shared building/land parcel. openavmkit drops geometry-less rows, so condos normally vanish from the universe. This module gives each condo unit a borrowed building polygon (so every centroid-based enrichment -- DEM, census, OSM distances, basic-geo, Overture -- works and yields identical "shared parcel" values per building), assigns a condo_group building identifier (a location, like neighborhood), and computes a per-unit allocated land size.

It is opt-in via data.process.condos in settings and runs once at the top of process_data -- BEFORE the universe merge / geometry attach -- mutating the loaded dataframes dict. After it runs, the existing pipeline does everything else unchanged.

Settings schema (see resolve_condos docstring)::

"condos": {
  "enabled": true,
  "select": ["isin", "bldg_type", ["CONDOMINIUM", ...]],
  "link":   { "method": "id_prefix", "id_field": "parcel_num", "prefix_len": 9, "from": "geo_parcels" },
  "group_field": "condo_group",
  "borrow_geometry": true,
  "land_share": { "method": "field", "field": "land_area_sqft" },
  "inherit": ["zoning", "neighborhood"]
}

apply_deferred_land_share

apply_deferred_land_share(df_univ, settings, verbose=False)

After the universe merge: share each building's land by finished area among units whose finished area came from another file (land_share.method floor_area, the field not in the units' own file); and make every unit's land size its share, which a units file without a land column couldn't hold before the merge (left blank, a unit would later be given its whole building's shape area).

Source code in openavmkit/condos.py
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
def apply_deferred_land_share(df_univ: pd.DataFrame, settings: dict, verbose: bool = False) -> pd.DataFrame:
    """After the universe merge: share each building's land by finished area among units whose finished area
    came from another file (land_share.method floor_area, the field not in the units' own file); and make every
    unit's land size its share, which a units file without a land column couldn't hold before the merge (left
    blank, a unit would later be given its whole building's shape area)."""
    if LAND_ALLOC_FIELD in df_univ.columns:
        shared = pd.to_numeric(df_univ[LAND_ALLOC_FIELD], errors="coerce")
        if "land_area_sqft" not in df_univ.columns:
            df_univ["land_area_sqft"] = pd.NA
        df_univ.loc[shared.notna(), "land_area_sqft"] = shared[shared.notna()]
    if not _DEFERRED:
        return df_univ
    s = _settings_condos(settings)
    floor_field = s.get("land_share", {}).get("floor_field", "bldg_area_finished_sqft")
    if floor_field not in df_univ.columns:
        raise ValueError(f"condos.land_share.floor_field='{floor_field}' not found, even after the merge.")
    keys = df_univ["key"].astype(str)
    idx = df_univ.index[keys.isin(_DEFERRED.keys())]
    bid = keys.loc[idx].map(_DEFERRED)
    floor = pd.to_numeric(df_univ.loc[idx, floor_field], errors="coerce").fillna(0.0)
    total_floor = floor.groupby(bid).transform("sum")
    parcel_land = bid.map(lambda b: _GEOM_AREA_CACHE.get(b))
    share = (floor / total_floor).where(total_floor > 0, 0.0)
    alloc = share * pd.to_numeric(parcel_land, errors="coerce")
    if LAND_ALLOC_FIELD not in df_univ.columns:
        df_univ[LAND_ALLOC_FIELD] = pd.NA
    df_univ.loc[idx, LAND_ALLOC_FIELD] = alloc.values
    valid = alloc.notna()
    if "land_area_sqft" not in df_univ.columns:
        df_univ["land_area_sqft"] = pd.NA
    df_univ.loc[alloc.index[valid], "land_area_sqft"] = alloc[valid].values
    if verbose:
        print(f"resolve_condos: land_share 'floor_area' set {int(valid.sum())} units after the merge")
    return df_univ

apply_inherited_fields

apply_inherited_fields(df_univ, settings, verbose=False)

After the universe merge: each unit takes the fields listed in condos.inherit from the parcel it's on (zoning, a neighborhood, a school district: what's the land's, not the unit's), where its own is blank. Its shape already brings the rest of where it is (map layers, distances, census). Opt-in: nothing without inherit. A field no parcel has is skipped, with a warning.

Source code in openavmkit/condos.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def apply_inherited_fields(df_univ: pd.DataFrame, settings: dict, verbose: bool = False) -> pd.DataFrame:
    """After the universe merge: each unit takes the fields listed in ``condos.inherit`` from the parcel it's on
    (zoning, a neighborhood, a school district: what's the land's, not the unit's), where its own is blank. Its
    shape already brings the rest of where it is (map layers, distances, census). Opt-in: nothing without
    ``inherit``. A field no parcel has is skipped, with a warning."""
    fields = _settings_condos(settings).get("inherit") or []
    if not fields or not _PARENTS:
        return df_univ
    keys = df_univ["key"].astype(str)
    idx = df_univ.index[keys.isin(_PARENTS.keys())]
    parent = keys.loc[idx].map(_PARENTS)
    lookup = df_univ.assign(_key=keys).drop_duplicates("_key").set_index("_key")
    for field in fields:
        if field not in lookup.columns:
            warnings.warn(f"condos.inherit: the parcels have no field '{field}'; skipped.")
            continue
        theirs = parent.map(lookup[field])
        own = df_univ.loc[idx, field]
        df_univ.loc[idx, field] = own.where(own.notna(), theirs)
    if verbose:
        print(f"resolve_condos: {len(idx)} units took {', '.join(fields)} from the parcel they're on")
    return df_univ

resolve_condos

resolve_condos(dataframes, settings, verbose=False)

Resolve condo units into the universe by borrowing building geometry.

Opt-in via data.process.condos.enabled. For each universe-merge source frame containing condo rows (matched by select), this: 1. links each unit to a building polygon (link.method: id_prefix | parent_id | spatial); 2. borrows that polygon as the unit's geometry (appends rows to geo_parcels); 3. writes group_field (the building id) onto the source; 4. writes a per-unit allocated land size (land_share.method: field | floor_area | equal | none; floor_area with the finished area in another file is shared out after the merge: apply_deferred_land_share) to land_area_alloc_sqft and into land_area_sqft for condos; 5. auto-registers the new fields in field_classification; 6. remembers the parcel each unit is on, so that after the merge each unit can take that parcel's inherit fields where its own are blank (apply_inherited_fields).

Returns the (mutated) dataframes dict. A no-op when disabled.

Source code in openavmkit/condos.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def resolve_condos(dataframes: dict, settings: dict, verbose: bool = False) -> dict:
    """Resolve condo units into the universe by borrowing building geometry.

    Opt-in via ``data.process.condos.enabled``. For each universe-merge source frame
    containing condo rows (matched by ``select``), this:
      1. links each unit to a building polygon (``link.method``: id_prefix | parent_id | spatial);
      2. borrows that polygon as the unit's geometry (appends rows to ``geo_parcels``);
      3. writes ``group_field`` (the building id) onto the source;
      4. writes a per-unit allocated land size (``land_share.method``: field | floor_area | equal | none; floor_area
         with the finished area in another file is shared out after the merge: apply_deferred_land_share)
         to ``land_area_alloc_sqft`` and into ``land_area_sqft`` for condos;
      5. auto-registers the new fields in field_classification;
      6. remembers the parcel each unit is on, so that after the merge each unit can take that parcel's
         ``inherit`` fields where its own are blank (apply_inherited_fields).

    Returns the (mutated) dataframes dict. A no-op when disabled.
    """
    s = _settings_condos(settings)
    _DEFERRED.clear()
    _PARENTS.clear()
    if not s.get("enabled", False):
        return dataframes

    geo = dataframes.get("geo_parcels")
    if geo is None or "geometry" not in geo:
        warnings.warn("resolve_condos: no 'geo_parcels' with geometry; skipping.")
        return dataframes

    select = s.get("select")
    link = s.get("link", {})
    group_field = s.get("group_field", "condo_group")
    borrow = s.get("borrow_geometry", True)
    land_share = s.get("land_share", {})

    merge_univ = (
        settings.get("data", {}).get("process", {}).get("merge", {}).get("universe", [])
    )
    univ_ids = [e if isinstance(e, str) else e.get("id") for e in merge_univ]

    geo_keys = set(geo["key"].astype(str))
    if BORROWED_FLAG not in geo.columns:
        geo[BORROWED_FLAG] = False

    total_borrowed = 0
    for uid in univ_ids:
        df = dataframes.get(uid)
        if df is None or "key" not in df.columns:
            continue
        mask = resolve_filter(df, select) if select else pd.Series(True, index=df.index)
        if mask.sum() == 0:
            continue
        condos = df[mask]
        condo_idx = condos.index

        link_ids, geom_map, parent_keys = _resolve_link(condos, dataframes, link, verbose)
        _PARENTS.update(
            {str(k): parent_keys[b] for k, b in zip(condos["key"], link_ids) if pd.notna(b) and b in parent_keys}
        )

        # cache building polygon areas (sqft) for floor_area land-share
        if geom_map:
            rep_gdf = gpd.GeoDataFrame(
                {"_b": list(geom_map.keys())},
                geometry=list(geom_map.values()),
                crs=geo.crs,
            )
            _GEOM_AREA_CACHE.update(dict(zip(rep_gdf["_b"], _polygon_areas_sqft(rep_gdf).values)))

        # 3) condo_group
        if group_field not in df.columns:
            df[group_field] = pd.NA
        df.loc[condo_idx, group_field] = link_ids.values

        # 2) borrow geometry for units lacking their own polygon
        if borrow:
            keys = condos["key"].astype(str)
            need = condos[(~keys.isin(geo_keys)).values & link_ids.notna().values]
            need_ids = link_ids.loc[need.index]
            rows = []
            id_field = link.get("id_field")
            for i, (_, row) in enumerate(need.iterrows()):
                bid = need_ids.iloc[i]
                geom = geom_map.get(bid)
                if geom is None:
                    continue
                rec = {"key": str(row["key"]), "geometry": geom, BORROWED_FLAG: True}
                if id_field and id_field in need.columns:
                    rec[id_field] = row[id_field]
                rows.append(rec)
            if rows:
                add = gpd.GeoDataFrame(rows, geometry="geometry", crs=geo.crs)
                geo = gpd.GeoDataFrame(
                    pd.concat([geo, add], ignore_index=True), geometry="geometry", crs=geo.crs
                )
                geo_keys.update(add["key"].astype(str))
                total_borrowed += len(add)

        # 4) land share
        df = _apply_land_share(df, condo_idx, link_ids, geom_map, land_share, verbose)
        dataframes[uid] = df

        if verbose:
            print(
                f"resolve_condos['{uid}']: {int(mask.sum())} condo rows, "
                f"{int(link_ids.notna().sum())} linked"
            )

    dataframes["geo_parcels"] = geo
    if verbose:
        print(f"resolve_condos: borrowed geometry for {total_borrowed} condo units total")
    _auto_register_fields(settings, s)
    return dataframes