exprmat 0.1.8__tar.gz → 0.1.9__tar.gz

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.
Files changed (113) hide show
  1. {exprmat-0.1.8 → exprmat-0.1.9}/PKG-INFO +1 -1
  2. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/geneset.py +6 -2
  3. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/descriptive/gse.py +37 -7
  4. exprmat-0.1.9/exprmat/plotting/gse.py +323 -0
  5. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reader/experiment.py +61 -1
  6. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat.egg-info/PKG-INFO +1 -1
  7. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat.egg-info/SOURCES.txt +1 -0
  8. {exprmat-0.1.8 → exprmat-0.1.9}/setup.py +1 -1
  9. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/__init__.py +0 -0
  10. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/ansi.py +0 -0
  11. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/clustering/__init__.py +0 -0
  12. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/clustering/leiden.py +0 -0
  13. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/clustering/rogue.py +0 -0
  14. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/clustering/spectral.py +0 -0
  15. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/clustering/summary.py +0 -0
  16. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/clustering/utils.py +0 -0
  17. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/cnv/__init__.py +0 -0
  18. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/cnv/cnvscore.py +0 -0
  19. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/cnv/infercnv.py +0 -0
  20. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/configuration.py +0 -0
  21. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/__init__.py +0 -0
  22. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/delim.py +0 -0
  23. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/finders.py +0 -0
  24. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/gff.py +0 -0
  25. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/entrez.tsv.gz +0 -0
  26. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/all.gmt +0 -0
  27. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/bp.gmt +0 -0
  28. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/cancer-modules.gmt +0 -0
  29. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/cancer-neighborhoods.gmt +0 -0
  30. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/cancer.gmt +0 -0
  31. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/cc.gmt +0 -0
  32. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/chemical-perturb.gmt +0 -0
  33. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/hallmark.gmt +0 -0
  34. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/human-phenotype-ontology.gmt +0 -0
  35. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/immune-perturb.gmt +0 -0
  36. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/mf.gmt +0 -0
  37. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/microrna.gmt +0 -0
  38. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/oncogenic.gmt +0 -0
  39. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/pathways.gmt +0 -0
  40. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/positional.gmt +0 -0
  41. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/single-cell.gmt +0 -0
  42. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/transcript-factors.gmt +0 -0
  43. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genesets/vaccine.gmt +0 -0
  44. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/genome.tsv.gz +0 -0
  45. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/mapping-ensembl.pkl +0 -0
  46. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/mapping-name.pkl +0 -0
  47. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/hsa/taxa +0 -0
  48. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/entrez.tsv.gz +0 -0
  49. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/all.gmt +0 -0
  50. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/biocarta.gmt +0 -0
  51. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/bp.gmt +0 -0
  52. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/cc.gmt +0 -0
  53. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/chemical-perturb.gmt +0 -0
  54. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/hallmark.gmt +0 -0
  55. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/m2.gmt +0 -0
  56. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/markers.gmt +0 -0
  57. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/mf.gmt +0 -0
  58. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/microrna.gmt +0 -0
  59. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/mpt.gmt +0 -0
  60. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/positional.gmt +0 -0
  61. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/reactome.gmt +0 -0
  62. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/transcript-factors.gmt +0 -0
  63. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genesets/wikipathway.gmt +0 -0
  64. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/genome.tsv.gz +0 -0
  65. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/mapping-ensembl.pkl +0 -0
  66. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/mapping-name.pkl +0 -0
  67. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/mmu/taxa +0 -0
  68. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/private.py +0 -0
  69. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/data/ranges.py +0 -0
  70. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/descriptive/__init__.py +0 -0
  71. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/descriptive/de.py +0 -0
  72. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/descriptive/kde.py +0 -0
  73. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/plotting/__init__.py +0 -0
  74. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/plotting/cnv.py +0 -0
  75. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/plotting/de.py +0 -0
  76. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/plotting/expression.py +0 -0
  77. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/plotting/palettes.py +0 -0
  78. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/plotting/summary.py +0 -0
  79. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/__init__.py +0 -0
  80. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/doublets/__init__.py +0 -0
  81. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/doublets/composite.py +0 -0
  82. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/doublets/scrublet.py +0 -0
  83. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/filter.py +0 -0
  84. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/integrate.py +0 -0
  85. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/linear.py +0 -0
  86. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/normal.py +0 -0
  87. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/plot.py +0 -0
  88. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/qc.py +0 -0
  89. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/sctransform/__init__.py +0 -0
  90. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/sctransform/estimate.py +0 -0
  91. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/sctransform/ksmooth.py +0 -0
  92. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/sctransform/residual.py +0 -0
  93. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/sctransform/transform.py +0 -0
  94. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/sparse.py +0 -0
  95. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/preprocessing/uniform.py +0 -0
  96. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reader/__init__.py +0 -0
  97. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reader/matcher.py +0 -0
  98. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reader/metadata.py +0 -0
  99. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/__init__.py +0 -0
  100. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/forceatlas.py +0 -0
  101. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/mde.py +0 -0
  102. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/nn.py +0 -0
  103. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/pca.py +0 -0
  104. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/plot.py +0 -0
  105. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/pumap.py +0 -0
  106. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/tsne.py +0 -0
  107. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/reduction/umap.py +0 -0
  108. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat/utils.py +0 -0
  109. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat.egg-info/dependency_links.txt +0 -0
  110. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat.egg-info/not-zip-safe +0 -0
  111. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat.egg-info/requires.txt +0 -0
  112. {exprmat-0.1.8 → exprmat-0.1.9}/exprmat.egg-info/top_level.txt +0 -0
  113. {exprmat-0.1.8 → exprmat-0.1.9}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: exprmat
3
- Version: 0.1.8
3
+ Version: 0.1.9
4
4
  Summary: routines to process expression matrices
5
5
  Home-page: https://github.com/yang-z-03/exprmat
6
6
  Author: Zheng Yang
@@ -28,8 +28,7 @@ def get_genesets(taxa, name, identifier = 'entrez'):
28
28
  lines = gfile.read().splitlines()
29
29
 
30
30
  gene_set = {}
31
- import tqdm
32
- for line in tqdm.tqdm(lines, ncols = 80):
31
+ for line in lines:
33
32
 
34
33
  if len(line.strip()) == 0: continue
35
34
  if line.startswith('#'): continue
@@ -53,6 +52,9 @@ def get_genesets(taxa, name, identifier = 'entrez'):
53
52
 
54
53
  def translate_id(taxa, genes, idfrom = 'entrez', idto = 'ugene', keep_nones = True):
55
54
 
55
+ if not taxa in genome.keys():
56
+ get_genome(taxa)
57
+
56
58
  # setup the conversion table cache
57
59
  if not 'conversion' in genome[taxa].keys():
58
60
 
@@ -86,6 +88,8 @@ def translate_id(taxa, genes, idfrom = 'entrez', idto = 'ugene', keep_nones = Tr
86
88
 
87
89
  else:
88
90
  result = []
91
+ froms = gtable[idfrom].tolist()
92
+ tos = gtable[idto].tolist()
89
93
  for x in genes:
90
94
  if x in froms:
91
95
  t = tos[froms.index(x)]
@@ -45,14 +45,44 @@ def gse(
45
45
 
46
46
  import gseapy as gp
47
47
  import pandas as pd
48
+
49
+ prernk = pd.DataFrame({
50
+ 'gene': translate_id(taxa, names, 'ugene', identifier, keep_nones = True),
51
+ 'lfc': input_gnames['lfc'].tolist()
52
+ })
53
+
54
+ prernk = prernk.loc[~ prernk['gene'].duplicated(), :].copy()
55
+ prernk = prernk.loc[~ prernk['gene'].isna(), :].copy()
48
56
  gsea = gp.prerank(
49
- pd.DataFrame({
50
- 'gene': translate_id(taxa, names, 'ugene', identifier, keep_nones = False),
51
- 'lfc': input_gnames['lfc'].tolist()
52
- }),
57
+ rnk = prernk,
53
58
  gene_sets = get_genesets(taxa = taxa, name = gene_sets, identifier = identifier)
54
59
  )
55
60
 
56
- # adata.uns[key_added] = gsea.results
57
- # adata.uns[key_added + '.table'] = gsea.res2d
58
- return gsea
61
+ adata.uns[key_added] = {
62
+ 'config': {
63
+ 'module': gsea.module,
64
+ 'ranking.key': np.array(gsea.ranking.index.tolist()),
65
+ 'ranking.value': np.array(gsea.ranking.values),
66
+ 'seed': gsea.seed,
67
+ 'negative': gsea.pheno_neg,
68
+ 'positive': gsea.pheno_pos
69
+ },
70
+ 'results': {}
71
+ }
72
+
73
+ for k in gsea.results.keys():
74
+ adata.uns[key_added]['results'][k] = {
75
+ 'name': gsea.results[k]['name'],
76
+ 'es': gsea.results[k]['es'],
77
+ 'res': np.array(gsea.results[k]['RES']),
78
+ 'nes': gsea.results[k]['nes'],
79
+ 'p': gsea.results[k]['pval'],
80
+ 'fdr': gsea.results[k]['fdr'],
81
+ 'fwerp': gsea.results[k]['fwerp'],
82
+ 'tag': gsea.results[k]['tag %'],
83
+ 'lead': np.array(gsea.results[k]['lead_genes'].split(';'), dtype = str),
84
+ 'match': np.array(gsea.results[k]['matched_genes'].split(';'), dtype = 'str'),
85
+ 'hits': np.array(gsea.results[k]['hits'])
86
+ }
87
+
88
+ pass
@@ -0,0 +1,323 @@
1
+
2
+ import sys
3
+ import operator
4
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ import matplotlib.pyplot as plt
10
+ import matplotlib.transforms as transforms
11
+ from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
12
+ from matplotlib.figure import Figure
13
+ from matplotlib.colors import Normalize
14
+
15
+ from exprmat.ansi import error
16
+
17
+
18
+ class normalize_midpoint(Normalize):
19
+ def __init__(self, vmin=None, vmax=None, vcenter=None, clip=False):
20
+ self.vcenter = vcenter
21
+ Normalize.__init__(self, vmin, vmax, clip)
22
+
23
+ def __call__(self, value, clip = None):
24
+ x, y = [self.vmin, self.vcenter, self.vmax], [0, 0.5, 1]
25
+ return np.ma.masked_array(np.interp(value, x, y, left = -np.inf, right = np.inf))
26
+
27
+ def inverse(self, value):
28
+ y, x = [self.vmin, self.vcenter, self.vmax], [0, 0.5, 1]
29
+ return np.interp(value, x, y, left = -np.inf, right = np.inf)
30
+
31
+
32
+ def zscore(data2d: pd.DataFrame, axis: Optional[int] = 0):
33
+
34
+ if axis is None:
35
+ # normalized to mean and std using entire matrix
36
+ # z_scored = (data2d - data2d.values.mean()) / data2d.values.std(ddof=1)
37
+ return data2d
38
+
39
+ assert axis in [0, 1]
40
+ z_scored = data2d.apply(
41
+ lambda x: (x - x.mean()) / x.std(ddof=1), axis = operator.xor(1, axis)
42
+ )
43
+
44
+ return z_scored
45
+
46
+
47
+ class nesplot:
48
+
49
+ def __init__(
50
+ self,
51
+ term: str,
52
+ tag: Sequence[int],
53
+ runes: Sequence[float],
54
+ nes: float,
55
+ pval: float,
56
+ fdr: float,
57
+ rank_metric: Optional[Sequence[float]] = None,
58
+ pheno_pos: str = "",
59
+ pheno_neg: str = "",
60
+ color: Optional[str] = "#88C544",
61
+ figsize: Tuple[float, float] = (4, 4),
62
+ cmap: str = "seismic",
63
+ ax: Optional[plt.Axes] = None,
64
+ module = 'gsea',
65
+ title = None,
66
+ ** kwargs
67
+ ):
68
+
69
+ self._x = np.arange(len(runes))
70
+ self.rankings = None
71
+ self._zero_score_ind = None
72
+ self._z_score_label = None
73
+ self.color = color
74
+ self.module = module
75
+
76
+ if rank_metric is not None:
77
+ self.rankings = np.asarray(rank_metric)
78
+ self._zero_score_ind = np.abs(self.rankings).argmin()
79
+ self._z_score_label = str(self._zero_score_ind)
80
+
81
+ self.running_es = np.asarray(runes)
82
+
83
+ self.figsize = figsize
84
+ self.term = term
85
+ self.cmap = cmap
86
+
87
+ self._pos_label = pheno_pos
88
+ self._neg_label = pheno_neg
89
+ self._hit_indices = tag
90
+
91
+ if self.module == "ssgsea":
92
+ self._nes_label = "Enrichment Score: " + "{:.3f}".format(float(nes))
93
+ self._fdr_label = "False discovery rate: -"
94
+ self._pval_label = "p value: -"
95
+
96
+ else:
97
+ self._nes_label = "Normalized enrichment score: " + "{:.3f}".format(float(nes))
98
+ self._fdr_label = "False discovery rate: " + "{:.3f}".format(float(fdr))
99
+ self._pval_label = "p value: " + "{:.3f}".format(float(pval))
100
+
101
+ if ax is None:
102
+ if hasattr(sys, "ps1"):
103
+ # working inside python console, show figure
104
+ self.fig = plt.figure(figsize=self.figsize, facecolor = "white")
105
+ else:
106
+ # if working on command line, don't show figure
107
+ self.fig = Figure(figsize=self.figsize, facecolor = "white")
108
+ self._canvas = FigureCanvas(self.fig)
109
+
110
+ elif isinstance(ax, plt.Axes): self.fig = ax.figure
111
+ else: error("`ax` must be matplotlib axes.")
112
+ self.fig.suptitle(
113
+ self.term if title is None else title, fontsize = 11,
114
+ wrap = True, fontweight = "bold"
115
+ )
116
+
117
+
118
+ def axes_rank(self, rect):
119
+
120
+ ax1 = self.fig.add_axes(rect)
121
+ if self.module == "ssgsea":
122
+ ax1.fill_between(self._x, y1 = np.log(self.rankings), y2=0, color = "#C9D3DB")
123
+ ax1.set_ylabel("Ranked metric (log)", fontsize = 9)
124
+ else:
125
+ ax1.fill_between(self._x, y1=self.rankings, y2 = 0, color="#C9D3DB")
126
+ ax1.set_ylabel("Ranked metric", fontsize = 9)
127
+
128
+ ax1.text(
129
+ 0.05, 0.9,
130
+ self._pos_label,
131
+ color = "red",
132
+ horizontalalignment = "left",
133
+ verticalalignment = "top",
134
+ transform = ax1.transAxes,
135
+ )
136
+
137
+ ax1.text(
138
+ 0.95, 0.05,
139
+ self._neg_label,
140
+ color = "Blue",
141
+ horizontalalignment = "right",
142
+ verticalalignment = "bottom",
143
+ transform = ax1.transAxes,
144
+ )
145
+
146
+ # the x coords of this transformation are data, and the y coord are axes
147
+ trans1 = transforms.blended_transform_factory(ax1.transData, ax1.transAxes)
148
+ ax1.vlines(
149
+ self._zero_score_ind, 0, 1, linewidth = 0.5,
150
+ transform = trans1, linestyles = "--", color = "grey",
151
+ )
152
+
153
+ hap = self._zero_score_ind / max(self._x)
154
+ if hap < 0.25: ha = "left"
155
+ elif hap > 0.75: ha = "right"
156
+ else: ha = "center"
157
+ ax1.text(
158
+ hap, 0.5, self._z_score_label,
159
+ horizontalalignment = ha, verticalalignment = "center",
160
+ transform = ax1.transAxes, fontsize = 9,
161
+ )
162
+
163
+ ax1.set_xlabel("Gene ranking", fontsize = 9)
164
+ ax1.spines["top"].set_visible(False)
165
+ ax1.tick_params(
166
+ axis = "both", which = "both",
167
+ top = False, right = False, left = False, labelsize = 9
168
+ )
169
+ ax1.locator_params(axis = "y", nbins = 5)
170
+ ax1.yaxis.set_major_formatter(
171
+ plt.FuncFormatter(lambda tick_loc, tick_num: "{:.1f}".format(tick_loc))
172
+ )
173
+
174
+
175
+ def axes_hits(self, rect, bottom: bool = False):
176
+
177
+ ax2 = self.fig.add_axes(rect)
178
+ # the x coords of this transformation are data, and the y coord are axes
179
+ trans2 = transforms.blended_transform_factory(ax2.transData, ax2.transAxes)
180
+ # to make axes shared with same x cooridincates, make the vlines same ranges to x
181
+ ax2.vlines(
182
+ [self._x[0], self._x[-1]],
183
+ 0, 1, linewidth = 0.5, transform = trans2,
184
+ color = "white", alpha = 0,
185
+ )
186
+
187
+ # add hits line
188
+ ax2.vlines(self._hit_indices, 0, 1, linewidth = 0.5, transform = trans2, color = "black")
189
+
190
+ ax2.tick_params(
191
+ axis = "both", which = "both",
192
+ bottom = bottom, top = False, right = False, left = False,
193
+ labelbottom = bottom, labelleft = False,
194
+ )
195
+
196
+ if bottom:
197
+ ax2.set_xlabel("Gene ranking", fontsize = 9)
198
+ ax2.spines["bottom"].set_visible(True)
199
+
200
+
201
+ def axes_cmap(self, rect):
202
+
203
+ # center color map at midpoint = 0
204
+ mat = self.rankings
205
+ if self.rankings is None:
206
+ mat = self.running_es
207
+ vmin = np.percentile(mat.min(), 2)
208
+ vmax = np.percentile(mat.max(), 98)
209
+ midnorm = normalize_midpoint(vmin = vmin, vcenter = 0, vmax = vmax)
210
+
211
+ # colormap
212
+ ax3 = self.fig.add_axes(rect)
213
+ ax3.pcolormesh(
214
+ mat[np.newaxis, :],
215
+ rasterized = True,
216
+ norm = midnorm,
217
+ cmap = self.cmap,
218
+ )
219
+
220
+ ax3.spines["bottom"].set_visible(False)
221
+ ax3.tick_params(
222
+ axis = "both", which = "both",
223
+ bottom = False, top = False, right = False, left = False,
224
+ labelbottom = False, labelleft = False,
225
+ )
226
+
227
+
228
+ def axes_stat(self, rect):
229
+
230
+ # enrichment score plot
231
+ ax4 = self.fig.add_axes(rect)
232
+ ax4.plot(self._x, self.running_es, linewidth = 4, color = self.color)
233
+ ax4.text(0.02, 0.05, self._fdr_label, transform = ax4.transAxes, fontsize = 9)
234
+ ax4.text(0.02, 0.15, self._pval_label, transform = ax4.transAxes, fontsize = 9)
235
+ ax4.text(0.02, 0.25, self._nes_label, transform = ax4.transAxes, fontsize = 9)
236
+
237
+ # the y coords of this transformation are data, and the x coord are axes
238
+ trans4 = transforms.blended_transform_factory(ax4.transAxes, ax4.transData)
239
+ ax4.hlines(0, 0, 1, linewidth = 1, transform = trans4, color = "grey")
240
+ ax4.set_ylabel("Enrichment score", fontsize = 9)
241
+
242
+ ax4.tick_params(
243
+ axis = "both", which = "both",
244
+ bottom = False, top = False, right = False, labelbottom = False,
245
+ labelsize = 9
246
+ )
247
+ ax4.locator_params(axis = "y", nbins = 5)
248
+ ax4.yaxis.set_major_formatter(
249
+ plt.FuncFormatter(lambda tick_loc, tick_num: "{:.1f}".format(tick_loc))
250
+ )
251
+ self.ax = ax4
252
+
253
+
254
+ def add_axes(self):
255
+
256
+ left = 0.1
257
+ width = 0.8
258
+ bottom = 0.1
259
+ height = 0
260
+
261
+ stat_height_ratio = 0.4
262
+ hits_height_ratio = 0.05
263
+ cmap_height_ratio = 0.05
264
+ rank_height_ratio = 0.3
265
+
266
+ if self.rankings is None:
267
+ rank_height_ratio = 0
268
+ cmap_height_ratio = 0
269
+
270
+ base = 0.8 / (
271
+ stat_height_ratio
272
+ + hits_height_ratio
273
+ + cmap_height_ratio
274
+ + rank_height_ratio
275
+ )
276
+
277
+ if self.rankings is not None:
278
+ height = rank_height_ratio * base
279
+ self.axes_rank([left, bottom, width, height])
280
+ bottom += height
281
+ height = cmap_height_ratio * base
282
+ self.axes_cmap([left, bottom, width, height])
283
+ bottom += height
284
+
285
+ height = hits_height_ratio * base
286
+ self.axes_hits(
287
+ [left, bottom, width, height], bottom=False if bottom > 0.1 else True
288
+ )
289
+
290
+ bottom += height
291
+ height = stat_height_ratio * base
292
+ self.axes_stat([left, bottom, width, height])
293
+
294
+
295
+ def esplot(
296
+ adata, *, gsea, terms, figsize = (4, 4), title = None,
297
+ colors = None, show_ranking = True, sample_name = None
298
+ ):
299
+
300
+ gsdict = adata.uns[gsea]['results'][terms]
301
+ ranking = pd.DataFrame({
302
+ 'gene_names': adata.uns[gsea]['config']['ranking.key'],
303
+ 'value': adata.uns[gsea]['config']['ranking.value']
304
+ })
305
+
306
+ ranking.set_index('gene_names')
307
+ g = nesplot(
308
+ term = terms,
309
+ tag = gsdict["hits"],
310
+ rank_metric = ranking['value'] if (show_ranking) else None,
311
+ runes = gsdict["res"],
312
+ nes = gsdict["nes"],
313
+ pval = gsdict["p"],
314
+ fdr = gsdict["fdr"],
315
+ pheno_pos = '', # adata.uns[gsea]['config']['positive'],
316
+ pheno_neg = '', # adata.uns[gsea]['config']['negative'],
317
+ color = colors,
318
+ title = title,
319
+ figsize = figsize,
320
+ )
321
+
322
+ g.add_axes()
323
+ return g.fig
@@ -364,6 +364,8 @@ class experiment:
364
364
 
365
365
  if not run_on_splits:
366
366
  figure = func(self.mudata['rna'], 'integrated', **kwargs)
367
+ import warnings
368
+ warnings.filterwarnings('ignore')
367
369
  figure.tight_layout()
368
370
  return figure
369
371
 
@@ -493,7 +495,10 @@ class experiment:
493
495
  x if str(x) != 'nan' else y
494
496
  for x, y in zip(fromslot, toslot)
495
497
  ]
498
+
496
499
  info(f'merged {annotation} to {to} in current dataset.')
500
+ print(self.mudata[slot].obs[to].value_counts())
501
+ self.mudata[slot].obs[to] = self.mudata[slot].obs[to].astype('category')
497
502
 
498
503
  # if todf is another subset.
499
504
  elif isinstance(todf, str) and os.path.exists(
@@ -510,7 +515,10 @@ class experiment:
510
515
  x if str(x) != 'nan' else y
511
516
  for x, y in zip(fromslot, toslot)
512
517
  ]
518
+
513
519
  info(f'merged {annotation} to {to} in current dataset.')
520
+ print(self.mudata[slot].obs[to].value_counts())
521
+ self.mudata[slot].obs[to] = self.mudata[slot].obs[to].astype('category')
514
522
 
515
523
  else:
516
524
 
@@ -534,6 +542,8 @@ class experiment:
534
542
 
535
543
  del mdata[slot].obs['.temp']
536
544
  info(f'updated {annotation} to {to} in {todf}.h5mu')
545
+ print(mdata[slot].obs[to].value_counts())
546
+ mdata[slot].obs[to] = mdata[slot].obs[to].astype('category')
537
547
  mdata.write_h5mu(os.path.join(self.directory, 'subsets', todf + '.h5mu'))
538
548
 
539
549
  elif isinstance(todf, str) and todf == 'integrated':
@@ -557,6 +567,8 @@ class experiment:
557
567
 
558
568
  del mdata[slot].obs['.temp']
559
569
  info(f'updated {annotation} to {to} in main integrated.h5mu')
570
+ print(mdata[slot].obs[to].value_counts())
571
+ mdata[slot].obs[to] = mdata[slot].obs[to].astype('category')
560
572
  mdata.write_h5mu(os.path.join(self.directory, 'integrated.h5mu'))
561
573
 
562
574
 
@@ -1221,6 +1233,17 @@ class experiment:
1221
1233
  def rna_plot_cnv_matrix(adata, sample_name, **kwargs):
1222
1234
  from exprmat.plotting.cnv import chromosome_heatmap
1223
1235
  return chromosome_heatmap(adata, sample_name = sample_name, **kwargs)
1236
+
1237
+
1238
+ @staticmethod
1239
+ def rna_plot_gsea_running_es(
1240
+ adata, sample_name, gsea, terms, figsize = (4, 4), colors = None, title = None, **kwargs
1241
+ ):
1242
+ from exprmat.plotting.gse import esplot
1243
+ return esplot(
1244
+ adata, sample_name = sample_name, title = title,
1245
+ gsea = gsea, terms = terms, figsize = figsize, colors = colors, **kwargs
1246
+ )
1224
1247
 
1225
1248
 
1226
1249
  # wrapper functions
@@ -1404,11 +1427,14 @@ class experiment:
1404
1427
  fig.tight_layout()
1405
1428
  return fig
1406
1429
 
1430
+ def plot_rna_gsea_running_es(self, run_on_samples = False, **kwargs):
1431
+ return self.plot_for_rna(run_on_samples, experiment.rna_plot_gsea_running_es, **kwargs)
1432
+
1407
1433
 
1408
1434
  # accessor wrappers
1409
1435
 
1410
1436
  def get_rna_markers(
1411
- self, de_slot = 'markers', group_name = None,
1437
+ self, de_slot = 'markers', group_name = None, max_q = None,
1412
1438
  min_pct = 0.25, max_pct_reference = 0.75, min_lfc = 1, max_lfc = 100, remove_zero_pval = False
1413
1439
  ):
1414
1440
  self.check_merged('rna')
@@ -1431,9 +1457,43 @@ class experiment:
1431
1457
  tab = tab[tab['lfc'] <= max_lfc]
1432
1458
  if remove_zero_pval:
1433
1459
  tab = tab[~ np.isinf(tab['log10.q'].to_numpy())]
1460
+ if max_q is not None and 'q' in tab.columns:
1461
+ tab = tab[tab['q'] <= max_q]
1434
1462
 
1435
1463
  tab = tab.sort_values(by = ['scores'], ascending = False)
1436
1464
  return tab
1465
+
1466
+
1467
+ def get_rna_gsea(self, gsea_slot = 'gsea', max_fdr = 1.00, max_p = 0.05):
1468
+
1469
+ df = {
1470
+ 'name': [],
1471
+ 'es': [],
1472
+ 'nes': [],
1473
+ 'p': [],
1474
+ 'fwerp': [],
1475
+ 'fdr': [],
1476
+ 'tag': []
1477
+ }
1478
+
1479
+ for gs in self.mudata['rna'].uns[gsea_slot]['results'].keys():
1480
+ data = self.mudata['rna'].uns[gsea_slot]['results'][gs]
1481
+ df['name'].append(gs)
1482
+ df['es'].append(data['es'])
1483
+ df['nes'].append(data['nes'])
1484
+ df['p'].append(data['p'])
1485
+ df['fwerp'].append(data['fwerp'])
1486
+ df['fdr'].append(data['fdr'])
1487
+ df['tag'].append(data['tag'])
1488
+
1489
+ df = pd.DataFrame(df)
1490
+ if max_fdr is not None:
1491
+ df = df[df['fdr'] <= max_fdr]
1492
+ if max_p is not None:
1493
+ df = df[df['p'] <= max_p]
1494
+
1495
+ df.sort_values(['p'])
1496
+ return df
1437
1497
 
1438
1498
 
1439
1499
  def save(self, fdir = None, save_samples = True):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: exprmat
3
- Version: 0.1.8
3
+ Version: 0.1.9
4
4
  Summary: routines to process expression matrices
5
5
  Home-page: https://github.com/yang-z-03/exprmat
6
6
  Author: Zheng Yang
@@ -76,6 +76,7 @@ exprmat/plotting/__init__.py
76
76
  exprmat/plotting/cnv.py
77
77
  exprmat/plotting/de.py
78
78
  exprmat/plotting/expression.py
79
+ exprmat/plotting/gse.py
79
80
  exprmat/plotting/palettes.py
80
81
  exprmat/plotting/summary.py
81
82
  exprmat/preprocessing/__init__.py
@@ -3,7 +3,7 @@ from setuptools import setup, find_packages
3
3
 
4
4
  setup(
5
5
  name = 'exprmat',
6
- version = '0.1.8',
6
+ version = '0.1.9',
7
7
  description = 'routines to process expression matrices',
8
8
  url = 'https://github.com/yang-z-03/exprmat',
9
9
  author = 'Zheng Yang',
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes