segger.data._utils¶
The _utils
module provides core utility functions for data processing, filtering, and management in the Segger framework. This module contains essential functions for handling spatial transcriptomics data, including coordinate processing, data filtering, and settings management.
SpatialTranscriptomicsDataset ¶
SpatialTranscriptomicsDataset(root, transform=None, pre_transform=None, pre_filter=None)
Bases: InMemoryDataset
A dataset class for handling SpatialTranscriptomics spatial transcriptomics data.
Attributes:
Name | Type | Description |
---|---|---|
root |
str
|
The root directory where the dataset is stored. |
transform |
callable
|
A function/transform that takes in a Data object and returns a transformed version. |
pre_transform |
callable
|
A function/transform that takes in a Data object and returns a transformed version. |
pre_filter |
callable
|
A function that takes in a Data object and returns a boolean indicating whether to keep it. |
Initialize the SpatialTranscriptomicsDataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
root |
str
|
Root directory where the dataset is stored. |
required |
transform |
callable
|
A function/transform that takes in a Data object and returns a transformed version. Defaults to None. |
None
|
pre_transform |
callable
|
A function/transform that takes in a Data object and returns a transformed version. Defaults to None. |
None
|
pre_filter |
callable
|
A function that takes in a Data object and returns a boolean indicating whether to keep it. Defaults to None. |
None
|
Source code in src/segger/data/_utils.py
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 |
|
processed_file_names
property
¶
processed_file_names
Return a list of processed file names in the processed directory.
Returns:
Type | Description |
---|---|
List[str]
|
List[str]: List of processed file names. |
raw_file_names
property
¶
raw_file_names
Return a list of raw file names in the raw directory.
Returns:
Type | Description |
---|---|
List[str]
|
List[str]: List of raw file names. |
download ¶
download()
Download the raw data. This method should be overridden if you need to download the data.
Source code in src/segger/data/_utils.py
957 958 959 |
|
get ¶
get(idx)
Get a processed data object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
idx |
int
|
Index of the data object to retrieve. |
required |
Returns:
Name | Type | Description |
---|---|---|
Data |
Data
|
The processed data object. |
Source code in src/segger/data/_utils.py
973 974 975 976 977 978 979 980 981 982 983 984 985 986 |
|
len ¶
len()
Return the number of processed files.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of processed files. |
Source code in src/segger/data/_utils.py
965 966 967 968 969 970 971 |
|
process ¶
process()
Process the raw data and save it to the processed directory. This method should be overridden if you need to process the data.
Source code in src/segger/data/_utils.py
961 962 963 |
|
add_transcript_ids ¶
add_transcript_ids(transcripts_df, x_col, y_col, id_col='transcript_id', precision=1000)
Add unique transcript IDs to a DataFrame based on x,y coordinates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
transcripts_df |
DataFrame
|
DataFrame containing transcript data with x,y coordinates. |
required |
x_col |
str
|
Name of the x-coordinate column. |
required |
y_col |
str
|
Name of the y-coordinate column. |
required |
id_col |
str
|
Name of the column to store the transcript IDs. Defaults to "transcript_id". |
'transcript_id'
|
precision |
int
|
Precision multiplier for coordinate values to handle floating point precision. Defaults to 1000. |
1000
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: DataFrame with added transcript_id column. |
Source code in src/segger/data/_utils.py
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 |
|
calculate_gene_celltype_abundance_embedding ¶
calculate_gene_celltype_abundance_embedding(adata, celltype_column)
Calculate the cell type abundance embedding for each gene based on the fraction of cells in each cell type that express the gene (non-zero expression).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
adata |
AnnData
|
An AnnData object containing gene expression data and cell type information. |
required |
celltype_column |
str
|
The column name in |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: A DataFrame where rows are genes and columns are cell types, with each value representing the fraction of cells in that cell type expressing the gene. |
Example
adata = AnnData(...) # Load your scRNA-seq AnnData object celltype_column = 'celltype_major' abundance_df = calculate_gene_celltype_abundance_embedding(adata, celltype_column) abundance_df.head()
Source code in src/segger/data/_utils.py
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 |
|
compute_nuclear_transcripts ¶
compute_nuclear_transcripts(polygons, transcripts, x_col, y_col, nuclear_column=None, nuclear_value=None)
Compute which transcripts are nuclear based on their coordinates and the nuclear polygons.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
polygons |
GeoSeries
|
The nuclear polygons. |
required |
transcripts |
DataFrame
|
The transcripts DataFrame. |
required |
x_col |
str
|
The x-coordinate column name. |
required |
y_col |
str
|
The y-coordinate column name. |
required |
nuclear_column |
str
|
The column name that indicates if a transcript is nuclear. Defaults to None. |
None
|
nuclear_value |
str
|
The value in nuclear_column that indicates a nuclear transcript. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
Series
|
pd.Series: A boolean series indicating which transcripts are nuclear. |
Source code in src/segger/data/_utils.py
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 |
|
compute_transcript_metrics ¶
compute_transcript_metrics(df, qv_threshold=30, cell_id_col='cell_id')
Computes various metrics for a given dataframe of transcript data filtered by quality value threshold.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
DataFrame
|
The dataframe containing transcript data. |
required |
qv_threshold |
float
|
The quality value threshold for filtering transcripts. |
30
|
cell_id_col |
str
|
The name of the column representing the cell ID. |
'cell_id'
|
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dict[str, Any]: A dictionary containing various transcript metrics: - 'percent_assigned' (float): The percentage of assigned transcripts. - 'percent_cytoplasmic' (float): The percentage of cytoplasmic transcripts among assigned transcripts. - 'percent_nucleus' (float): The percentage of nucleus transcripts among assigned transcripts. - 'percent_non_assigned_cytoplasmic' (float): The percentage of non-assigned cytoplasmic transcripts. - 'gene_metrics' (pd.DataFrame): A dataframe containing gene-level metrics. |
Source code in src/segger/data/_utils.py
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 |
|
create_anndata ¶
create_anndata(df, panel_df=None, min_transcripts=5, cell_id_col='cell_id', qv_threshold=30, min_cell_area=10.0, max_cell_area=1000.0)
Generates an AnnData object from a dataframe of segmented transcriptomics data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
DataFrame
|
The dataframe containing segmented transcriptomics data. |
required |
panel_df |
Optional[DataFrame]
|
The dataframe containing panel information. |
None
|
min_transcripts |
int
|
The minimum number of transcripts required for a cell to be included. |
5
|
cell_id_col |
str
|
The column name representing the cell ID in the input dataframe. |
'cell_id'
|
qv_threshold |
float
|
The quality value threshold for filtering transcripts. |
30
|
min_cell_area |
float
|
The minimum cell area to include a cell. |
10.0
|
max_cell_area |
float
|
The maximum cell area to include a cell. |
1000.0
|
Returns:
Type | Description |
---|---|
AnnData
|
ad.AnnData: The generated AnnData object containing the transcriptomics data and metadata. |
Source code in src/segger/data/_utils.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 |
|
ensure_transcript_ids ¶
ensure_transcript_ids(parquet_path, x_col, y_col, id_col='transcript_id', precision=1000)
Ensure that a parquet file has transcript IDs by adding them if missing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parquet_path |
PathLike
|
Path to the parquet file. |
required |
x_col |
str
|
Name of the x-coordinate column. |
required |
y_col |
str
|
Name of the y-coordinate column. |
required |
id_col |
str
|
Name of the column to store the transcript IDs. Defaults to "transcript_id". |
'transcript_id'
|
precision |
int
|
Precision multiplier for coordinate values to handle floating point precision. Defaults to 1000. |
1000
|
Source code in src/segger/data/_utils.py
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 |
|
filter_boundaries ¶
filter_boundaries(boundaries, inset, outset, x, y, label)
Filter boundary polygons based on their overlap with specified inset and outset regions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
boundaries |
DataFrame
|
A DataFrame containing the boundary data with x and y coordinates and identifiers. |
required |
inset |
Polygon
|
A polygon representing the inner region to filter the boundaries. |
required |
outset |
Polygon
|
A polygon representing the outer region to filter the boundaries. |
required |
x |
str
|
The name of the column representing the x-coordinate. |
required |
y |
str
|
The name of the column representing the y-coordinate. |
required |
label |
str
|
The name of the column representing the cell or nucleus label. |
required |
Returns:
Type | Description |
---|---|
pd.DataFrame: A DataFrame containing the filtered boundary polygons. |
Note
The function determines overlaps of boundary polygons with the specified inset and outset regions. It creates boolean masks for overlaps with the top, left, right, and bottom sides of the outset region, as well as the center region defined by the inset polygon. The filtering logic includes polygons that: - Are completely within the center region. - Overlap with the center and the left side, but not the bottom side. - Overlap with the center and the top side, but not the right side.
Source code in src/segger/data/_utils.py
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 |
|
filter_transcripts ¶
filter_transcripts(transcripts_df, label=None, filter_substrings=None, qv_column=None, min_qv=None)
Filter transcripts based on quality value and remove unwanted transcripts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
transcripts_df |
DataFrame
|
The dataframe containing transcript data. |
required |
label |
Optional[str]
|
The label of transcript features. Defaults to None. |
None
|
filter_substrings |
Optional[List[str]]
|
The list of feature substrings to remove. Defaults to None. |
None
|
qv_column |
Optional[str]
|
The name of the column representing the quality value. Defaults to None. |
None
|
min_qv |
Optional[float]
|
The minimum quality value threshold for filtering transcripts. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: The filtered dataframe. |
Source code in src/segger/data/_utils.py
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 |
|
find_markers ¶
find_markers(adata, cell_type_column, pos_percentile=5, neg_percentile=10, percentage=50)
Identify positive and negative marker genes for each cell type in an AnnData object.
Positive markers are top-ranked genes that are expressed in at least
percentage
percent of cells in the given cell type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
adata |
AnnData
|
Annotated data object containing gene expression data and cell type annotations. |
required |
cell_type_column |
str
|
Name of the column in |
required |
pos_percentile |
float
|
Percentile threshold for selecting top highly expressed genes as positive markers. Defaults to 5. |
5
|
neg_percentile |
float
|
Percentile threshold for selecting lowest expressed genes as negative markers. Defaults to 10. |
10
|
percentage |
float
|
Minimum percent of cells (0-100) in a cell type expressing a gene for it to be a marker. Defaults to 50. |
50
|
Returns:
Name | Type | Description |
---|---|---|
dict |
Dict[str, Dict[str, List[str]]]
|
Dictionary mapping cell type names to: { 'positive': [list of positive marker gene names], 'negative': [list of negative marker gene names] } |
Source code in src/segger/data/_utils.py
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
|
find_mutually_exclusive_genes ¶
find_mutually_exclusive_genes(adata, markers, cell_type_column)
Identify mutually exclusive genes based on expression criteria.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
adata |
AnnData
|
Annotated data object containing gene expression data. |
required |
markers |
Dict[str, Dict[str, List[str]]]
|
Dictionary where keys are cell types and values are dictionaries containing: 'positive': list of top x% highly expressed genes 'negative': list of top x% lowly expressed genes. |
required |
cell_type_column |
str
|
Column name in |
required |
Returns:
Name | Type | Description |
---|---|---|
list |
List[Tuple[str, str]]
|
List of mutually exclusive gene pairs. |
Source code in src/segger/data/_utils.py
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 |
|
format_time ¶
format_time(elapsed)
Format elapsed time to hs.
Parameters:¶
elapsed : float Elapsed time in seconds.
Returns:¶
str
Formatted time in hs.
Source code in src/segger/data/_utils.py
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 |
|
get_edge_index ¶
get_edge_index(coords_1, coords_2, k=5, dist=10, method='kd_tree', workers=1)
Computes edge indices using KD-Tree.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
coords_1 |
ndarray
|
First set of coordinates. |
required |
coords_2 |
ndarray
|
Second set of coordinates. |
required |
k |
int
|
Number of nearest neighbors. |
5
|
dist |
int
|
Distance threshold. |
10
|
method |
str
|
The method to use. Only 'kd_tree' is supported now. |
'kd_tree'
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: Edge indices. |
Source code in src/segger/data/_utils.py
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 |
|
get_edge_index_kdtree ¶
get_edge_index_kdtree(coords_1, coords_2, k=5, dist=10, workers=1)
Computes edge indices using KDTree.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
coords_1 |
ndarray
|
First set of coordinates. |
required |
coords_2 |
ndarray
|
Second set of coordinates. |
required |
k |
int
|
Number of nearest neighbors. |
5
|
dist |
int
|
Distance threshold. |
10
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: Edge indices. |
Source code in src/segger/data/_utils.py
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 |
|
get_polygons_from_xy ¶
get_polygons_from_xy(boundaries, x, y, label, scale_factor=1.0)
Convert boundary coordinates from a DataFrame to a GeoSeries of polygons.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
boundaries |
DataFrame
|
A DataFrame containing the boundary data with x and y coordinates and identifiers. |
required |
x |
str
|
The name of the column representing the x-coordinate. |
required |
y |
str
|
The name of the column representing the y-coordinate. |
required |
label |
str
|
The name of the column representing the cell or nucleus label. |
required |
scale_factor |
float
|
A ratio to scale the polygons. A value of 1.0 means no change, greater than 1.0 expands the polygons, and less than 1.0 shrinks the polygons. Defaults to 1.0. |
1.0
|
Returns:
Type | Description |
---|---|
GeoSeries
|
gpd.GeoSeries: A GeoSeries containing the polygons created from the boundary coordinates. |
Source code in src/segger/data/_utils.py
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 |
|
get_xy_extents ¶
get_xy_extents(filepath, x, y)
Get the bounding box of the x and y coordinates from a Parquet file.
Parameters¶
filepath : str The path to the Parquet file. x : str The name of the column representing the x-coordinate. y : str The name of the column representing the y-coordinate.
Returns¶
shapely.Polygon A polygon representing the bounding box of the x and y coordinates.
Source code in src/segger/data/_utils.py
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 |
|
load_settings ¶
load_settings(sample_type)
Load a matching YAML file from the _settings/ directory and convert its contents into a SimpleNamespace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_type |
str
|
Name of the sample type to load (case-insensitive). |
required |
Returns:
Name | Type | Description |
---|---|---|
SimpleNamespace |
SimpleNamespace
|
The settings loaded from the YAML file as a SimpleNamespace. |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If |
Source code in src/segger/data/_utils.py
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 |
|
read_parquet_region ¶
read_parquet_region(filepath, x, y, bounds=None, extra_columns=[], extra_filters=[], row_group_chunksize=None)
Read a region from a Parquet file based on x and y coordinates and optional filters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath |
The path to the Parquet file. |
required | |
x |
str
|
The name of the column representing the x-coordinate. |
required |
y |
str
|
The name of the column representing the y-coordinate. |
required |
bounds |
Polygon
|
A polygon representing the bounding box to filter the data. If None, no bounding box filter is applied. Defaults to None. |
None
|
extra_columns |
list[str]
|
A list of additional columns to include in the output DataFrame. Defaults to []. |
[]
|
extra_filters |
list[str]
|
A list of additional filters to apply to the data. Defaults to []. |
[]
|
row_group_chunksize |
Optional[int]
|
Chunk size for row group processing. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
pd.DataFrame: A DataFrame containing the filtered data from the Parquet file. |
Source code in src/segger/data/_utils.py
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 |
|