py2ls 0.2.4.2__py3-none-any.whl → 0.2.4.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- py2ls/.DS_Store +0 -0
- py2ls/.git/index +0 -0
- py2ls/bio.py +1225 -47
- py2ls/data/mygenes_fields_241022.txt +355 -0
- py2ls/ips.py +523 -110
- py2ls/ml2ls.py +1094 -0
- py2ls/netfinder.py +12 -1
- py2ls/plot.py +290 -75
- {py2ls-0.2.4.2.dist-info → py2ls-0.2.4.4.dist-info}/METADATA +1 -1
- {py2ls-0.2.4.2.dist-info → py2ls-0.2.4.4.dist-info}/RECORD +11 -9
- {py2ls-0.2.4.2.dist-info → py2ls-0.2.4.4.dist-info}/WHEEL +0 -0
py2ls/bio.py
CHANGED
@@ -1,11 +1,20 @@
|
|
1
1
|
import GEOparse
|
2
|
+
import gseapy as gp
|
2
3
|
from typing import Union
|
3
4
|
import pandas as pd
|
5
|
+
import numpy as np
|
4
6
|
import os
|
5
7
|
import logging
|
8
|
+
|
9
|
+
from sympy import use
|
6
10
|
from . import ips
|
11
|
+
from . import plot
|
12
|
+
import matplotlib.pyplot as plt
|
13
|
+
|
7
14
|
def load_geo(
|
8
|
-
datasets: Union[list, str] = ["GSE00000", "GSE00001"],
|
15
|
+
datasets: Union[list, str] = ["GSE00000", "GSE00001"],
|
16
|
+
dir_save: str = "./datasets",
|
17
|
+
verbose=False,
|
9
18
|
) -> dict:
|
10
19
|
"""
|
11
20
|
Check if GEO datasets are already in the directory, and download them if not.
|
@@ -17,7 +26,7 @@ def load_geo(
|
|
17
26
|
Returns:
|
18
27
|
dict: A dictionary containing the GEO objects for each dataset.
|
19
28
|
"""
|
20
|
-
use_str="""
|
29
|
+
use_str = """
|
21
30
|
get_meta(geo: dict, dataset: str = "GSE25097")
|
22
31
|
get_expression_data(geo: dict, dataset: str = "GSE25097")
|
23
32
|
get_probe(geo: dict, dataset: str = "GSE25097", platform_id: str = "GPL10687")
|
@@ -51,7 +60,7 @@ def load_geo(
|
|
51
60
|
return geo_data
|
52
61
|
|
53
62
|
|
54
|
-
def get_meta(geo: dict, dataset: str = "GSE25097",verbose=True) -> pd.DataFrame:
|
63
|
+
def get_meta(geo: dict, dataset: str = "GSE25097", verbose=True) -> pd.DataFrame:
|
55
64
|
"""
|
56
65
|
df_meta = get_meta(geo, dataset="GSE25097")
|
57
66
|
Extracts metadata from a specific GEO dataset and returns it as a DataFrame.
|
@@ -118,27 +127,55 @@ def get_meta(geo: dict, dataset: str = "GSE25097",verbose=True) -> pd.DataFrame:
|
|
118
127
|
|
119
128
|
# Convert the list of dictionaries to a DataFrame
|
120
129
|
meta_df = pd.DataFrame(meta_list)
|
130
|
+
col_rm = [
|
131
|
+
"channel_count",
|
132
|
+
"contact_web_link",
|
133
|
+
"contact_address",
|
134
|
+
"contact_city",
|
135
|
+
"contact_country",
|
136
|
+
"contact_department",
|
137
|
+
"contact_email",
|
138
|
+
"contact_institute",
|
139
|
+
"contact_laboratory",
|
140
|
+
"contact_name",
|
141
|
+
"contact_phone",
|
142
|
+
"contact_state",
|
143
|
+
"contact_zip/postal_code",
|
144
|
+
"contributor",
|
145
|
+
"manufacture_protocol",
|
146
|
+
"taxid",
|
147
|
+
"web_link",
|
148
|
+
]
|
149
|
+
# rm unrelavent columns
|
150
|
+
meta_df = meta_df.drop(columns=[col for col in col_rm if col in meta_df.columns])
|
121
151
|
if verbose:
|
122
152
|
print(
|
123
153
|
f"Meta info columns for dataset '{dataset}': \n{sorted(meta_df.columns.tolist())}"
|
124
154
|
)
|
125
|
-
|
155
|
+
display(meta_df[:1].T)
|
156
|
+
return meta_df
|
157
|
+
|
126
158
|
|
127
|
-
def get_probe(
|
159
|
+
def get_probe(
|
160
|
+
geo: dict, dataset: str = "GSE25097", platform_id: str = None, verbose=True
|
161
|
+
):
|
128
162
|
"""
|
129
163
|
df_probe = get_probe(geo, dataset="GSE25097", platform_id: str = "GPL10687")
|
130
164
|
"""
|
131
165
|
# try to find the platform_id from meta
|
132
166
|
if platform_id is None:
|
133
|
-
df_meta=get_meta(geo=geo, dataset=dataset,verbose=False)
|
134
|
-
platform_id=df_meta["platform_id"].unique().tolist()
|
135
|
-
platform_id = platform_id[0] if len(platform_id)==1 else platform_id
|
136
|
-
print(platform_id)
|
167
|
+
df_meta = get_meta(geo=geo, dataset=dataset, verbose=False)
|
168
|
+
platform_id = df_meta["platform_id"].unique().tolist()
|
169
|
+
platform_id = platform_id[0] if len(platform_id) == 1 else platform_id
|
170
|
+
print(f"Platform: {platform_id}")
|
137
171
|
df_probe = geo[dataset].gpls[platform_id].table
|
138
172
|
if df_probe.empty:
|
139
|
-
print(
|
140
|
-
|
141
|
-
|
173
|
+
print(
|
174
|
+
f"Warning: cannot find the probe info. 看一下是不是在单独的文件中包含了probe信息"
|
175
|
+
)
|
176
|
+
display(f"🔗: https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc={platform_id}")
|
177
|
+
return get_meta(geo, dataset, verbose=verbose)
|
178
|
+
if verbose:
|
142
179
|
print(f"columns in the probe table: \n{sorted(df_probe.columns.tolist())}")
|
143
180
|
return df_probe
|
144
181
|
|
@@ -170,18 +207,25 @@ def get_expression_data(geo: dict, dataset: str = "GSE25097") -> pd.DataFrame:
|
|
170
207
|
return expression_values
|
171
208
|
|
172
209
|
|
173
|
-
|
174
|
-
|
210
|
+
def get_data(geo: dict, dataset: str = "GSE25097", verbose=False):
|
211
|
+
print(f"\n\ndataset: {dataset}\n")
|
175
212
|
# get probe info
|
176
|
-
df_probe = get_probe(geo,dataset=dataset,verbose=False)
|
213
|
+
df_probe = get_probe(geo, dataset=dataset, verbose=False)
|
177
214
|
# get expression values
|
178
|
-
df_expression = get_expression_data(geo, dataset=dataset
|
179
|
-
|
180
|
-
|
181
|
-
|
215
|
+
df_expression = get_expression_data(geo, dataset=dataset)
|
216
|
+
if not df_expression.select_dtypes(include=["number"]).empty:
|
217
|
+
# 如果数据全部是counts类型的话, 则使用TMM进行normalize
|
218
|
+
if 'counts' in get_data_type(df_expression):
|
219
|
+
print(f"{dataset}'s type is raw read counts, nomalized(transformed) via 'TMM'")
|
220
|
+
df_expression=counts2expression(df_expression.T).T
|
182
221
|
if any([df_probe.empty, df_expression.empty]):
|
183
|
-
print(
|
222
|
+
print(
|
223
|
+
f"got empty values, check the probe info. 看一下是不是在单独的文件中包含了probe信息"
|
224
|
+
)
|
184
225
|
return get_meta(geo, dataset, verbose=True)
|
226
|
+
print(
|
227
|
+
f"\n\tdf_expression.shape: {df_expression.shape} \n\tdf_probe.shape: {df_probe.shape}"
|
228
|
+
)
|
185
229
|
df_exp = pd.merge(
|
186
230
|
df_probe,
|
187
231
|
df_expression,
|
@@ -191,27 +235,73 @@ def get_data(geo: dict, dataset: str = "GSE25097",verbose=True):
|
|
191
235
|
)
|
192
236
|
|
193
237
|
# get meta info
|
194
|
-
df_meta=get_meta(geo, dataset=dataset,verbose=False)
|
195
|
-
col_rm=[
|
238
|
+
df_meta = get_meta(geo, dataset=dataset, verbose=False)
|
239
|
+
col_rm = [
|
240
|
+
"channel_count",
|
241
|
+
"contact_web_link",
|
242
|
+
"contact_address",
|
243
|
+
"contact_city",
|
244
|
+
"contact_country",
|
245
|
+
"contact_department",
|
246
|
+
"contact_email",
|
247
|
+
"contact_institute",
|
248
|
+
"contact_laboratory",
|
249
|
+
"contact_name",
|
250
|
+
"contact_phone",
|
251
|
+
"contact_state",
|
252
|
+
"contact_zip/postal_code",
|
253
|
+
"contributor",
|
254
|
+
"manufacture_protocol",
|
255
|
+
"taxid",
|
256
|
+
"web_link",
|
257
|
+
]
|
196
258
|
# rm unrelavent columns
|
197
259
|
df_meta = df_meta.drop(columns=[col for col in col_rm if col in df_meta.columns])
|
198
260
|
# sorte columns
|
199
|
-
df_meta = df_meta.reindex(sorted(df_meta.columns),axis=1)
|
261
|
+
df_meta = df_meta.reindex(sorted(df_meta.columns), axis=1)
|
200
262
|
# find a proper column
|
201
|
-
col_sample_id = ips.strcmp("sample_id",df_meta.columns.tolist())[0]
|
202
|
-
df_meta.set_index(col_sample_id, inplace=True)
|
203
|
-
|
204
|
-
col_gene_symbol = ips.strcmp("GeneSymbol",df_exp.columns.tolist())[0]
|
263
|
+
col_sample_id = ips.strcmp("sample_id", df_meta.columns.tolist())[0]
|
264
|
+
df_meta.set_index(col_sample_id, inplace=True) # set gene symbol as index
|
265
|
+
|
266
|
+
col_gene_symbol = ips.strcmp("GeneSymbol", df_exp.columns.tolist())[0]
|
205
267
|
# select the 'GSM' columns
|
206
268
|
col_gsm = df_exp.columns[df_exp.columns.str.startswith("GSM")].tolist()
|
207
269
|
df_exp.set_index(col_gene_symbol, inplace=True)
|
208
|
-
df_exp=df_exp[col_gsm].T
|
270
|
+
df_exp = df_exp[col_gsm].T # transpose, so that could add meta info
|
271
|
+
|
272
|
+
df_merged = ips.df_merge(df_meta, df_exp,use_index=True)
|
209
273
|
|
210
|
-
|
274
|
+
print(
|
275
|
+
f"\ndataset:'{dataset}' n_sample = {df_merged.shape[0]}, n_gene={df_exp.shape[1]}"
|
276
|
+
)
|
211
277
|
if verbose:
|
212
|
-
|
213
|
-
|
214
|
-
|
278
|
+
display(df_merged.sample(5))
|
279
|
+
return df_merged
|
280
|
+
|
281
|
+
def get_data_type(data: pd.DataFrame) -> str:
|
282
|
+
"""
|
283
|
+
Determine the type of data: 'read counts' or 'normalized expression data'.
|
284
|
+
usage:
|
285
|
+
get_data_type(df_counts)
|
286
|
+
"""
|
287
|
+
numeric_data = data.select_dtypes(include=["number"])
|
288
|
+
if numeric_data.empty:
|
289
|
+
raise ValueError(f"找不到数字格式的数据, 请先进行转换")
|
290
|
+
# Check if the data contains only integers
|
291
|
+
if numeric_data.apply(lambda x: x.dtype == "int").all():
|
292
|
+
# Check for values typically found in raw read counts (large integers)
|
293
|
+
if numeric_data.max().max() > 10000: # Threshold for raw counts
|
294
|
+
return "read counts"
|
295
|
+
# Check if all values are floats
|
296
|
+
if numeric_data.apply(lambda x: x.dtype == "float").all():
|
297
|
+
# If values are small, it's likely normalized data
|
298
|
+
if numeric_data.max().max() < 1000: # Threshold for normalized expression
|
299
|
+
return "normalized expression data"
|
300
|
+
else:
|
301
|
+
print(f"the max value: {numeric_data.max().max()}, it could be a raw read counts data. but needs you to double check it")
|
302
|
+
return "read counts"
|
303
|
+
# If mixed data types or unexpected values
|
304
|
+
return "mixed or unknown"
|
215
305
|
|
216
306
|
def split_at_lower_upper(lst):
|
217
307
|
"""
|
@@ -228,16 +318,24 @@ def split_at_lower_upper(lst):
|
|
228
318
|
return lst[: i + 1], lst[i + 1 :]
|
229
319
|
return lst, []
|
230
320
|
|
231
|
-
def
|
321
|
+
def find_condition(data:pd.DataFrame, columns=["characteristics_ch1","title"]):
|
322
|
+
if data.shape[1]>=data.shape[0]:
|
323
|
+
display(data.iloc[:1,:40].T)
|
324
|
+
# 详细看看每个信息的有哪些类, 其中有数字的, 要去除
|
325
|
+
for col in columns:
|
326
|
+
print(f"{"="*10} {col} {"="*10}")
|
327
|
+
display(ips.flatten([ips.ssplit(i, by="numer")[0] for i in data[col]]))
|
328
|
+
|
329
|
+
def add_condition(
|
232
330
|
data: pd.DataFrame,
|
233
|
-
column:str="characteristics_ch1"
|
234
|
-
column_new:str="condition"
|
235
|
-
by:str="tissue: tumor liver"
|
236
|
-
by_not:str=": tumor", # 健康的选择条件
|
237
|
-
by_name:str="non-tumor", # 健康的命名
|
238
|
-
by_not_name:str="tumor", # 不健康的命名
|
239
|
-
inplace: bool = True,
|
240
|
-
verbose:bool = True
|
331
|
+
column: str = "characteristics_ch1", # 在哪一行进行分类
|
332
|
+
column_new: str = "condition", # 新col的命名
|
333
|
+
by: str = "tissue: tumor liver", # 通过by来命名
|
334
|
+
by_not: str = ": tumor", # 健康的选择条件
|
335
|
+
by_name: str = "non-tumor", # 健康的命名
|
336
|
+
by_not_name: str = "tumor", # 不健康的命名
|
337
|
+
inplace: bool = True, # replace the data
|
338
|
+
verbose: bool = True,
|
241
339
|
):
|
242
340
|
"""
|
243
341
|
Add a new column to the DataFrame based on the presence of a specific substring in another column.
|
@@ -255,18 +353,1098 @@ def get_condition(
|
|
255
353
|
|
256
354
|
"""
|
257
355
|
# first check the content in column
|
258
|
-
content=data[column].unique().tolist()
|
356
|
+
content = data[column].unique().tolist()
|
259
357
|
if verbose:
|
260
|
-
if len(content)>10:
|
358
|
+
if len(content) > 10:
|
261
359
|
display(content[:10])
|
262
360
|
else:
|
263
361
|
display(content)
|
264
362
|
# 优先by
|
265
363
|
if by:
|
266
|
-
data[column_new] = data[column].apply(
|
364
|
+
data[column_new] = data[column].apply(
|
365
|
+
lambda x: by_name if by in x else by_not_name
|
366
|
+
)
|
267
367
|
elif by_not:
|
268
|
-
data[column_new] = data[column].apply(
|
368
|
+
data[column_new] = data[column].apply(
|
369
|
+
lambda x: by_not_name if not by_not in x else by_name
|
370
|
+
)
|
371
|
+
if verbose:
|
372
|
+
display(data.sample(5))
|
373
|
+
if not inplace:
|
374
|
+
return data
|
375
|
+
|
376
|
+
|
377
|
+
def add_condition_multi(
|
378
|
+
data: pd.DataFrame,
|
379
|
+
column: str = "characteristics_ch1", # Column to classify
|
380
|
+
column_new: str = "condition", # New column name
|
381
|
+
conditions: dict = {
|
382
|
+
"low": "low",
|
383
|
+
"high": "high",
|
384
|
+
"intermediate": "intermediate",
|
385
|
+
}, # A dictionary where keys are substrings and values are condition names
|
386
|
+
default_name: str = "unknown", # Default name if no condition matches
|
387
|
+
inplace: bool = True, # Whether to replace the data
|
388
|
+
verbose: bool = True,
|
389
|
+
):
|
390
|
+
"""
|
391
|
+
Add a new column to the DataFrame based on the presence of specific substrings in another column.
|
392
|
+
|
393
|
+
Parameters
|
394
|
+
----------
|
395
|
+
data : pd.DataFrame
|
396
|
+
The input DataFrame containing the data.
|
397
|
+
column : str, optional
|
398
|
+
The name of the column in which to search for the substrings (default is 'characteristics_ch1').
|
399
|
+
column_new : str, optional
|
400
|
+
The name of the new column to be created (default is 'condition').
|
401
|
+
conditions : dict, optional
|
402
|
+
A dictionary where keys are substrings to search for and values are the corresponding labels.
|
403
|
+
default_name : str, optional
|
404
|
+
The name to assign if no condition matches (default is 'unknown').
|
405
|
+
inplace : bool, optional
|
406
|
+
Whether to modify the original DataFrame (default is True).
|
407
|
+
verbose : bool, optional
|
408
|
+
Whether to display the unique values and final DataFrame (default is True).
|
409
|
+
"""
|
410
|
+
|
411
|
+
# Display the unique values in the column
|
412
|
+
content = data[column].unique().tolist()
|
413
|
+
if verbose:
|
414
|
+
if len(content) > 10:
|
415
|
+
display(content[:10])
|
416
|
+
else:
|
417
|
+
display(content)
|
418
|
+
|
419
|
+
# Check if conditions are provided
|
420
|
+
if conditions is None:
|
421
|
+
raise ValueError(
|
422
|
+
"Conditions must be provided as a dictionary with substrings and corresponding labels."
|
423
|
+
)
|
424
|
+
|
425
|
+
# Define a helper function to map the conditions
|
426
|
+
def map_condition(value):
|
427
|
+
for substring, label in conditions.items():
|
428
|
+
if substring in value:
|
429
|
+
return label
|
430
|
+
return default_name # If no condition matches, return the default name
|
431
|
+
|
432
|
+
# Apply the mapping function to create the new column
|
433
|
+
data[column_new] = data[column].apply(map_condition)
|
434
|
+
|
435
|
+
# Display the updated DataFrame if verbose is True
|
269
436
|
if verbose:
|
270
|
-
display(data)
|
437
|
+
display(data.sample(5))
|
438
|
+
|
271
439
|
if not inplace:
|
272
|
-
return data
|
440
|
+
return data
|
441
|
+
|
442
|
+
def clean_dataset(
|
443
|
+
data: pd.DataFrame, dataset: str = None, condition: str = "condition",sep="///"
|
444
|
+
):
|
445
|
+
"""
|
446
|
+
#* it has been involved in bio.batch_effects(), but default: False
|
447
|
+
1. clean data set and prepare super_datasets
|
448
|
+
2. if "///" in index, then extend it, or others.
|
449
|
+
3. drop duplicates and dropna()
|
450
|
+
4. add the 'condition' and 'dataset info' to the columns
|
451
|
+
5. set genes as index
|
452
|
+
"""
|
453
|
+
usage_str="""clean_dataset(data: pd.DataFrame, dataset: str = None, condition: str = "condition",sep="///")
|
454
|
+
"""
|
455
|
+
if dataset is None:
|
456
|
+
try:
|
457
|
+
dataset=data["dataset"][0]
|
458
|
+
except:
|
459
|
+
print("cannot find 'dataset' name")
|
460
|
+
print(f"example\n {usage_str}")
|
461
|
+
#! (4.1) clean data set and prepare super_datasets
|
462
|
+
# df_data_2, 左边的列是meta,右边的列是gene_symbol
|
463
|
+
col_gene = split_at_lower_upper(data.columns.tolist())[1][0]
|
464
|
+
idx = ips.strcmp(col_gene, data.columns.tolist())[1]
|
465
|
+
df_gene = data.iloc[:, idx:].T # keep the last 'condition'
|
466
|
+
|
467
|
+
#! if "///" in index, then extend it, or others.
|
468
|
+
print(f"before extend shape: {df_gene.shape}")
|
469
|
+
df = df_gene.reset_index()
|
470
|
+
df_gene = ips.df_extend(df, column="index", sep=sep)
|
471
|
+
# reset 'index' column as index
|
472
|
+
# df_gene = df_gene.set_index("index")
|
473
|
+
print(f"after extended by '{sep}' shape: {df_gene.shape}")
|
474
|
+
|
475
|
+
# *alternative:
|
476
|
+
# df_unique = df.reset_index().drop_duplicates(subset="index").set_index("index")
|
477
|
+
#! 4.2 drop duplicates and dropna()
|
478
|
+
df_gene = df_gene.drop_duplicates(subset=["index"]).dropna()
|
479
|
+
print(f"drop duplicates and dropna: shape: {df_gene.shape}")
|
480
|
+
|
481
|
+
#! add the 'condition' and 'dataset info' to the columns
|
482
|
+
ds = [data["dataset"][0]] * len(df_gene.columns[1:])
|
483
|
+
samp = df_gene.columns.tolist()[1:]
|
484
|
+
cond = df_gene[df_gene["index"] == condition].values.tolist()[0][1:]
|
485
|
+
df_gene.columns = ["index"] + [
|
486
|
+
f"{ds}_{sam}_{cond}" for (ds, sam, cond) in zip(ds, samp, cond)
|
487
|
+
]
|
488
|
+
df_gene.drop(df_gene[df_gene["index"] == condition].index, inplace=True)
|
489
|
+
#! set genes as index
|
490
|
+
df_gene.set_index("index",inplace=True)
|
491
|
+
display(df_gene.head())
|
492
|
+
return df_gene
|
493
|
+
|
494
|
+
def batch_effect(
|
495
|
+
data: list = "[df_gene_1, df_gene_2, df_gene_3]", # index (genes),columns(samples)
|
496
|
+
datasets: list = ["GSE25097", "GSE62232", "GSE65372"],
|
497
|
+
clean_data:bool=False, # default, not do data cleaning
|
498
|
+
top_genes:int=10,# only for plotting
|
499
|
+
plot_=True,
|
500
|
+
dir_save="./res/",
|
501
|
+
kws_clean_dataset:dict={},
|
502
|
+
**kwargs
|
503
|
+
):
|
504
|
+
"""
|
505
|
+
usage 1:
|
506
|
+
bio.batch_effect(
|
507
|
+
data=[df_gene_1, df_gene_2, df_gene_3],
|
508
|
+
datasets=["GSE25097", "GSE62232", "GSE65372"],
|
509
|
+
clean_data=False,
|
510
|
+
dir_save="./res/")
|
511
|
+
|
512
|
+
#! # or conbine clean_dataset and batch_effect together
|
513
|
+
# # data = [bio.clean_dataset(data=dt, dataset=ds) for (dt, ds) in zip(data, datasets)]
|
514
|
+
data_common = bio.batch_effect(
|
515
|
+
data=[df_data_1, df_data_2, df_data_3],
|
516
|
+
datasets=["GSE25097", "GSE62232", "GSE65372"], clean_data=True
|
517
|
+
)
|
518
|
+
"""
|
519
|
+
# data = [df_gene_1, df_gene_2, df_gene_3]
|
520
|
+
# datasets = ["GSE25097", "GSE62232", "GSE65372"]
|
521
|
+
# top_genes = 10 # show top 10 genes
|
522
|
+
# plot_ = True
|
523
|
+
from combat.pycombat import pycombat
|
524
|
+
if clean_data:
|
525
|
+
data=[clean_dataset(data=dt,dataset=ds,**kws_clean_dataset) for (dt,ds) in zip(data,datasets)]
|
526
|
+
#! prepare data
|
527
|
+
# the datasets are dataframes where:
|
528
|
+
# the indexes correspond to the gene names
|
529
|
+
# the column names correspond to the sample names
|
530
|
+
#! merge batchs
|
531
|
+
# https://epigenelabs.github.io/pyComBat/
|
532
|
+
# we merge all the datasets into one, by keeping the common genes only
|
533
|
+
df_expression_common_genes = pd.concat(data, join="inner", axis=1)
|
534
|
+
#! convert to float
|
535
|
+
ips.df_astype(df_expression_common_genes, astype="float", inplace=True)
|
536
|
+
|
537
|
+
#!to visualise results, use Mini datasets, only take the first 10 samples of each batch(dataset)
|
538
|
+
if plot_:
|
539
|
+
col2plot = []
|
540
|
+
for ds in datasets:
|
541
|
+
# select the first 10 samples to plot, to see the diff
|
542
|
+
dat_tmp = df_expression_common_genes.columns[
|
543
|
+
df_expression_common_genes.columns.str.startswith(ds)
|
544
|
+
][:top_genes].tolist()
|
545
|
+
col2plot.extend(dat_tmp)
|
546
|
+
# visualise results
|
547
|
+
_, axs = plt.subplots(2, 1, figsize=(15, 10))
|
548
|
+
plot.plotxy(
|
549
|
+
ax=axs[0],
|
550
|
+
data=df_expression_common_genes.loc[:, col2plot],
|
551
|
+
kind="bar",
|
552
|
+
figsets=dict(
|
553
|
+
title="Samples expression distribution (non-correction)",
|
554
|
+
ylabel="Observations",
|
555
|
+
xangle=90,
|
556
|
+
),
|
557
|
+
)
|
558
|
+
# prepare batch list
|
559
|
+
batch = [
|
560
|
+
ips.ssplit(i, by="_")[0] for i in df_expression_common_genes.columns.tolist()
|
561
|
+
]
|
562
|
+
# run pyComBat
|
563
|
+
df_corrected = pycombat(df_expression_common_genes, batch, **kwargs)
|
564
|
+
print(f"df_corrected.shape: {df_corrected.shape}")
|
565
|
+
display(df_corrected.head())
|
566
|
+
# visualise results again
|
567
|
+
if plot_:
|
568
|
+
|
569
|
+
plot.plotxy(
|
570
|
+
ax=axs[1],
|
571
|
+
data=df_corrected.loc[:, col2plot],
|
572
|
+
kind="bar",
|
573
|
+
figsets=dict(
|
574
|
+
title="Samples expression distribution (corrected)",
|
575
|
+
ylabel="Observations",
|
576
|
+
xangle=90,
|
577
|
+
),
|
578
|
+
)
|
579
|
+
if dir_save is not None:
|
580
|
+
ips.figsave(dir_save + "batch_sample_exp_distri.pdf")
|
581
|
+
return df_corrected
|
582
|
+
|
583
|
+
def get_common_genes(elment1, elment2):
|
584
|
+
common_genes=ips.shared(elment1, elment2)
|
585
|
+
return common_genes
|
586
|
+
|
587
|
+
def counts2expression(
|
588
|
+
counts: pd.DataFrame,# index(samples); columns(genes)
|
589
|
+
method: str = "TMM", # 'CPM', 'FPKM', 'TPM', 'UQ', 'TMM', 'CUF', 'CTF'
|
590
|
+
length: list = None,
|
591
|
+
uq_factors: pd.Series = None,
|
592
|
+
verbose: bool = False,
|
593
|
+
) -> pd.DataFrame:
|
594
|
+
"""
|
595
|
+
https://www.linkedin.com/pulse/snippet-corner-raw-read-count-normalization-python-mazzalab-gzzyf?trk=public_post
|
596
|
+
Convert raw RNA-seq read counts to expression values
|
597
|
+
counts: pd.DataFrame
|
598
|
+
index: samples
|
599
|
+
columns: genes
|
600
|
+
usage:
|
601
|
+
df_normalized = counts2expression(df_counts, method='TMM', verbose=True)
|
602
|
+
recommend cross datasets:
|
603
|
+
cross-datasets:
|
604
|
+
TMM (Trimmed Mean of M-values); Very suitable for merging datasets, especially
|
605
|
+
for cross-sample and cross-dataset comparisons; commonly used in
|
606
|
+
differential expression analysis
|
607
|
+
CTF (Counts adjusted with TMM factors); Suitable for merging datasets, as
|
608
|
+
TMM-based normalization. Typically used as input for downstream analyses
|
609
|
+
like differential expression
|
610
|
+
TPM (Transcripts Per Million); Good for merging datasets. TPM is often more
|
611
|
+
suitable for cross-dataset comparisons because it adjusts for gene length
|
612
|
+
and ensures that the expression levels sum to the same total in each sample
|
613
|
+
UQ (Upper Quartile); less commonly used than TPM or TMM
|
614
|
+
CUF (Counts adjusted with UQ factors); Can be used, but UQ normalization is
|
615
|
+
generally not as standardized as TPM or TMM for merging datasets.
|
616
|
+
within-datasets:
|
617
|
+
CPM(Counts Per Million); it doesn’t adjust for gene length or other
|
618
|
+
variables that could vary across datasets
|
619
|
+
FPKM(Fragments Per Kilobase Million); FPKM has been known to be inconsistent
|
620
|
+
across different experiments
|
621
|
+
Parameters:
|
622
|
+
- counts: pd.DataFrame
|
623
|
+
Raw read counts with genes as rows and samples as columns.
|
624
|
+
- method: str, default='TMM'
|
625
|
+
CPM (Counts per Million): Scales counts by total library size.
|
626
|
+
FPKM (Fragments per Kilobase Million): Requires gene length; scales by both library size and gene length.
|
627
|
+
TPM (Transcripts per Million): Scales by gene length and total transcript abundance.
|
628
|
+
UQ (Upper Quartile): Normalizes based on the upper quartile of the counts.
|
629
|
+
TMM (Trimmed Mean of M-values): Adjusts for compositional biases.
|
630
|
+
CUF (Counts adjusted with Upper Quartile factors): Counts adjusted based on UQ factors.
|
631
|
+
CTF (Counts adjusted with TMM factors): Counts adjusted based on TMM factors.
|
632
|
+
- gene_lengths: pd.Series, optional
|
633
|
+
Gene lengths (e.g., in kilobases) for FPKM/TPM normalization. Required for FPKM/TPM.
|
634
|
+
- verbose: bool, default=False
|
635
|
+
If True, provides detailed logging information.
|
636
|
+
- uq_factors: pd.Series, optional
|
637
|
+
Precomputed Upper Quartile factors, required for UQ and CUF normalization.
|
638
|
+
|
639
|
+
|
640
|
+
Returns:
|
641
|
+
- normalized_counts: pd.DataFrame
|
642
|
+
Normalized expression values.
|
643
|
+
"""
|
644
|
+
import rnanorm
|
645
|
+
print(f"'counts' data shoule be: index(samples); columns(genes)")
|
646
|
+
if "length" in method: # 有时候记不住这么多不同的名字
|
647
|
+
method="FPKM"
|
648
|
+
methods = ["CPM", "FPKM", "TPM", "UQ", "TMM", "CUF", "CTF"]
|
649
|
+
method = ips.strcmp(method, methods)[0]
|
650
|
+
if verbose:
|
651
|
+
print(
|
652
|
+
f"Starting normalization using method: {method},supported methods: {methods}"
|
653
|
+
)
|
654
|
+
columns_org = counts.columns.tolist()
|
655
|
+
# Check if gene lengths are provided when necessary
|
656
|
+
if method in ["FPKM", "TPM"]:
|
657
|
+
if length is None:
|
658
|
+
raise ValueError(f"Gene lengths must be provided for {method} normalization.")
|
659
|
+
if isinstance(length, list):
|
660
|
+
df_genelength = pd.DataFrame({"gene_length": length})
|
661
|
+
df_genelength.index = counts.columns # set gene_id as index
|
662
|
+
df_genelength.index = df_genelength.index.astype(str).str.strip()
|
663
|
+
# length = np.array(df_genelength["gene_length"]).reshape(1,-1)
|
664
|
+
length = df_genelength["gene_length"]
|
665
|
+
counts.index = counts.index.astype(str).str.strip()
|
666
|
+
elif isinstance(length, pd.Series):
|
667
|
+
|
668
|
+
length.index=length.index.astype(str).str.strip()
|
669
|
+
counts.columns = counts.columns.astype(str).str.strip()
|
670
|
+
shared_genes=ips.shared(length.index, counts.columns)
|
671
|
+
length=length.loc[shared_genes]
|
672
|
+
counts=counts.loc[:,shared_genes]
|
673
|
+
columns_org = counts.columns.tolist()
|
674
|
+
|
675
|
+
|
676
|
+
# # Ensure gene lengths are aligned with counts if provided
|
677
|
+
# if length is not None:
|
678
|
+
# length = length[counts.index]
|
679
|
+
|
680
|
+
# Start the normalization based on the chosen method
|
681
|
+
if method == "CPM":
|
682
|
+
normalized_counts = (
|
683
|
+
rnanorm.CPM().set_output(transform="pandas").fit_transform(counts)
|
684
|
+
)
|
685
|
+
|
686
|
+
elif method == "FPKM":
|
687
|
+
if verbose:
|
688
|
+
print("Performing FPKM normalization using gene lengths.")
|
689
|
+
normalized_counts = (
|
690
|
+
rnanorm.CPM().set_output(transform="pandas").fit_transform(counts)
|
691
|
+
)
|
692
|
+
# convert it to FPKM by, {FPKM= gene length /read counts ×1000} is applied using row-wise division and multiplication.
|
693
|
+
normalized_counts=normalized_counts.div(length.values,axis=1)*1e3
|
694
|
+
|
695
|
+
elif method == "TPM":
|
696
|
+
if verbose:
|
697
|
+
print("Performing TPM normalization using gene lengths.")
|
698
|
+
normalized_counts = (
|
699
|
+
rnanorm.TPM(gene_lengths=length)
|
700
|
+
.set_output(transform="pandas")
|
701
|
+
.fit_transform(counts)
|
702
|
+
)
|
703
|
+
|
704
|
+
elif method == "UQ":
|
705
|
+
if verbose:
|
706
|
+
print("Performing Upper Quartile (UQ) normalization.")
|
707
|
+
if uq_factors is None:
|
708
|
+
uq_factors = rnanorm.upper_quartile_factors(counts)
|
709
|
+
normalized_counts = (
|
710
|
+
rnanorm.UQ(factors=uq_factors)()
|
711
|
+
.set_output(transform="pandas")
|
712
|
+
.fit_transform(counts)
|
713
|
+
)
|
714
|
+
|
715
|
+
elif method == "TMM":
|
716
|
+
if verbose:
|
717
|
+
print("Performing TMM normalization (Trimmed Mean of M-values).")
|
718
|
+
normalized_counts = (
|
719
|
+
rnanorm.TMM().set_output(transform="pandas").fit_transform(counts)
|
720
|
+
)
|
721
|
+
|
722
|
+
elif method == "CUF":
|
723
|
+
if verbose:
|
724
|
+
print("Performing Counts adjusted with UQ factors (CUF).")
|
725
|
+
if uq_factors is None:
|
726
|
+
uq_factors = rnanorm.upper_quartile_factors(counts)
|
727
|
+
normalized_counts = (
|
728
|
+
rnanorm.CUF(factors=uq_factors)()
|
729
|
+
.set_output(transform="pandas")
|
730
|
+
.fit_transform(counts)
|
731
|
+
)
|
732
|
+
|
733
|
+
elif method == "CTF":
|
734
|
+
if verbose:
|
735
|
+
print("Performing Counts adjusted with TMM factors (CTF).")
|
736
|
+
normalized_counts = (rnanorm.CTF().set_output(transform="pandas").fit_transform(counts))
|
737
|
+
|
738
|
+
else:
|
739
|
+
raise ValueError(f"Unknown normalization method: {method}")
|
740
|
+
normalized_counts.columns=columns_org
|
741
|
+
if verbose:
|
742
|
+
print(f"Normalization complete using method: {method}")
|
743
|
+
|
744
|
+
return normalized_counts
|
745
|
+
|
746
|
+
def counts_deseq(counts_sam_gene: pd.DataFrame,
|
747
|
+
meta_sam_cond: pd.DataFrame,
|
748
|
+
design_factors:list=None,
|
749
|
+
kws_DeseqDataSet:dict={},
|
750
|
+
kws_DeseqStats:dict={}):
|
751
|
+
"""
|
752
|
+
https://pydeseq2.readthedocs.io/en/latest/api/docstrings/pydeseq2.ds.DeseqStats.html
|
753
|
+
Note: Using normalized expression data in a DeseqDataSet object is generally not recommended
|
754
|
+
because the DESeq2 framework is designed to work with raw count data.
|
755
|
+
baseMean:
|
756
|
+
- This value represents the average normalized count (or expression level) of a
|
757
|
+
gene across all samples in your dataset.
|
758
|
+
- For example, a baseMean of 0.287 for 4933401J01Rik indicates that this gene has
|
759
|
+
low expression levels in the samples compared to others with higher baseMean
|
760
|
+
values like Xkr4 (591.015).
|
761
|
+
log2FoldChange: the magnitude and direction of change in expression between conditions.
|
762
|
+
lfcSE (Log Fold Change Standard Error): standard error of the log2FoldChange. It
|
763
|
+
indicates the uncertainty in the estimate of the fold change.A lower value indicates
|
764
|
+
more confidence in the fold change estimate.
|
765
|
+
padj: This value accounts for multiple testing corrections (e.g., Benjamini-Hochberg).
|
766
|
+
Log10transforming: The columns -log10(pvalue) and -log10(FDR) are transformations of
|
767
|
+
the p-values and adjusted p-values, respectively
|
768
|
+
"""
|
769
|
+
from pydeseq2.dds import DeseqDataSet
|
770
|
+
from pydeseq2.ds import DeseqStats
|
771
|
+
from pydeseq2.default_inference import DefaultInference
|
772
|
+
|
773
|
+
# data filtering
|
774
|
+
# counts_sam_gene = counts_sam_gene.loc[:, ~(counts_sam_gene.sum(axis=0) < 10)]
|
775
|
+
if design_factors is None:
|
776
|
+
design_factors=meta_sam_cond.columns.tolist()
|
777
|
+
|
778
|
+
kws_DeseqDataSet.pop("design_factors",{})
|
779
|
+
refit_cooks=kws_DeseqDataSet.pop("refit_cooks",True)
|
780
|
+
|
781
|
+
#! DeseqDataSet
|
782
|
+
inference = DefaultInference(n_cpus=8)
|
783
|
+
dds = DeseqDataSet(
|
784
|
+
counts=counts_sam_gene,
|
785
|
+
metadata=meta_sam_cond,
|
786
|
+
design_factors=meta_sam_cond.columns.tolist(),
|
787
|
+
refit_cooks=refit_cooks,
|
788
|
+
inference=inference,
|
789
|
+
**kws_DeseqDataSet
|
790
|
+
)
|
791
|
+
dds.deseq2()
|
792
|
+
#* results
|
793
|
+
dds_explain="""
|
794
|
+
res[0]:
|
795
|
+
# X stores the count data,
|
796
|
+
# obs stores design factors,
|
797
|
+
# obsm stores sample-level data, such as "design_matrix" and "size_factors",
|
798
|
+
# varm stores gene-level data, such as "dispersions" and "LFC"."""
|
799
|
+
print(dds_explain)
|
800
|
+
#! DeseqStats
|
801
|
+
stat_res = DeseqStats(dds,**kws_DeseqStats)
|
802
|
+
stat_res.summary()
|
803
|
+
diff = stat_res.results_df.assign(padj=lambda x: x.padj.fillna(1))
|
804
|
+
|
805
|
+
# handle '0' issue, which will case inf when the later cal (e.g., log10)
|
806
|
+
diff["padj"] = diff["padj"].replace(0, 1e-10)
|
807
|
+
diff["pvalue"] = diff["pvalue"].replace(0, 1e-10)
|
808
|
+
|
809
|
+
diff["-log10(pvalue)"] = diff["pvalue"].apply(lambda x: -np.log10(x))
|
810
|
+
diff["-log10(FDR)"] = diff["padj"].apply(lambda x: -np.log10(x))
|
811
|
+
diff=diff.reset_index().rename(columns={"index": "gene"})
|
812
|
+
# sig_diff = (
|
813
|
+
# diff.query("log2FoldChange.abs()>0.585 & padj<0.05")
|
814
|
+
# .reset_index()
|
815
|
+
# .rename(columns={"index": "gene"})
|
816
|
+
# )
|
817
|
+
return dds, diff,stat_res
|
818
|
+
|
819
|
+
def scope_genes(gene_list: list, scopes:str=None, fields: str = "symbol", species="human"):
|
820
|
+
"""
|
821
|
+
usage:
|
822
|
+
scope_genes(df_counts.columns.tolist()[:1000], species="mouse")
|
823
|
+
"""
|
824
|
+
import mygene
|
825
|
+
|
826
|
+
if scopes is None:
|
827
|
+
# copy from: https://docs.mygene.info/en/latest/doc/query_service.html#scopes
|
828
|
+
scopes = ips.fload(
|
829
|
+
"/Users/macjianfeng/Dropbox/github/python/py2ls/py2ls/data/mygenes_fields_241022.txt",
|
830
|
+
kind="csv",
|
831
|
+
verbose=False,
|
832
|
+
)
|
833
|
+
scopes = ",".join([i.strip() for i in scopes.iloc[:, 0]])
|
834
|
+
mg = mygene.MyGeneInfo()
|
835
|
+
results = mg.querymany(
|
836
|
+
gene_list,
|
837
|
+
scopes=scopes,
|
838
|
+
fields=fields,
|
839
|
+
species=species,
|
840
|
+
)
|
841
|
+
return pd.DataFrame(results)
|
842
|
+
|
843
|
+
def get_enrichr(gene_symbol_list,
|
844
|
+
gene_sets:str,
|
845
|
+
species='Human',
|
846
|
+
dir_save="./",
|
847
|
+
plot_=False,
|
848
|
+
n_top=30,
|
849
|
+
palette=None,
|
850
|
+
check_shared=True,
|
851
|
+
figsize=(5,8),
|
852
|
+
show_ring=False,
|
853
|
+
xticklabels_rot=0,
|
854
|
+
title=None,# 'KEGG'
|
855
|
+
cutoff=0.05,
|
856
|
+
cmap="coolwarm",
|
857
|
+
**kwargs):
|
858
|
+
"""
|
859
|
+
Note: Enrichr uses a list of Entrez gene symbols as input.
|
860
|
+
|
861
|
+
"""
|
862
|
+
kws_figsets = {}
|
863
|
+
for k_arg, v_arg in kwargs.items():
|
864
|
+
if "figset" in k_arg:
|
865
|
+
kws_figsets = v_arg
|
866
|
+
kwargs.pop(k_arg, None)
|
867
|
+
break
|
868
|
+
species_org=species
|
869
|
+
# organism (str) – Select one from { ‘Human’, ‘Mouse’, ‘Yeast’, ‘Fly’, ‘Fish’, ‘Worm’ }
|
870
|
+
organisms=['Human', 'Mouse', 'Yeast', 'Fly', 'Fish', 'Worm']
|
871
|
+
species=ips.strcmp(species,organisms)[0]
|
872
|
+
if species_org.lower()!= species.lower():
|
873
|
+
print(f"species was corrected to {species}, becasue only support {organisms}")
|
874
|
+
if os.path.isfile(gene_sets):
|
875
|
+
gene_sets_name=os.path.basename(gene_sets)
|
876
|
+
gene_sets = ips.fload(gene_sets)
|
877
|
+
else:
|
878
|
+
lib_support_names = gp.get_library_name()
|
879
|
+
# correct input gene_set name
|
880
|
+
gene_sets_name=ips.strcmp(gene_sets,lib_support_names)[0]
|
881
|
+
# download it
|
882
|
+
gene_sets = gp.get_library(name=gene_sets_name, organism=species)
|
883
|
+
print(f"gene_sets get ready: {gene_sets_name}")
|
884
|
+
|
885
|
+
# gene symbols are uppercase
|
886
|
+
gene_symbol_list=[str(i).upper() for i in gene_symbol_list]
|
887
|
+
|
888
|
+
# # check how shared genes
|
889
|
+
if check_shared:
|
890
|
+
shared_genes=ips.shared(ips.flatten(gene_symbol_list,verbose=False), ips.flatten(gene_sets,verbose=False))
|
891
|
+
|
892
|
+
#! enrichr
|
893
|
+
try:
|
894
|
+
enr = gp.enrichr(
|
895
|
+
gene_list=gene_symbol_list,
|
896
|
+
gene_sets=gene_sets,
|
897
|
+
organism=species,
|
898
|
+
outdir=None, # don't write to disk
|
899
|
+
**kwargs
|
900
|
+
)
|
901
|
+
except ValueError as e:
|
902
|
+
print(f"\n{'!'*10} Error {'!'*10}\n{' '*4}{e}\n{'!'*10} Error {'!'*10}")
|
903
|
+
return None
|
904
|
+
|
905
|
+
results_df = enr.results
|
906
|
+
print(f"got enrichr reslutls; shape: {results_df.shape}")
|
907
|
+
results_df["-log10(Adjusted P-value)"] = -np.log10(results_df["Adjusted P-value"])
|
908
|
+
results_df.sort_values("-log10(Adjusted P-value)", inplace=True, ascending=False)
|
909
|
+
|
910
|
+
if plot_:
|
911
|
+
if palette is None:
|
912
|
+
palette=plot.get_color(n_top, cmap="coolwarm")[::-1]
|
913
|
+
#! barplot
|
914
|
+
if n_top<5:
|
915
|
+
height_=4
|
916
|
+
elif 5<=n_top<10:
|
917
|
+
height_=5
|
918
|
+
elif 5<=n_top<10:
|
919
|
+
height_=6
|
920
|
+
elif 10<=n_top<15:
|
921
|
+
height_=7
|
922
|
+
elif 15<=n_top<20:
|
923
|
+
height_=8
|
924
|
+
elif 25<=n_top<30:
|
925
|
+
height_=9
|
926
|
+
else:
|
927
|
+
height_=int(n_top/3)
|
928
|
+
plt.figure(figsize=[5, height_])
|
929
|
+
ax1=plot.plotxy(
|
930
|
+
data=results_df.head(n_top),
|
931
|
+
kind="barplot",
|
932
|
+
x="-log10(Adjusted P-value)",
|
933
|
+
y="Term",
|
934
|
+
hue="Term",
|
935
|
+
palette=palette,
|
936
|
+
legend=None,
|
937
|
+
)
|
938
|
+
if dir_save:
|
939
|
+
ips.figsave(f"{dir_save} enr_barplot.pdf")
|
940
|
+
plot.figsets(ax=ax1, **kws_figsets)
|
941
|
+
plt.show()
|
942
|
+
|
943
|
+
#! dotplot
|
944
|
+
cutoff_curr = cutoff
|
945
|
+
step=0.05
|
946
|
+
cutoff_stop = 0.5
|
947
|
+
while cutoff_curr <=cutoff_stop:
|
948
|
+
try:
|
949
|
+
print(kws_figsets)
|
950
|
+
if cutoff_curr!=cutoff:
|
951
|
+
plt.clf()
|
952
|
+
ax2 = gp.dotplot(enr.res2d,
|
953
|
+
column="Adjusted P-value",
|
954
|
+
show_ring=show_ring,
|
955
|
+
xticklabels_rot=xticklabels_rot,
|
956
|
+
title=title,
|
957
|
+
cmap=cmap,
|
958
|
+
cutoff=cutoff_curr,
|
959
|
+
top_term=n_top,
|
960
|
+
figsize=[6, height_])
|
961
|
+
if len(ax2.collections)>=n_top:
|
962
|
+
print(f"cutoff={cutoff_curr} done! ")
|
963
|
+
break
|
964
|
+
if cutoff_curr==cutoff_stop:
|
965
|
+
break
|
966
|
+
cutoff_curr+=step
|
967
|
+
except Exception as e:
|
968
|
+
cutoff_curr+=step
|
969
|
+
print(f"Warning: trying cutoff={cutoff_curr}, cutoff={cutoff_curr-step} failed: {e} ")
|
970
|
+
ax = plt.gca()
|
971
|
+
plot.figsets(ax=ax,**kws_figsets)
|
972
|
+
|
973
|
+
if dir_save:
|
974
|
+
ips.figsave(f"{dir_save}enr_dotplot.pdf")
|
975
|
+
|
976
|
+
return results_df
|
977
|
+
|
978
|
+
|
979
|
+
#! https://string-db.org/help/api/
|
980
|
+
|
981
|
+
import pandas as pd
|
982
|
+
import requests
|
983
|
+
import networkx as nx
|
984
|
+
import matplotlib.pyplot as plt
|
985
|
+
from io import StringIO
|
986
|
+
from py2ls import ips
|
987
|
+
|
988
|
+
|
989
|
+
def get_ppi(
|
990
|
+
target_genes:list,
|
991
|
+
species:int=9606, # "human"
|
992
|
+
ci:float=0.1, # int 1~1000
|
993
|
+
max_nodes:int=50,
|
994
|
+
base_url:str="https://string-db.org",
|
995
|
+
gene_mapping_api:str="/api/json/get_string_ids?",
|
996
|
+
interaction_api:str="/api/tsv/network?",
|
997
|
+
):
|
998
|
+
"""
|
999
|
+
Generate a Protein-Protein Interaction (PPI) network using STRINGdb data.
|
1000
|
+
|
1001
|
+
return:
|
1002
|
+
the STRING protein-protein interaction (PPI) data, which contains information about
|
1003
|
+
predicted and experimentally validated associations between proteins.
|
1004
|
+
|
1005
|
+
stringId_A and stringId_B: Unique identifiers for the interacting proteins based on the
|
1006
|
+
STRING database.
|
1007
|
+
preferredName_A and preferredName_B: Standard gene names for the interacting proteins.
|
1008
|
+
ncbiTaxonId: The taxon ID (9606 for humans).
|
1009
|
+
score: A combined score reflecting the overall confidence of the interaction, which aggregates different sources of evidence.
|
1010
|
+
|
1011
|
+
nscore, fscore, pscore, ascore, escore, dscore, tscore: These are sub-scores representing the confidence in the interaction based on various evidence types:
|
1012
|
+
- nscore: Neighborhood score, based on genes located near each other in the genome.
|
1013
|
+
- fscore: Fusion score, based on gene fusions in other genomes.
|
1014
|
+
- pscore: Phylogenetic profile score, based on co-occurrence across different species.
|
1015
|
+
- ascore: Coexpression score, reflecting the likelihood of coexpression.
|
1016
|
+
- escore: Experimental score, based on experimental evidence.
|
1017
|
+
- dscore: Database score, from curated databases.
|
1018
|
+
- tscore: Text-mining score, from literature co-occurrence.
|
1019
|
+
|
1020
|
+
Higher score values (closer to 1) indicate stronger evidence for an interaction.
|
1021
|
+
- Combined score: Useful for ranking interactions based on overall confidence. A score >0.7 is typically considered high-confidence.
|
1022
|
+
- Sub-scores: Interpret the types of evidence supporting the interaction. For instance:
|
1023
|
+
- High ascore indicates strong evidence of coexpression.
|
1024
|
+
- High escore suggests experimental validation.
|
1025
|
+
|
1026
|
+
"""
|
1027
|
+
print("check api: https://string-db.org/help/api/")
|
1028
|
+
|
1029
|
+
# 将species转化为taxon_id
|
1030
|
+
if isinstance(species,str):
|
1031
|
+
print(species)
|
1032
|
+
species=list(get_taxon_id(species).values())[0]
|
1033
|
+
print(species)
|
1034
|
+
|
1035
|
+
|
1036
|
+
string_api_url = base_url + gene_mapping_api
|
1037
|
+
interaction_api_url = base_url + interaction_api
|
1038
|
+
# Map gene symbols to STRING IDs
|
1039
|
+
mapped_genes = {}
|
1040
|
+
for gene in target_genes:
|
1041
|
+
params = {"identifiers": gene, "species": species, "limit": 1}
|
1042
|
+
response = requests.get(string_api_url, params=params)
|
1043
|
+
if response.status_code == 200:
|
1044
|
+
try:
|
1045
|
+
json_data = response.json()
|
1046
|
+
if json_data:
|
1047
|
+
mapped_genes[gene] = json_data[0]["stringId"]
|
1048
|
+
except ValueError:
|
1049
|
+
print(
|
1050
|
+
f"Failed to decode JSON for gene {gene}. Response: {response.text}"
|
1051
|
+
)
|
1052
|
+
else:
|
1053
|
+
print(
|
1054
|
+
f"Failed to fetch data for gene {gene}. Status code: {response.status_code}"
|
1055
|
+
)
|
1056
|
+
if not mapped_genes:
|
1057
|
+
print("No mapped genes found in STRING database.")
|
1058
|
+
return None
|
1059
|
+
|
1060
|
+
# Retrieve PPI data from STRING API
|
1061
|
+
string_ids = "%0d".join(mapped_genes.values())
|
1062
|
+
params = {
|
1063
|
+
"identifiers": string_ids,
|
1064
|
+
"species": species,
|
1065
|
+
"required_score": int(ci * 1000),
|
1066
|
+
"limit": max_nodes,
|
1067
|
+
}
|
1068
|
+
response = requests.get(interaction_api_url, params=params)
|
1069
|
+
|
1070
|
+
if response.status_code == 200:
|
1071
|
+
try:
|
1072
|
+
interactions = pd.read_csv(StringIO(response.text), sep="\t")
|
1073
|
+
except Exception as e:
|
1074
|
+
print("Error reading the interaction data:", e)
|
1075
|
+
print("Response content:", response.text)
|
1076
|
+
return None
|
1077
|
+
else:
|
1078
|
+
print(
|
1079
|
+
f"Failed to retrieve interaction data. Status code: {response.status_code}"
|
1080
|
+
)
|
1081
|
+
print("Response content:", response.text)
|
1082
|
+
return None
|
1083
|
+
display(interactions.head())
|
1084
|
+
# Filter interactions by ci score
|
1085
|
+
if "score" in interactions.columns:
|
1086
|
+
interactions = interactions[interactions["score"] >= ci]
|
1087
|
+
if interactions.empty:
|
1088
|
+
print("No interactions found with the specified confidence.")
|
1089
|
+
return None
|
1090
|
+
else:
|
1091
|
+
print("The 'score' column is missing from the retrieved data. Unable to filter by confidence interval.")
|
1092
|
+
if "fdr" in interactions.columns:
|
1093
|
+
interactions=interactions.sort_values(by="fdr",ascending=False)
|
1094
|
+
return interactions
|
1095
|
+
# * usage
|
1096
|
+
# interactions = get_ppi(target_genes, ci=0.0001)
|
1097
|
+
|
1098
|
+
def plot_ppi(
|
1099
|
+
interactions,
|
1100
|
+
player1="preferredName_A",
|
1101
|
+
player2="preferredName_B",
|
1102
|
+
weight="score",
|
1103
|
+
n_layers=None, # Number of concentric layers
|
1104
|
+
n_rank=[5, 10], # Nodes in each rank for the concentric layout
|
1105
|
+
dist_node = 10, # Distance between each rank of circles
|
1106
|
+
layout="degree",
|
1107
|
+
size='auto',#700,
|
1108
|
+
facecolor="skyblue",
|
1109
|
+
cmap='coolwarm',
|
1110
|
+
edgecolor="k",
|
1111
|
+
edgelinewidth=1.5,
|
1112
|
+
alpha=.5,
|
1113
|
+
marker="o",
|
1114
|
+
node_hideticks=True,
|
1115
|
+
linecolor="gray",
|
1116
|
+
linewidth=1.5,
|
1117
|
+
linestyle="-",
|
1118
|
+
line_arrowstyle='-',
|
1119
|
+
fontsize=10,
|
1120
|
+
fontcolor="k",
|
1121
|
+
ha:str="center",
|
1122
|
+
va:str="center",
|
1123
|
+
figsize=(12, 10),
|
1124
|
+
k_value=0.3,
|
1125
|
+
bgcolor="w",
|
1126
|
+
dir_save="./ppi_network.html",
|
1127
|
+
physics=True,
|
1128
|
+
notebook=False,
|
1129
|
+
scale=1,
|
1130
|
+
ax=None,
|
1131
|
+
**kwargs
|
1132
|
+
):
|
1133
|
+
"""
|
1134
|
+
Plot a Protein-Protein Interaction (PPI) network with adjustable appearance.
|
1135
|
+
"""
|
1136
|
+
from pyvis.network import Network
|
1137
|
+
import networkx as nx
|
1138
|
+
from IPython.display import IFrame
|
1139
|
+
from matplotlib.colors import Normalize
|
1140
|
+
from matplotlib import cm
|
1141
|
+
# Check for required columns in the DataFrame
|
1142
|
+
for col in [player1, player2, weight]:
|
1143
|
+
if col not in interactions.columns:
|
1144
|
+
raise ValueError(f"Column '{col}' is missing from the interactions DataFrame.")
|
1145
|
+
|
1146
|
+
# Initialize Pyvis network
|
1147
|
+
net = Network(height="750px", width="100%", bgcolor=bgcolor, font_color=fontcolor)
|
1148
|
+
net.force_atlas_2based(
|
1149
|
+
gravity=-50, central_gravity=0.01, spring_length=100, spring_strength=0.1
|
1150
|
+
)
|
1151
|
+
net.toggle_physics(physics)
|
1152
|
+
|
1153
|
+
kws_figsets = {}
|
1154
|
+
for k_arg, v_arg in kwargs.items():
|
1155
|
+
if "figset" in k_arg:
|
1156
|
+
kws_figsets = v_arg
|
1157
|
+
kwargs.pop(k_arg, None)
|
1158
|
+
break
|
1159
|
+
|
1160
|
+
# Create a NetworkX graph from the interaction data
|
1161
|
+
G = nx.Graph()
|
1162
|
+
for _, row in interactions.iterrows():
|
1163
|
+
G.add_edge(row[player1], row[player2], weight=row[weight])
|
1164
|
+
|
1165
|
+
# Calculate node degrees
|
1166
|
+
degrees = dict(G.degree())
|
1167
|
+
norm = Normalize(vmin=min(degrees.values()), vmax=max(degrees.values()))
|
1168
|
+
colormap = cm.get_cmap(cmap) # Get the 'coolwarm' colormap
|
1169
|
+
|
1170
|
+
# Set properties based on degrees
|
1171
|
+
if not isinstance(size, (int,float,list)):
|
1172
|
+
size = [deg * 50 for deg in degrees.values()] # Scale sizes
|
1173
|
+
if not ips.isa(facecolor, 'color'):
|
1174
|
+
facecolor = [colormap(norm(deg)) for deg in degrees.values()] # Use colormap
|
1175
|
+
if size is None:
|
1176
|
+
size = [700] * G.number_of_nodes() # Default size for all nodes
|
1177
|
+
elif isinstance(size, (int, float)):
|
1178
|
+
size = [size] * G.number_of_nodes() # If a scalar, apply to all nodes
|
1179
|
+
# else:
|
1180
|
+
# size = size.tolist() # Ensure size is a list
|
1181
|
+
if len(size)>G.number_of_nodes():
|
1182
|
+
size=size[:G.number_of_nodes()]
|
1183
|
+
|
1184
|
+
for node in G.nodes():
|
1185
|
+
net.add_node(
|
1186
|
+
node,
|
1187
|
+
label=node,
|
1188
|
+
size=size[list(G.nodes()).index(node)] if isinstance(size,list) else size[0],
|
1189
|
+
color=facecolor[list(G.nodes()).index(node)] if isinstance(facecolor,list) else facecolor,
|
1190
|
+
font={"size": fontsize, "color": fontcolor},
|
1191
|
+
)
|
1192
|
+
|
1193
|
+
for edge in G.edges(data=True):
|
1194
|
+
net.add_edge(
|
1195
|
+
edge[0],
|
1196
|
+
edge[1],
|
1197
|
+
weight=edge[2]["weight"],
|
1198
|
+
color=edgecolor,
|
1199
|
+
width=edgelinewidth * edge[2]["weight"],
|
1200
|
+
)
|
1201
|
+
layouts = [
|
1202
|
+
"spring",
|
1203
|
+
"circular",
|
1204
|
+
"kamada_kawai",
|
1205
|
+
"random",
|
1206
|
+
"shell",
|
1207
|
+
"planar",
|
1208
|
+
"spiral",
|
1209
|
+
"degree"
|
1210
|
+
]
|
1211
|
+
layout = ips.strcmp(layout, layouts)[0]
|
1212
|
+
print(layout)
|
1213
|
+
# Choose layout
|
1214
|
+
if layout == "spring":
|
1215
|
+
pos = nx.spring_layout(G, k=k_value)
|
1216
|
+
elif layout == "circular":
|
1217
|
+
pos = nx.circular_layout(G)
|
1218
|
+
elif layout == "kamada_kawai":
|
1219
|
+
pos = nx.kamada_kawai_layout(G)
|
1220
|
+
elif layout == "spectral":
|
1221
|
+
pos = nx.spectral_layout(G)
|
1222
|
+
elif layout == "random":
|
1223
|
+
pos = nx.random_layout(G)
|
1224
|
+
elif layout == "shell":
|
1225
|
+
pos = nx.shell_layout(G)
|
1226
|
+
elif layout == "planar":
|
1227
|
+
if nx.check_planarity(G)[0]:
|
1228
|
+
pos = nx.planar_layout(G)
|
1229
|
+
else:
|
1230
|
+
print("Graph is not planar; switching to spring layout.")
|
1231
|
+
pos = nx.spring_layout(G, k=k_value)
|
1232
|
+
elif layout == "spiral":
|
1233
|
+
pos = nx.spiral_layout(G)
|
1234
|
+
elif layout=='degree':
|
1235
|
+
# Calculate node degrees and sort nodes by degree
|
1236
|
+
degrees = dict(G.degree())
|
1237
|
+
sorted_nodes = sorted(degrees.items(), key=lambda x: x[1], reverse=True)
|
1238
|
+
|
1239
|
+
# Create positions for concentric circles based on n_layers and n_rank
|
1240
|
+
pos = {}
|
1241
|
+
n_layers=len(n_rank)+1 if n_layers is None else n_layers
|
1242
|
+
for rank_index in range(n_layers):
|
1243
|
+
if rank_index < len(n_rank):
|
1244
|
+
nodes_per_rank = n_rank[rank_index]
|
1245
|
+
rank_nodes = sorted_nodes[sum(n_rank[:rank_index]): sum(n_rank[:rank_index + 1])]
|
1246
|
+
else:
|
1247
|
+
# 随机打乱剩余节点的顺序
|
1248
|
+
remaining_nodes = sorted_nodes[sum(n_rank[:rank_index]):]
|
1249
|
+
random_indices = np.random.permutation(len(remaining_nodes))
|
1250
|
+
rank_nodes = [remaining_nodes[i] for i in random_indices]
|
1251
|
+
|
1252
|
+
radius = (rank_index + 1) * dist_node # Radius for this rank
|
1253
|
+
|
1254
|
+
# Arrange nodes in a circle for the current rank
|
1255
|
+
for i, (node, degree) in enumerate(rank_nodes):
|
1256
|
+
angle = (i / len(rank_nodes)) * 2 * np.pi # Distribute around circle
|
1257
|
+
pos[node] = (radius * np.cos(angle), radius * np.sin(angle))
|
1258
|
+
|
1259
|
+
else:
|
1260
|
+
print(f"Unknown layout '{layout}', defaulting to 'spring',or可以用这些: {layouts}")
|
1261
|
+
pos = nx.spring_layout(G, k=k_value)
|
1262
|
+
|
1263
|
+
for node, (x, y) in pos.items():
|
1264
|
+
net.get_node(node)["x"] = x * scale
|
1265
|
+
net.get_node(node)["y"] = y * scale
|
1266
|
+
|
1267
|
+
# If ax is None, use plt.gca()
|
1268
|
+
if ax is None:
|
1269
|
+
fig, ax = plt.subplots(1,1,figsize=figsize)
|
1270
|
+
|
1271
|
+
# Draw nodes, edges, and labels with customization options
|
1272
|
+
nx.draw_networkx_nodes(
|
1273
|
+
G,
|
1274
|
+
pos,
|
1275
|
+
ax=ax,
|
1276
|
+
node_size=size,
|
1277
|
+
node_color=facecolor,
|
1278
|
+
linewidths=edgelinewidth,
|
1279
|
+
edgecolors=edgecolor,
|
1280
|
+
alpha=alpha,
|
1281
|
+
hide_ticks=node_hideticks,
|
1282
|
+
node_shape=marker
|
1283
|
+
)
|
1284
|
+
nx.draw_networkx_edges(
|
1285
|
+
G,
|
1286
|
+
pos,
|
1287
|
+
ax=ax,
|
1288
|
+
edge_color=linecolor,
|
1289
|
+
width=linewidth,
|
1290
|
+
style=linestyle,
|
1291
|
+
arrowstyle=line_arrowstyle,
|
1292
|
+
alpha=0.7
|
1293
|
+
)
|
1294
|
+
nx.draw_networkx_labels(
|
1295
|
+
G, pos, ax=ax, font_size=fontsize, font_color=fontcolor,horizontalalignment=ha,verticalalignment=va
|
1296
|
+
)
|
1297
|
+
plot.figsets(ax=ax,**kws_figsets)
|
1298
|
+
ax.axis("off")
|
1299
|
+
net.write_html(dir_save)
|
1300
|
+
return G,ax
|
1301
|
+
|
1302
|
+
|
1303
|
+
# * usage:
|
1304
|
+
# G, ax = bio.plot_ppi(
|
1305
|
+
# interactions,
|
1306
|
+
# player1="preferredName_A",
|
1307
|
+
# player2="preferredName_B",
|
1308
|
+
# weight="score",
|
1309
|
+
# # size="auto",
|
1310
|
+
# # size=interactions["score"].tolist(),
|
1311
|
+
# # layout="circ",
|
1312
|
+
# n_rank=[5, 10, 15],
|
1313
|
+
# dist_node=100,
|
1314
|
+
# alpha=0.6,
|
1315
|
+
# linecolor="0.8",
|
1316
|
+
# linewidth=1,
|
1317
|
+
# figsize=(8, 8.5),
|
1318
|
+
# cmap="jet",
|
1319
|
+
# edgelinewidth=0.5,
|
1320
|
+
# # facecolor="#FF5F57",
|
1321
|
+
# fontsize=10,
|
1322
|
+
# # fontcolor="b",
|
1323
|
+
# # edgecolor="r",
|
1324
|
+
# # scale=100,
|
1325
|
+
# # physics=False,
|
1326
|
+
# figsets=dict(title="ppi networks"),
|
1327
|
+
# )
|
1328
|
+
# figsave("./ppi_network.pdf")
|
1329
|
+
|
1330
|
+
def top_ppi(interactions, n_top=10):
|
1331
|
+
"""
|
1332
|
+
Analyzes protein-protein interactions (PPIs) to identify key proteins based on
|
1333
|
+
degree and betweenness centrality.
|
1334
|
+
|
1335
|
+
Parameters:
|
1336
|
+
interactions (pd.DataFrame): DataFrame containing PPI data with columns
|
1337
|
+
['preferredName_A', 'preferredName_B', 'score'].
|
1338
|
+
|
1339
|
+
Returns:
|
1340
|
+
dict: A dictionary containing the top key proteins by degree and betweenness centrality.
|
1341
|
+
"""
|
1342
|
+
|
1343
|
+
# Create a NetworkX graph from the interaction data
|
1344
|
+
G = nx.Graph()
|
1345
|
+
for _, row in interactions.iterrows():
|
1346
|
+
G.add_edge(row["preferredName_A"], row["preferredName_B"], weight=row["score"])
|
1347
|
+
|
1348
|
+
# Calculate Degree Centrality
|
1349
|
+
degree_centrality = G.degree()
|
1350
|
+
key_proteins_degree = sorted(degree_centrality, key=lambda x: x[1], reverse=True)
|
1351
|
+
|
1352
|
+
# Calculate Betweenness Centrality
|
1353
|
+
betweenness_centrality = nx.betweenness_centrality(G)
|
1354
|
+
key_proteins_betweenness = sorted(
|
1355
|
+
betweenness_centrality.items(), key=lambda x: x[1], reverse=True
|
1356
|
+
)
|
1357
|
+
print(
|
1358
|
+
{
|
1359
|
+
"Top 10 Key Proteins by Degree Centrality": key_proteins_degree[:10],
|
1360
|
+
"Top 10 Key Proteins by Betweenness Centrality": key_proteins_betweenness[
|
1361
|
+
:10
|
1362
|
+
],
|
1363
|
+
}
|
1364
|
+
)
|
1365
|
+
# Return the top n_top key proteins
|
1366
|
+
if n_top == "all":
|
1367
|
+
return key_proteins_degree, key_proteins_betweenness
|
1368
|
+
else:
|
1369
|
+
return key_proteins_degree[:n_top], key_proteins_betweenness[:n_top]
|
1370
|
+
|
1371
|
+
|
1372
|
+
# * usage: top_ppi(interactions)
|
1373
|
+
# top_ppi(interactions, n_top="all")
|
1374
|
+
# top_ppi(interactions, n_top=10)
|
1375
|
+
|
1376
|
+
|
1377
|
+
|
1378
|
+
species_dict = {
|
1379
|
+
"Human": "Homo sapiens",
|
1380
|
+
"House mouse": "Mus musculus",
|
1381
|
+
"Zebrafish": "Danio rerio",
|
1382
|
+
"Norway rat": "Rattus norvegicus",
|
1383
|
+
"Fruit fly": "Drosophila melanogaster",
|
1384
|
+
"Baker's yeast": "Saccharomyces cerevisiae",
|
1385
|
+
"Nematode": "Caenorhabditis elegans",
|
1386
|
+
"Chicken": "Gallus gallus",
|
1387
|
+
"Cattle": "Bos taurus",
|
1388
|
+
"Rice": "Oryza sativa",
|
1389
|
+
"Thale cress": "Arabidopsis thaliana",
|
1390
|
+
"Guinea pig": "Cavia porcellus",
|
1391
|
+
"Domestic dog": "Canis lupus familiaris",
|
1392
|
+
"Domestic cat": "Felis catus",
|
1393
|
+
"Horse": "Equus caballus",
|
1394
|
+
"Domestic pig": "Sus scrofa",
|
1395
|
+
"African clawed frog": "Xenopus laevis",
|
1396
|
+
"Great white shark": "Carcharodon carcharias",
|
1397
|
+
"Common chimpanzee": "Pan troglodytes",
|
1398
|
+
"Rhesus macaque": "Macaca mulatta",
|
1399
|
+
"Water buffalo": "Bubalus bubalis",
|
1400
|
+
"Lettuce": "Lactuca sativa",
|
1401
|
+
"Tomato": "Solanum lycopersicum",
|
1402
|
+
"Maize": "Zea mays",
|
1403
|
+
"Cucumber": "Cucumis sativus",
|
1404
|
+
"Common grape vine": "Vitis vinifera",
|
1405
|
+
"Scots pine": "Pinus sylvestris",
|
1406
|
+
}
|
1407
|
+
|
1408
|
+
|
1409
|
+
def get_taxon_id(species_list):
|
1410
|
+
"""
|
1411
|
+
Convert species names to their corresponding taxon ID codes.
|
1412
|
+
|
1413
|
+
Parameters:
|
1414
|
+
- species_list: List of species names (strings).
|
1415
|
+
|
1416
|
+
Returns:
|
1417
|
+
- dict: A dictionary with species names as keys and their taxon IDs as values.
|
1418
|
+
"""
|
1419
|
+
from Bio import Entrez
|
1420
|
+
|
1421
|
+
if not isinstance(species_list, list):
|
1422
|
+
species_list = [species_list]
|
1423
|
+
species_list = [
|
1424
|
+
species_dict[ips.strcmp(i, ips.flatten(list(species_dict.keys())))[0]]
|
1425
|
+
for i in species_list
|
1426
|
+
]
|
1427
|
+
taxon_dict = {}
|
1428
|
+
|
1429
|
+
for species in species_list:
|
1430
|
+
try:
|
1431
|
+
search_handle = Entrez.esearch(db="taxonomy", term=species)
|
1432
|
+
search_results = Entrez.read(search_handle)
|
1433
|
+
search_handle.close()
|
1434
|
+
|
1435
|
+
# Get the taxon ID
|
1436
|
+
if search_results["IdList"]:
|
1437
|
+
taxon_id = search_results["IdList"][0]
|
1438
|
+
taxon_dict[species] = int(taxon_id)
|
1439
|
+
else:
|
1440
|
+
taxon_dict[species] = None # Not found
|
1441
|
+
except Exception as e:
|
1442
|
+
print(f"Error occurred for species '{species}': {e}")
|
1443
|
+
taxon_dict[species] = None # Error in processing
|
1444
|
+
return taxon_dict
|
1445
|
+
|
1446
|
+
|
1447
|
+
# # * usage: get_taxon_id("human")
|
1448
|
+
# species_names = ["human", "nouse", "rat"]
|
1449
|
+
# taxon_ids = get_taxon_id(species_names)
|
1450
|
+
# print(taxon_ids)
|