Neighborhood Module API Reference
Module for performing neighborhood analysis.
NBHD
A class representing neighborhoods with associated derived data matrices.
Source code in src/celldega/nbhd/neighborhoods.py
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
set_derived(key, subkey=None)
Set a derived data matrix.
Source code in src/celldega/nbhd/neighborhoods.py
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 | |
alpha_shape_cell_clusters(adata, cat='cluster', alphas=(100, 150, 200, 250, 300, 350), meta_cluster=None)
Compute alpha shapes for each cluster in the cell metadata.
Parameters
adata : AnnData AnnData object with cell metadata in obs and spatial coordinates in obsm["spatial"]. cat : str Column name in adata.obs containing cluster/category labels. alphas : Sequence[float] List of inverse alpha values to compute shapes for. meta_cluster : pd.DataFrame | None Optional DataFrame with cluster metadata including 'color' column. If not provided, colors will be extracted from adata.uns[f'{cat}_colors'] if available, otherwise defaults to black.
Returns
gpd.GeoDataFrame GeoDataFrame with alpha shapes for each cluster at each alpha value.
Source code in src/celldega/nbhd/alpha_shapes.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
calc_grad_nbhd_from_roi(polygon, gdf_reference, band_width=300)
Generate concentric rings (neighborhood bands) from a polygon, clipped to the convex hull of a reference GeoDataFrame.
Parameters
polygon : GeoDataFrame GeoDataFrame containing a single polygon. gdf_reference : GeoDataFrame Reference GeoDataFrame used to calculate the boundary area (convex hull). band_width : float Width of each band in microns (default: 300).
Returns
GeoDataFrame GeoDataFrame with columns for band (index of ring) and geometry (polygon).
Source code in src/celldega/nbhd/gradient.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
calc_nbhd_bordering(gdf_nbhd, metric='border_ratio', name_col='name', category='leiden')
Calculate pairwise border relationships between neighborhoods as a neighborhood-by-neighborhood matrix.
Parameters
gdf_nbhd : gpd.GeoDataFrame
GeoDataFrame containing neighborhood geometries. Must have a geometry column
and a column specified by name_col for neighborhood identifiers.
metric : str, default "border_ratio"
The border metric to compute:
- "border_ratio": Border length over self (row) perimeter.
Value = shared_border_length / row_perimeter.
Asymmetric measure showing what fraction of the row neighborhood's
perimeter is shared with the column neighborhood.
- "border_length": Raw shared border length in linear units.
Symmetric measure of the absolute length of shared boundary.
- "binary": Binary adjacency (1 if touching, 0 otherwise).
Symmetric measure indicating whether neighborhoods share a border.
name_col : str, default "name"
Column name containing neighborhood identifiers.
category : str, default "leiden"
Name of the category that neighborhoods represent (e.g., "leiden", "cell_type").
This is used to name the category column in obs/var and the colors in uns.
Returns
AnnData
AnnData object with shape (n_neighborhoods, n_neighborhoods) where:
- X: Matrix of border metric values
- obs: DataFrame indexed by neighborhood names (rows)
- var: DataFrame indexed by neighborhood names (columns)
- obs["perimeter"]: Perimeter of each neighborhood
- obs[category]: Category value for each neighborhood
- uns["metric"]: The metric used for computation
Notes
Shared border length is computed as the length of the intersection of the
two neighborhood boundaries (perimeters). This works for neighborhoods that
touch but don't overlap. For overlapping neighborhoods, consider using
calc_nbhd_overlap instead.
Examples
adata_border = dega.nbhd.calc_nbhd_bordering(gdf_nbhd, metric="border_ratio") adata_adj = dega.nbhd.calc_nbhd_bordering(gdf_nbhd, metric="binary") mat = dega.clust.Matrix(adata_border, row_entity="nbhd", col_entity="nbhd")
Source code in src/celldega/nbhd/neighborhoods.py
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 | |
calc_nbhd_by_gene(gdf_nbhd, by='cell', adata=None, data_dir=None, nbhd_col='name', min_cells=1)
Calculate neighborhood-by-gene expression matrix.
Computes gene expression values for each neighborhood, either from cell-level expression data (mean expression of cells within each neighborhood) or from raw transcript counts (cell-free mode).
Parameters
gdf_nbhd : gpd.GeoDataFrame
GeoDataFrame containing neighborhood geometries. Must have a geometry column
and a column specified by nbhd_col for neighborhood identifiers.
by : str, default "cell"
Method for calculating gene expression:
- "cell": Mean expression of cells within each neighborhood (requires adata)
- "cell-free": Transcript counts within each neighborhood (requires data_dir)
adata : AnnData, optional
AnnData object with cell data. Required when by="cell". Must have spatial
coordinates in obsm["spatial"].
data_dir : str, optional
Path to directory containing transcripts.parquet. Required when
by="cell-free".
nbhd_col : str, default "name"
Column in gdf_nbhd containing neighborhood identifiers.
min_cells : int, default 1
Minimum number of cells/transcripts required within a neighborhood to
include it in the output. Only applies when by="cell".
Returns
AnnData
AnnData object with shape (n_neighborhoods, n_genes) where:
- X: Matrix of gene expression values (mean for cell-derived, counts for cell-free)
- obs: DataFrame indexed by neighborhood names
- var: DataFrame indexed by gene names
- obs["n_cells"]: Cell count per neighborhood (when by="cell")
- uns["by"]: Method used ("cell" or "cell-free")
Examples
Cell-derived gene expression per neighborhood
adata_nbg = dega.nbhd.calc_nbhd_by_gene(gdf_alpha, by="cell", adata=adata)
Cell-free transcript counts per neighborhood
adata_nbg = dega.nbhd.calc_nbhd_by_gene(gdf_alpha, by="cell-free", data_dir="./data")
For cluster-specific analysis, pre-filter the AnnData
adata_cluster0 = adata[adata.obs["leiden"] == "0"] adata_nbg = dega.nbhd.calc_nbhd_by_gene(gdf_alpha, by="cell", adata=adata_cluster0)
Notes
For cluster-specific gene expression analysis, filter your AnnData object to include only cells from the desired cluster before calling this function.
Source code in src/celldega/nbhd/neighborhoods.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |
calc_nbhd_by_pop(adata, gdf_nbhd, category='leiden', nbhd_col='name', min_cells=5, output='percentage')
Calculate cell-level population distribution of neighborhoods.
Computes a neighborhood-by-population matrix showing the distribution of cell categories (e.g., clusters, cell types) within each neighborhood.
Parameters
adata : AnnData
AnnData object containing cell data. Must have spatial coordinates in
obsm["spatial"] and the category column in obs.
gdf_nbhd : gpd.GeoDataFrame
GeoDataFrame containing neighborhood geometries. Must have a geometry column
and a column specified by nbhd_col for neighborhood identifiers.
category : str, default "leiden"
Column name in adata.obs containing cell category labels (e.g., "leiden",
"cell_type", "cluster").
nbhd_col : str, default "name"
Column name in gdf_nbhd containing neighborhood identifiers.
min_cells : int, default 5
Minimum number of cells required within a neighborhood to include it in
the output. Neighborhoods with fewer cells are filtered out.
output : str, default "percentage"
Type of values in the output matrix:
- "percentage": Fraction of cells per category (sums to 1 per neighborhood)
- "counts": Raw cell counts per category
Returns
AnnData
AnnData object with shape (n_neighborhoods, n_categories) where:
- X: Matrix of population distributions (percentages or counts)
- obs: DataFrame indexed by neighborhood names
- var: DataFrame indexed by category names
- obs["n_cells"]: Total cell count per neighborhood
Examples
adata_nbp = dega.nbhd.calc_nbhd_by_pop(adata, gdf_alpha, category="leiden") adata_nbp.shape (42, 18) # 42 neighborhoods, 18 clusters
Source code in src/celldega/nbhd/neighborhoods.py
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 | |
calc_nbhd_overlap(gdf_nbhd, metric='iou', name_col='name', category='leiden')
Calculate pairwise overlap between all neighborhoods as a neighborhood-by-neighborhood matrix.
Parameters
gdf_nbhd : gpd.GeoDataFrame
GeoDataFrame containing neighborhood geometries. Must have a geometry column
and a column specified by name_col for neighborhood identifiers.
metric : str, default "iou"
The overlap metric to compute:
- "iou": Intersection over Union. Value = intersection_area / union_area.
Symmetric measure ranging from 0 (no overlap) to 1 (identical geometries).
- "ioa": Intersection over Area (of self/row). Value = intersection_area / row_area.
Asymmetric measure showing what fraction of the row neighborhood overlaps
with the column neighborhood. Useful for containment analysis.
- "intersection": Raw intersection area in square units.
name_col : str, default "name"
Column name containing neighborhood identifiers.
category : str, default "leiden"
Name of the category that neighborhoods represent (e.g., "leiden", "cell_type").
This is used to name the category column in obs/var and the colors in uns.
Returns
AnnData
AnnData object with shape (n_neighborhoods, n_neighborhoods) where:
- X: Matrix of overlap values
- obs: DataFrame indexed by neighborhood names (rows)
- var: DataFrame indexed by neighborhood names (columns)
- obs["area"]: Area of each neighborhood
- obs[category]: Category value for each neighborhood
- uns["metric"]: The metric used for computation
Examples
adata_iou = dega.nbhd.calc_nbhd_overlap(gdf_nbhd, metric="iou") adata_ioa = dega.nbhd.calc_nbhd_overlap(gdf_nbhd, metric="ioa") mat = dega.clust.Matrix(adata_iou, row_entity="nbhd", col_entity="nbhd")
Source code in src/celldega/nbhd/neighborhoods.py
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 | |
filter_alpha_shapes(gdf_alpha, alpha, min_area=0, clean_names=True)
Filter alpha shapes by a specific alpha value and optionally clean up names.
Alpha shapes computed by alpha_shape_cell_clusters have names in the format
{category}_{alpha} (e.g., "cluster_0_150"). This function filters to a specific
alpha value and removes the trailing _{alpha} suffix from names.
Parameters
gdf_alpha : gpd.GeoDataFrame
GeoDataFrame of alpha shapes with 'inv_alpha', 'area', 'name', and 'cat' columns.
Typically the output of alpha_shape_cell_clusters.
alpha : float
The inverse alpha value to filter for (must match values in 'inv_alpha' column).
min_area : float, default 0
Minimum area threshold. Shapes with area <= min_area are excluded.
clean_names : bool, default True
If True, removes the trailing _{alpha} suffix from the 'name' column,
leaving just the category name (e.g., "cluster_0" instead of "cluster_0_150").
Returns
gpd.GeoDataFrame Filtered GeoDataFrame with optionally cleaned names.
Examples
gdf_alpha = dega.nbhd.alpha_shape_cell_clusters(adata, cat="leiden") gdf_filtered = dega.nbhd.filter_alpha_shapes(gdf_alpha, alpha=150)
Names are now just category names without the alpha suffix
print(gdf_filtered["name"].tolist()[:3]) ['0', '1', '2']
Source code in src/celldega/nbhd/alpha_shapes.py
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 | |
generate_hextile(adata, diameter=100)
Generate a hexagonal grid over the bounding box of cell spatial coordinates.
Parameters
adata : AnnData
AnnData object with spatial coordinates in obsm["spatial"].
diameter : float, default 100
Diameter of each hexagon in the same units as the spatial coordinates
(typically microns).
Returns
gpd.GeoDataFrame GeoDataFrame with hexagon geometries covering the spatial extent. Columns: "name" (hex_0, hex_1, ...), "geometry" (Polygon).
Examples
gdf_hex = dega.nbhd.generate_hextile(adata, diameter=100) gdf_hex.shape (1234, 2)
Source code in src/celldega/nbhd/hextile.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
get_nbhd_meta(gdf_nbhd, unique_nbhd_col, gdf_trx, gdf_cell)
Compute neighborhood-level summary statistics including transcript and cell assignments, along with area and perimeter from geometry.
Source code in src/celldega/nbhd/neighborhoods.py
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | |
hextile_niche(gdf_hex, adata_hex, category='leiden', dissolve=True)
Create niche polygons from hextiles based on clustering results.
Takes hexagon geometries and assigns them to niches based on clustering (e.g., Leiden clustering of hexagon population distributions). Optionally dissolves adjacent hexagons of the same niche into unified polygons.
Parameters
gdf_hex : gpd.GeoDataFrame
GeoDataFrame of hexagon geometries. Must be indexed by hexagon name
(matching adata_hex.obs.index).
adata_hex : AnnData
AnnData object containing clustering results in obs[category].
The index must match the hexagon names in gdf_hex.
Colors can be provided in uns[f"{category}_colors"].
category : str, default "leiden"
Column name in adata_hex.obs containing the niche/cluster assignment.
dissolve : bool, default True
If True, dissolve adjacent hexagons of the same niche into unified
MultiPolygon geometries. If False, return individual hexagons with
their niche assignment.
Returns
gpd.GeoDataFrame If dissolve=True: GeoDataFrame with dissolved niche polygons. Columns: "name", "cat", "geometry", "color", "area". If dissolve=False: GeoDataFrame with individual hexagons and niche assignment. Columns: "name", "cat", "geometry", "color".
Examples
Generate hexagons and compute population distribution
gdf_hex = dega.nbhd.generate_hextile(adata, diameter=100) adata_hex = dega.nbhd.calc_nbhd_by_pop(adata, gdf_hex, category="leiden")
Cluster hexagons by population similarity (e.g., using scanpy)
import scanpy as sc sc.pp.pca(adata_hex) sc.pp.neighbors(adata_hex) sc.tl.leiden(adata_hex)
Create dissolved niche polygons
gdf_niche = dega.nbhd.hextile_niche(gdf_hex, adata_hex, category="leiden")
Or keep individual hexagons with niche assignment
gdf_hex_niche = dega.nbhd.hextile_niche(gdf_hex, adata_hex, dissolve=False)
Source code in src/celldega/nbhd/hextile.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |