Utilities
Utility functions for scpviz.
This module provides a collection of helper and processing functions used throughout the scpviz package. They fall into four main categories:
Text Utility Functions
Functions:
| Name | Description |
|---|---|
format_log_prefix |
Return standardized log prefixes for messages. |
format_class_filter |
Standardize class/value inputs for filtering. |
Data Processing Functions
Functions:
| Name | Description |
|---|---|
get_samplenames |
Resolve sample names for given classes from |
get_classlist |
Return unique class values for specified |
get_adata_layer |
Safely extract data from |
get_adata |
Retrieve |
get_abundance |
Wrapper to extract abundance data from pAnnData or AnnData. |
resolve_accessions |
Map gene names or accessions to |
get_upset_contents |
Build contents for UpSet plots from pAnnData. |
get_upset_query |
Query features present/absent in UpSet contents. |
filter |
Legacy sample filtering (use |
resolve_class_filter |
Resolve class/value pairs and apply filtering. |
get_pep_prot_mapping |
Determine peptide-to-protein mapping column. |
API Functions
Functions:
| Name | Description |
|---|---|
get_uniprot_fields_worker |
Low-level UniProt REST API query function (batch up to 1024). |
get_uniprot_fields |
High-level UniProt API wrapper with batching. |
Statistical Test Functions
Functions:
| Name | Description |
|---|---|
pairwise_log2fc |
Compute pairwise median log2 fold change between groups. |
get_pca_importance |
Identify most important features for PCA components. |
get_protein_clusters |
Retrieve hierarchical clusters from stored linkage. |
Warning
Many of the functions in this module are internal helpers and not
intended for direct end-user use. For filtering and abundance queries,
prefer the corresponding pAnnData methods.
Example
To use this module, import it and call functions from your code as follows:
Todo
- Add corrections for differential expression.
- Add more examples for each function.
convert_identifiers
convert_identifiers(ids, from_type: str, to_type, pdata=None, use_cache: bool = True, return_type: str = 'dict', verbose: bool = True)
Convert identifiers between UniProt-compatible types.
Supports mapping between protein accessions, gene names, STRING IDs, and organism IDs. Multiple output types may be requested at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ids |
list of str
|
Input identifiers. |
required |
from_type |
str
|
Source identifier type ('accession', 'gene'). 'organism_id' cannot be used as a source. |
required |
to_type |
str or list of str
|
Target identifier type(s). May include any of: ['gene', 'string', 'organism_id']. |
required |
pdata |
pAnnData
|
pAnnData object providing cached
accession–gene mappings. If provided, |
None
|
use_cache |
bool
|
Whether to use cached mappings from |
True
|
return_type |
str
|
Output format: - 'dict': {input → {to_type → value}} - 'df': DataFrame with columns [from_type, *to_type] - 'both': (dict, DataFrame) |
'dict'
|
verbose |
bool
|
Whether to print progress messages. |
True
|
Returns:
| Type | Description |
|---|---|
|
dict, pandas.DataFrame, or tuple: Depending on |
Example
convert_identifiers(["P12345", "Q9XYZ1"], "accession", "gene", pdata=pdata) convert_identifiers(["P12345"], "accession", ["gene", "string", "organism_id"], return_type="df")
Source code in src/scpviz/utils.py
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 | |
de_adata
de_adata(adata, values=None, class_type=None, method='ttest', fold_change_mode='mean', layer='X', pval=0.05, log2fc=1.0, data_is_log=False, log_base=2.0, pseudocount=1.0, gene_col=None)
Standalone DE analysis for AnnData. Produces a volcano-ready DataFrame identical to pdata.de().
Supports
- Legacy-style: class_type="condition", values=["A","B"]
- Legacy multi-col: class_type=["cellline","treatment"], values=[["HCT116","DMSO"], ["HCT116","Drug"]]
- Dictionary-style: values=[{"cellline":"HCT116","treatment":"DMSO"}, {...}]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata |
AnnData
|
AnnData object. |
required |
values |
list of dict or list of list
|
Sample group filters to compare.
|
None
|
class_type |
str or list of str
|
Legacy-style class label(s) to interpret |
None
|
method |
str
|
'ttest', 'mannwhitneyu', 'wilcoxon'. |
'ttest'
|
fold_change_mode |
str
|
'mean' or 'pairwise_median'. |
'mean'
|
layer |
str
|
Layer to use. Default is 'X'. |
'X'
|
pval_thresh |
float
|
p-value threshold. |
required |
log2fc_thresh |
float
|
log2 fold change threshold. |
required |
data_is_log |
bool
|
If True, treat |
False
|
log_base |
float
|
Base of the log used in |
2.0
|
pseudocount |
float
|
If data is log of (x + pseudocount), provide that here (e.g., 1.0 for log2(x+1)). |
1.0
|
gene_col |
str
|
Column in |
None
|
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: DE results with volcano-ready columns. |
Source code in src/scpviz/utils.py
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 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 1181 1182 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 1277 1278 1279 | |
filter
Legacy-style filtering of samples in pAnnData or AnnData objects.
This function filters samples based on metadata values using the older
(class_type, values) interface. For pAnnData objects, it automatically
delegates to .filter_sample_values() after converting the input into the
recommended dictionary-style format.
Warning
For pAnnData users, prefer .filter_sample_values() with dictionary-style
input, as it is more flexible and consistent. The filter() utility is
retained primarily for backward compatibility and direct AnnData usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdata |
pAnnData or AnnData
|
Input data object to filter. |
required |
class_type |
str or list of str
|
Metadata field(s) in |
required |
values |
list, dict, or list of dict
|
Metadata values to match.
- If |
required |
exact_cases |
bool
|
Whether to interpret |
False
|
debug |
bool
|
If True, print the query string used for filtering. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
filtered |
pAnnData or AnnData
|
A filtered object of the same type as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If input types are invalid, if fields are missing in |
Example
Filter samples by a single metadata field:
Filter by multiple fields with OR logic:
samples = utils.filter(
adata,
class_type=["cell_type", "treatment"],
values=[["wt", "kd"], ["control", "treatment"]]
)
# returns samples where cell_type is either 'wt' or 'kd' and treatment is either 'control' or 'treatment'
Filter by exact case combinations:
samples = utils.filter(
adata,
class_type=["cell_type", "treatment"],
values=[{"cell_type": "wt", "treatment": "control"},
{"cell_type": "kd", "treatment": "treatment"}],
exact_cases=True
)
# returns samples where cell_type is 'wt' and treatment is 'kd', or cell_type is 'control' and treatment is 'treatment'
Source code in src/scpviz/utils.py
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 | |
format_class_filter
Convert legacy-style filter input into dictionary-style format.
This function standardizes (classes, class_value) input into the dictionary
format expected by pAnnData.filter_sample_values(). It supports both loose
OR-style filtering and exact case matching across multiple metadata fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
classes |
str or list of str
|
Metadata field(s) to filter on.
Example: |
required |
class_value |
str, list of str, or list of list
|
Values to filter by.
- str: May be underscore-joined (e.g. |
required |
exact_cases |
bool
|
If True, return a list of dictionaries representing exact combinations across fields. If False, return a dictionary with OR logic applied. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
formatted |
dict or list of dict
|
Dictionary-style filter input compatible |
|
with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If input shapes are inconsistent with the number of classes,
or if |
Example
Single class with OR logic:
Multiple classes with loose matching:
Multiple classes with exact cases (underscore-joined strings):
Multiple classes with exact cases (list of lists):
Note
This function is primarily used internally by utils.filter() and
pAnnData.filter_sample_values(). End users should generally call
.filter_sample_values() directly on pAnnData objects instead of
using this helper.
Source code in src/scpviz/utils.py
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 | |
format_log_prefix
Return a standardized log prefix with emoji and label.
This helper formats log message prefixes consistently across scpviz, with optional indentation for nested output. Used internally for user-facing messages, warnings, errors, and updates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level |
str
|
Logging level keyword. Must be one of:
|
required |
indent |
int or None
|
Indentation level override. Options:
If None, uses built-in default spacing (applied to most levels). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A formatted log prefix with emoji and label. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unknown |
Example
Format an info prefix with default spacing:
Format a warning prefix with explicit indent:
Source code in src/scpviz/utils.py
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 | |
get_abundance
Wrapper to extract abundance from either pAnnData or AnnData.
This is a convenience wrapper that dispatches to the appropriate method:
- If pdata is a pAnnData object, it calls pdata.get_abundance().
- If pdata is an AnnData object, it falls back to the internal
helper _get_abundance_from_adata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdata |
pAnnData or AnnData
|
Input object to extract abundance from. |
required |
*args |
Positional arguments forwarded to |
()
|
|
**kwargs |
Keyword arguments forwarded to |
{}
|
Note
See pAnnData.get_abundance for full parameter documentation. Briefly,
- namelist (list of str, optional): List of accessions or gene names to extract.
- layer (str): Data layer name (default = "X").
- on (str): "protein" or "peptide".
- classes (str or list of str, optional): Sample-level `.obs` column(s) to include.
- log (bool): If True, applies log2 transform to abundance values.
- x_label (str): Label features by "gene" or "accession".
Returns:
| Name | Type | Description |
|---|---|---|
df |
DataFrame
|
Long-form abundance DataFrame, optionally with |
|
sample metadata and protein/peptide annotations. |
See Also
- :func:
pAnnData.get_abundance(EditingMixin): Full-featured version with detailed docs. - get_adata_layer: Helper to access abundance matrices from AnnData layers.
Source code in src/scpviz/utils.py
get_adata
Retrieve the protein- or peptide-level AnnData object from a pAnnData container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdata |
pAnnData
|
The parent pAnnData object containing both protein- and peptide-level data. |
required |
on |
str
|
Which data object to return. |
'protein'
|
Returns:
| Name | Type | Description |
|---|---|---|
adata |
AnnData
|
The requested AnnData object. |
Source code in src/scpviz/utils.py
get_adata_layer
Safely extract layer data as dense numpy array.
This helper returns the requested layer as a dense numpy.ndarray,
ensuring compatibility for downstream operations. Supports both
.X and .layers[...].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata |
AnnData
|
AnnData object containing data matrices. |
required |
layer |
str
|
Layer key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
data |
ndarray
|
Dense matrix representation of the requested layer. |
Source code in src/scpviz/utils.py
get_classlist
Retrieve unique class values for specified metadata columns. Useful for plot legends.
Unlike get_samplenames, which returns one identifier per row/sample,
this function extracts the set of unique class values for grouping
purposes (e.g., plotting categories). Supports optional reordering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata |
AnnData
|
AnnData object containing sample metadata. |
required |
classes |
str or list of str
|
Column(s) in
|
None
|
order |
list of str
|
Custom order of categories. Must exactly
match the unique values; otherwise, a |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
class_list |
list of str
|
Unique class values in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If invalid columns are provided, or if |
Example
Get unique values from one metadata column:
Combine two columns and return unique class labels:
Reorder categories explicitly:
Source code in src/scpviz/utils.py
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | |
get_pca_importance
get_pca_importance(model: Union[dict, sklearn.decomposition.PCA], initial_feature_names: List[str], n: int = 1) -> pd.DataFrame
Identify the most important features for each principal component.
This function ranks features by their absolute PCA loading values and extracts the top contributors for each principal component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
PCA or dict
|
Either a fitted PCA model
from scikit-learn, or a dictionary with key |
required |
initial_feature_names |
list of str
|
Names of the features, typically
|
required |
n |
int
|
Number of top features to return per principal component (default = 1). |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
df |
DataFrame
|
DataFrame with one row per principal component, |
DataFrame
|
listing the top contributing features. |
Example
Retrieve the top 5 features contributing to each PC:
Source code in src/scpviz/utils.py
get_pep_prot_mapping
Retrieve the peptide-to-protein mapping column or mapping values.
This function resolves the appropriate .pep.var column for peptide-to-protein
mapping based on the data source recorded in pdata.metadata["source"].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdata |
pAnnData
|
The annotated proteomics object containing |
required |
return_series |
bool
|
If True, return a pandas Series of peptide-to-protein mappings. If False (default), return the column name as a string. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
col |
str
|
Column name in |
|
if |
||
mapping |
Series
|
Series mapping peptides to proteins, |
|
if |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the data source is unrecognized or no valid mapping column is found. |
Note
The mapping column depends on the import source:
- Proteome Discoverer →
"Master Protein Accessions" - DIA-NN →
"Protein.Group" - MaxQuant →
"Leading razor protein"
Source code in src/scpviz/utils.py
get_protein_clusters
Retrieve hierarchical clusters of proteins from stored linkage.
This function uses linkage information stored in pdata.stats to
partition proteins into clusters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdata |
pAnnData
|
Input object containing |
required |
on |
str
|
Data level to use, |
'prot'
|
layer |
str
|
Data layer name used when the linkage was computed (default = |
'X'
|
t |
int or float
|
Number of clusters (if |
5
|
criterion |
str
|
Clustering criterion passed to |
'maxclust'
|
Returns:
| Name | Type | Description |
|---|---|---|
clusters |
dict
|
Mapping of |
None |
If no linkage is found in |
Note
Requires that a clustermap has been previously computed and linkage
stored under pdata.stats[f"{on}_{layer}_clustermap"].
Source code in src/scpviz/utils.py
get_samplenames
Retrieve sample names for specified class values.
This function resolves .obs metadata into sample-level identifiers
(one name per row). It is typically used for plotting functions where
sample names are required for labeling or grouping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata |
AnnData
|
AnnData object containing sample metadata. |
required |
classes |
str or list of str
|
Column(s) in
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
sample_names |
list of str
|
Sample names dervied from |
Example
Get sample names from a single metadata column:
Combine multiple columns into sample identifiers:
Source code in src/scpviz/utils.py
get_string_mappings
get_string_mappings(identifiers, use_uniprot=True, use_string=True, caller_identity='scpviz', batch_size=100, debug=False)
Resolve STRING identifiers for a list of UniProt accessions.
This function maps UniProt protein accessions to STRING IDs using a two-step strategy:
- UniProt lookup – retrieves STRING cross-references (
xref_string) and organism IDs via the UniProt API (fast). - STRING API lookup – queries the STRING
get_string_idsendpoint for any identifiers not resolved via UniProt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifiers |
list of str
|
List of UniProt accession IDs to map. |
required |
use_uniprot |
bool
|
If True (default), attempt mapping via UniProt
|
True
|
use_string |
bool
|
If True (default), query the STRING API for any identifiers still unresolved after the UniProt step. |
True
|
caller_identity |
str
|
Identifier passed to the STRING API (default: "scpviz"). |
'scpviz'
|
batch_size |
int
|
Number of identifiers per batch when querying external APIs (default=100). |
100
|
debug |
bool
|
If True, print progress and debug information. |
False
|
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: Mapping table with one row per input identifier and |
|
|
the following columns: |
|
|
|
|
|
|
Example
Map a small set of UniProt accessions to STRING IDs:
Disable the UniProt shortcut and query STRING directly (takes longer than UniProt):
Source code in src/scpviz/utils.py
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 | |
get_uniprot_fields
get_uniprot_fields(prot_list, search_fields=['accession', 'id', 'protein_name', 'gene_primary', 'gene_names', 'organism_id', 'go', 'go_f', 'go_c', 'go_p', 'cc_interaction', 'xref_string'], batch_size=100, verbose=True, standardize=True, worker_verbose=False)
Retrieve UniProt metadata for a list of protein accessions.
This function wraps get_uniprot_fields_worker to handle batching of
protein IDs, returning results as a single DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prot_list |
list of str
|
List of protein accessions. |
required |
search_fields |
list of str
|
UniProt fields to return. Defaults include accession, gene names, GO terms, and STRING IDs. |
['accession', 'id', 'protein_name', 'gene_primary', 'gene_names', 'organism_id', 'go', 'go_f', 'go_c', 'go_p', 'cc_interaction', 'xref_string']
|
batch_size |
int
|
Number of accessions per batch (max 1024, default=100). |
100
|
verbose |
bool
|
If True, print progress messages. |
True
|
standardize |
bool
|
If True (default), normalize UniProt column names to canonical lowercase keys (e.g., "gene_primary", "organism_id", "xref_string") for consistent downstream processing. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
df |
DataFrame
|
DataFrame containing UniProt metadata for the input proteins. |
Example
Query UniProt for a small set of proteins:
proteins = ["P40925", "P40926"]
df = get_uniprot_fields(proteins)
df[["Entry", "Gene Names", "Organism Id"]].head()
Retrieve raw UniProt field names without renaming: >>> df_raw = get_uniprot_fields(proteins, standardize=False)
Source code in src/scpviz/utils.py
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 | |
get_uniprot_fields_worker
Query UniProt for a batch of protein accessions.
This function sends requests to the UniProt REST API for up to 1024 proteins at a time and returns the requested fields as a DataFrame. It handles isoform accessions, fallback queries, and UniProt ID redirects automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prot_list |
list of str
|
List of protein accessions or IDs. |
required |
search_fields |
list of str
|
UniProt return fields. See: https://www.uniprot.org/help/return_fields |
None
|
verbose |
bool
|
If True, print progress messages and missing accessions. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
df |
DataFrame
|
DataFrame containing UniProt metadata for the input proteins. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Info
- This function is intended as a worker and is usually called by
get_uniprot_fields. - It automatically resolves canonical vs. isoform accessions and will attempt UniProt ID mapping if some accessions cannot be found.
Source code in src/scpviz/utils.py
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 | |
get_upset_contents
Construct contents for an UpSet plot from a pAnnData object.
This function extracts feature sets (proteins or peptides) present in
specified sample classes and returns them either as a dictionary or
in an upsetplot-compatible format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdata |
pAnnData
|
The pAnnData object containing |
required |
classes |
str or list of str
|
Metadata column(s) in |
required |
on |
str
|
Data level to use. Options are |
'protein'
|
upsetForm |
bool
|
If True, return an |
True
|
debug |
bool
|
If True, print filtering steps and class resolution details. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
upset_data |
DataFrame
|
Binary presence/absence DataFrame for use with
|
upset_dict |
dict
|
Mapping of class → list of present features,
if |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
Get contents for an UpSet plot of sample classes:
upset_data = get_upset_contents(pdata, classes="treatment")
from upsetplot import UpSet
UpSet(upset_data, subset_size="count").plot()
Retrieve raw dictionary of sets instead:
Query proteins from a set and highlight them in a plot:
upset_data = scutils.get_upset_contents(pdata, classes="condition")
prot_df = scutils.get_upset_query(upset_data, present=["treated"], absent=["control"])
scplt.plot_rankquant(ax, pdata, classes="condition", cmap=cmaps, color=colors)
scplt.mark_rankquant(ax, pdata, mark_df=prot_df, class_values=["treated"], color="black")
Source code in src/scpviz/utils.py
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 | |
get_upset_query
Query features from UpSet contents given inclusion and exclusion criteria.
This function extracts the set of features (proteins or peptides) that are present in all specified groups and absent in others. It then queries UniProt metadata for the resulting accessions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upset_content |
DataFrame
|
Output from |
required |
present |
list of str
|
List of groups in which the features must be present. |
required |
absent |
list of str
|
List of groups in which the features must be absent. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
prot_query_df |
DataFrame
|
DataFrame of features matching the query, |
|
annotated with UniProt metadata via |
Example
Query proteins unique to one group and highlight them in a plot:
upset_data = scutils.get_upset_contents(pdata, classes="condition")
prot_df = scutils.get_upset_query(upset_data, present=["treated"], absent=["control"])
scplt.plot_rankquant(ax, pdata, classes="condition", cmap=cmaps, color=colors)
scplt.mark_rankquant(ax, pdata, mark_df=prot_df, class_values=["treated"], color="black")
Source code in src/scpviz/utils.py
pairwise_log2fc
Compute pairwise median log2 fold change (log2FC) between two groups.
This function calculates all pairwise log2 ratios between features in
two groups of samples and returns the median value per feature. It is
primarily used as a helper for fold-change strategies in pAnnData.de().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data1 |
ndarray
|
Array of shape |
required |
data2 |
ndarray
|
Array of shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
median_log2fc |
ndarray
|
Array of shape |
|
the median pairwise log2 fold change for each feature. |
Note
This is an internal helper for differential expression calculations.
End users should call pAnnData.de() instead of using this function directly.
Source code in src/scpviz/utils.py
parse_filename_index
Parse DataFrame index (filenames) into metadata columns based on a list of obs_columns. Can label a subset based on condition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df |
DataFrame
|
DataFrame whose index contains delimited filenames. |
required |
obs_columns |
list of str
|
Names of the metadata columns to extract from the filename. |
required |
delimiter |
str
|
Character used to split the filename. Default is "_". |
'_'
|
condition |
str or None
|
Optional boolean expression (evaluated with df.eval) that selects a
subset of rows for parsing. If None, parse all rows. For example, |
None
|
Returns:
| Type | Description |
|---|---|
|
pd.DataFrame: Copy of df with added metadata columns. |
Source code in src/scpviz/utils.py
resolve_accessions
Resolve gene or accession names to accession IDs from .var_names.
This function maps user-specified identifiers (gene names or accession IDs)
to the canonical accession IDs in an AnnData or pAnnData object. It first
checks .var_names for exact matches, then optionally resolves gene names
via a specified column (default "Genes"). Unmatched names are reported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata |
AnnData or pAnnData
|
AnnData-like object containing |
required |
namelist |
list of str
|
Input identifiers to resolve (genes or accessions). |
required |
gene_col |
str
|
Column in |
'Genes'
|
gene_map |
dict
|
Precomputed mapping of gene → accession. If None,
a mapping is constructed from |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
resolved |
list of str
|
List of accession IDs corresponding to the input names. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If none of the provided names can be resolved to |
Example
Resolve gene symbols to accession IDs:
Resolve accessions directly:
Source code in src/scpviz/utils.py
resolve_class_filter
Resolve (classes, class_value) inputs and apply filtering.
This helper standardizes class/value pairs into dictionary-style filters and applies them to an AnnData or pAnnData object. It is primarily used internally by plotting and analysis functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata |
AnnData or pAnnData
|
Input data object to filter. |
required |
classes |
str or list of str
|
Metadata field(s) used for filtering. |
required |
class_value |
str or list of str
|
Values corresponding to |
required |
debug |
bool
|
If True, print resolved class/value pairs. |
False
|
filter_func |
callable
|
Filtering function to apply.
Defaults to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
filtered |
AnnData or pAnnData
|
Subset of the input object, same type as |
Warning
This is an internal helper for use inside functions such as
plot_rankquant and plot_raincloud. End users should call
pAnnData.filter_sample_values() instead.
Source code in src/scpviz/utils.py
scalarize_taxon
Normalize taxon-id values so they never contain lists or arrays.
Returns:
| Type | Description |
|---|---|
object
|
Scalar string-like taxon id, or pd.NA. |
Source code in src/scpviz/utils.py
standardize_uniprot_columns
Normalize UniProt DataFrame column names to a consistent lowercase, snake_case schema.
This ensures stability across UniProt REST API version changes while keeping the user informed only when critical fields are affected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df |
DataFrame
|
Raw UniProt metadata table. |
required |
Returns:
| Type | Description |
|---|---|
|
pd.DataFrame: Copy of the DataFrame with standardized column names. |
Source code in src/scpviz/utils.py
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 | |