py2ls 0.2.4.3__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/bio.py CHANGED
@@ -1,8 +1,12 @@
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
7
11
  from . import plot
8
12
  import matplotlib.pyplot as plt
@@ -123,11 +127,32 @@ def get_meta(geo: dict, dataset: str = "GSE25097", verbose=True) -> pd.DataFrame
123
127
 
124
128
  # Convert the list of dictionaries to a DataFrame
125
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])
126
151
  if verbose:
127
152
  print(
128
153
  f"Meta info columns for dataset '{dataset}': \n{sorted(meta_df.columns.tolist())}"
129
154
  )
130
- display(meta_df[:3].T)
155
+ display(meta_df[:1].T)
131
156
  return meta_df
132
157
 
133
158
 
@@ -142,13 +167,14 @@ def get_probe(
142
167
  df_meta = get_meta(geo=geo, dataset=dataset, verbose=False)
143
168
  platform_id = df_meta["platform_id"].unique().tolist()
144
169
  platform_id = platform_id[0] if len(platform_id) == 1 else platform_id
145
- print(platform_id)
170
+ print(f"Platform: {platform_id}")
146
171
  df_probe = geo[dataset].gpls[platform_id].table
147
172
  if df_probe.empty:
148
173
  print(
149
- f"above is meta info, failed to find the probe info. 看一下是不是在单独的文件中包含了probe信息"
174
+ f"Warning: cannot find the probe info. 看一下是不是在单独的文件中包含了probe信息"
150
175
  )
151
- return get_meta(geo, dataset, verbose=True)
176
+ display(f"🔗: https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc={platform_id}")
177
+ return get_meta(geo, dataset, verbose=verbose)
152
178
  if verbose:
153
179
  print(f"columns in the probe table: \n{sorted(df_probe.columns.tolist())}")
154
180
  return df_probe
@@ -181,19 +207,25 @@ def get_expression_data(geo: dict, dataset: str = "GSE25097") -> pd.DataFrame:
181
207
  return expression_values
182
208
 
183
209
 
184
- def get_data(geo: dict, dataset: str = "GSE25097", verbose=True):
210
+ def get_data(geo: dict, dataset: str = "GSE25097", verbose=False):
211
+ print(f"\n\ndataset: {dataset}\n")
185
212
  # get probe info
186
213
  df_probe = get_probe(geo, dataset=dataset, verbose=False)
187
214
  # get expression values
188
215
  df_expression = get_expression_data(geo, dataset=dataset)
189
- print(
190
- f"df_expression.shape: {df_expression.shape} \ndf_probe.shape: {df_probe.shape}"
191
- )
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
192
221
  if any([df_probe.empty, df_expression.empty]):
193
222
  print(
194
- f"above is meta info, failed to find the probe info. 看一下是不是在单独的文件中包含了probe信息"
223
+ f"got empty values, check the probe info. 看一下是不是在单独的文件中包含了probe信息"
195
224
  )
196
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
+ )
197
229
  df_exp = pd.merge(
198
230
  df_probe,
199
231
  df_expression,
@@ -237,14 +269,39 @@ def get_data(geo: dict, dataset: str = "GSE25097", verbose=True):
237
269
  df_exp.set_index(col_gene_symbol, inplace=True)
238
270
  df_exp = df_exp[col_gsm].T # transpose, so that could add meta info
239
271
 
240
- df_merged = ips.df_merge(df_meta, df_exp)
272
+ df_merged = ips.df_merge(df_meta, df_exp,use_index=True)
273
+
274
+ print(
275
+ f"\ndataset:'{dataset}' n_sample = {df_merged.shape[0]}, n_gene={df_exp.shape[1]}"
276
+ )
241
277
  if verbose:
242
- print(
243
- f"\ndataset:'{dataset}' n_sample = {df_merged.shape[0]}, n_gene={df_exp.shape[1]}"
244
- )
245
278
  display(df_merged.sample(5))
246
279
  return df_merged
247
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"
248
305
 
249
306
  def split_at_lower_upper(lst):
250
307
  """
@@ -261,6 +318,13 @@ def split_at_lower_upper(lst):
261
318
  return lst[: i + 1], lst[i + 1 :]
262
319
  return lst, []
263
320
 
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]]))
264
328
 
265
329
  def add_condition(
266
330
  data: pd.DataFrame,
@@ -305,7 +369,7 @@ def add_condition(
305
369
  lambda x: by_not_name if not by_not in x else by_name
306
370
  )
307
371
  if verbose:
308
- display(data)
372
+ display(data.sample(5))
309
373
  if not inplace:
310
374
  return data
311
375
 
@@ -370,13 +434,13 @@ def add_condition_multi(
370
434
 
371
435
  # Display the updated DataFrame if verbose is True
372
436
  if verbose:
373
- display(data)
437
+ display(data.sample(5))
374
438
 
375
439
  if not inplace:
376
440
  return data
377
441
 
378
442
  def clean_dataset(
379
- data: pd.DataFrame, dataset: str = "GSE25097", condition: str = "condition",sep="///"
443
+ data: pd.DataFrame, dataset: str = None, condition: str = "condition",sep="///"
380
444
  ):
381
445
  """
382
446
  #* it has been involved in bio.batch_effects(), but default: False
@@ -386,6 +450,14 @@ def clean_dataset(
386
450
  4. add the 'condition' and 'dataset info' to the columns
387
451
  5. set genes as index
388
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}")
389
461
  #! (4.1) clean data set and prepare super_datasets
390
462
  # df_data_2, 左边的列是meta,右边的列是gene_symbol
391
463
  col_gene = split_at_lower_upper(data.columns.tolist())[1][0]
@@ -420,7 +492,7 @@ def clean_dataset(
420
492
  return df_gene
421
493
 
422
494
  def batch_effect(
423
- data: list = "[df_gene_1, df_gene_2, df_gene_3]",
495
+ data: list = "[df_gene_1, df_gene_2, df_gene_3]", # index (genes),columns(samples)
424
496
  datasets: list = ["GSE25097", "GSE62232", "GSE65372"],
425
497
  clean_data:bool=False, # default, not do data cleaning
426
498
  top_genes:int=10,# only for plotting
@@ -510,4 +582,869 @@ def batch_effect(
510
582
 
511
583
  def get_common_genes(elment1, elment2):
512
584
  common_genes=ips.shared(elment1, elment2)
513
- return common_genes
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)