pilotpy 2.0.12__tar.gz → 2.0.14__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 (25) hide show
  1. {pilotpy-2.0.12 → pilotpy-2.0.14}/PKG-INFO +2 -2
  2. {pilotpy-2.0.12 → pilotpy-2.0.14}/README.md +1 -1
  3. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/__init__.py +1 -1
  4. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/plot/ploting.py +67 -0
  5. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/tools/Trajectory.py +198 -14
  6. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy.egg-info/PKG-INFO +2 -2
  7. {pilotpy-2.0.12 → pilotpy-2.0.14}/setup.py +1 -1
  8. {pilotpy-2.0.12 → pilotpy-2.0.14}/LICENSE +0 -0
  9. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/pl.py +0 -0
  10. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/plot/__init__.py +0 -0
  11. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/plot/curve_activity.py +0 -0
  12. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/plot/gene_selection_analysis.py +0 -0
  13. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/plot/pseudobulk_DE_analysis.py +0 -0
  14. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/tl.py +0 -0
  15. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/tools/Cell_gene_selection.py +0 -0
  16. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/tools/Gene_cluster_specific.py +0 -0
  17. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/tools/Gene_cluster_specific_functions.py +0 -0
  18. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/tools/__init__.py +0 -0
  19. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy/tools/patients_sub_clustering.py +0 -0
  20. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy.egg-info/SOURCES.txt +0 -0
  21. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy.egg-info/dependency_links.txt +0 -0
  22. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy.egg-info/requires.txt +0 -0
  23. {pilotpy-2.0.12 → pilotpy-2.0.14}/pilotpy.egg-info/top_level.txt +0 -0
  24. {pilotpy-2.0.12 → pilotpy-2.0.14}/setup.cfg +0 -0
  25. {pilotpy-2.0.12 → pilotpy-2.0.14}/test/test_pilot.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pilotpy
3
- Version: 2.0.12
3
+ Version: 2.0.14
4
4
  Summary: PatIent Level analysis with Optimal Transport (PILOT)
5
5
  Home-page: https://github.com/CostaLab/PILOT
6
6
  Author: Mehdi Joodaki
@@ -50,7 +50,7 @@ Although clinical applications represent the next challenge in single-cell genom
50
50
  ![plot](./img/plot.png)
51
51
 
52
52
 
53
- Current version for PILOT is 2.0.12
53
+ Current version for PILOT is 2.0.14
54
54
 
55
55
  ## Installation
56
56
  The easiest way to install PILOT and the required packages is using the following way:
@@ -7,7 +7,7 @@ Although clinical applications represent the next challenge in single-cell genom
7
7
  ![plot](./img/plot.png)
8
8
 
9
9
 
10
- Current version for PILOT is 2.0.12
10
+ Current version for PILOT is 2.0.14
11
11
 
12
12
  ## Installation
13
13
  The easiest way to install PILOT and the required packages is using the following way:
@@ -1,4 +1,4 @@
1
- __version__ = "2.0.12"
1
+ __version__ = "2.0.14"
2
2
  __author__ = 'Mehdi Joodaki'
3
3
  __credits__ = 'Institute for Computational Genomics'
4
4
 
@@ -2465,3 +2465,70 @@ def plot_stats_by_pattern(cluster_names: list = None,
2465
2465
  plt.show()
2466
2466
  plt.close()
2467
2467
 
2468
+
2469
+
2470
+
2471
+
2472
+
2473
+ def create_sample_grid(df, pattern, image_dir=' figures/', output_path="Results_PILOT/plots/sample_grid_cores.png",zoom=0.1,num_rows = 10):
2474
+ """
2475
+ Create a grid of sample images based on ordering in a DataFrame.
2476
+
2477
+ Args:
2478
+ df: DataFrame containing at least:
2479
+ - 'sampleID': unique sample identifiers
2480
+ - 'order': numerical ordering for sorting
2481
+ image_dir: Directory containing images (named as {sampleID}.png)
2482
+ output_path: Where to save the resulting grid
2483
+ """
2484
+ # Sort samples by the specified order
2485
+ sorted_df = df.sort_values('Time_score')
2486
+ sample_names = sorted_df['sampleID'].tolist()
2487
+
2488
+ # Calculate grid dimensions (10 rows, auto columns)
2489
+ num_samples = len(sample_names)
2490
+ num_rows = num_rows
2491
+ num_cols = math.ceil(num_samples / num_rows)
2492
+
2493
+ # Prepare figure
2494
+ fig, axes = plt.subplots(num_rows, num_cols,
2495
+ figsize=(num_cols * 2, num_rows * 2))
2496
+ axes = axes.flatten()
2497
+
2498
+ # Image loading function
2499
+ def get_image(path, zoom=zoom):
2500
+ if os.path.exists(path):
2501
+ return OffsetImage(plt.imread(path), zoom=zoom)
2502
+ return None
2503
+
2504
+ # Plot each sample
2505
+ for i, sample in enumerate(sample_names):
2506
+ img_path = os.path.join(image_dir, f"show_{sample}_{pattern}.png")
2507
+ ax = axes[i]
2508
+
2509
+ # Add image if exists
2510
+ img = get_image(img_path)
2511
+ if img:
2512
+ ab = AnnotationBbox(img, (0.5, 0.5),
2513
+ frameon=False,
2514
+ box_alignment=(0.5, 0.5))
2515
+ ax.add_artist(ab)
2516
+
2517
+ # Minimal labeling
2518
+ ax.set_title(sample, fontsize=6)
2519
+ ax.set_xticks([])
2520
+ ax.set_yticks([])
2521
+ ax.axis('off')
2522
+
2523
+ # Hide unused subplots
2524
+ for i in range(num_samples, len(axes)):
2525
+ axes[i].axis('off')
2526
+
2527
+
2528
+
2529
+ plt.tight_layout()
2530
+ fig.canvas.draw() # Force render
2531
+ plt.savefig(output_path, dpi=300, bbox_inches='tight')
2532
+ plt.show()
2533
+ plt.close()
2534
+ print(f"Saved grid to {output_path}")
@@ -38,7 +38,7 @@ clusters_col='cell_types',sample_col='sampleID',status='status',
38
38
  metric='cosine',
39
39
  regulizer=0.2,normalization=True,
40
40
  regularized='unreg',reg=0.1,
41
- res=0.01,steper=0.01,data_type='scRNA',return_sil_ari=False):
41
+ res=0.01,steper=0.01,data_type='scRNA',return_sil_ari=False,use_centroids=True):
42
42
 
43
43
  """
44
44
  Calculate the Wasserstein (W) distance among samples using PCA representation and clustering information.
@@ -69,6 +69,8 @@ clusters_col='cell_types',sample_col='sampleID',status='status',
69
69
  Stepper value for finding the best Leiden resolution, by default 0.01.
70
70
  data_type : str, optional
71
71
  Type of your data, e.g., 'scRNA' or 'pathomics', by default 'scRNA'.
72
+ use_centroids: str, optional,
73
+ Use centriod in Cost function.
72
74
  return_sil_ari : bool, optional
73
75
  Whether to return ARI (Adjusted Rand Index) or Silhouette score for assessing W distance effects, by default False.
74
76
 
@@ -95,7 +97,8 @@ clusters_col=clusters_col,sample_col=sample_col,status=status)
95
97
  normalization=normalization)
96
98
  adata.uns['proportions'] = proportions
97
99
 
98
- cost,cost_df= cost_matrix(annot,data,metric=metric)
100
+ #cost,cost_df= cost_matrix(annot,data,metric=metric)
101
+ cost,cost_df= cost_matrix(annot,data,metric=metric,use_centroids=use_centroids)
99
102
  adata.uns['cost'] = cost_df
100
103
 
101
104
  EMD,emd_df = wasserstein_d(proportions,cost/cost.max(),regularized=regularized,
@@ -254,8 +257,11 @@ def extract_data_anno_scRNA_from_h5ad(adata,emb_matrix='PCA',clusters_col='cell_
254
257
  global path_to_results
255
258
  data=adata.obsm[emb_matrix]
256
259
  col_add=[]
257
- for i in range(1,adata.obsm[emb_matrix].shape[1]+1):
258
- col_add.append('PCA_'+str(i))
260
+ #for i in range(1,adata.obsm[emb_matrix].shape[1]+1):
261
+ # col_add.append('PCA_'+str(i))
262
+
263
+ for i in range(adata.obsm[emb_matrix].shape[1]):
264
+ col_add.append(adata.obsm[emb_matrix].columns[i])
259
265
  data=pd.DataFrame(data,columns=col_add)
260
266
  data = data.reset_index(drop=True)
261
267
  annot=adata.obs[[clusters_col,sample_col,status]]
@@ -438,7 +444,7 @@ def Cluster_Representations(df, cell_col = 0, sample_col = 1,regulizer=0.2,norma
438
444
 
439
445
 
440
446
 
441
- def cost_matrix(annot,data,metric='cosine'):
447
+ def cost_matrix(annot,data,metric='cosine',use_centroids=True):
442
448
  """
443
449
  Compute the cost matrix to find distances between clusters/cell-types.
444
450
 
@@ -452,8 +458,13 @@ def cost_matrix(annot,data,metric='cosine'):
452
458
  PCA representations.
453
459
  path : str
454
460
  Path for saving the cost matrix.
461
+
462
+ use_centroids: str, optional
463
+ Use centriod in Cost function.
464
+
455
465
  metric : str
456
466
  Metric for calculating the distances between centroids.
467
+
457
468
 
458
469
  Returns
459
470
  -------
@@ -462,15 +473,19 @@ def cost_matrix(annot,data,metric='cosine'):
462
473
  cells = annot[annot.columns[0]].unique() # gets cells
463
474
  centroids = []
464
475
 
465
- for i in cells:
466
- centroids.append(list(data[annot[annot.columns[0]] == i].median(axis=0))) #get the centriod of each cluster
467
-
468
- dis_t = scipy.spatial.distance.pdist(centroids, metric = metric)
469
- dis = scipy.spatial.distance.squareform(dis_t, force ='no', checks = True)
470
- cost = pd.DataFrame.from_dict(dis).T
471
- cost.columns=annot.cell_type.unique()
472
- cost['cell_types']=annot.cell_type.unique()
473
- cost=cost.set_index('cell_types')
476
+ if use_centroids:
477
+ for i in cells:
478
+ centroids.append(list(data[annot[annot.columns[0]] == i].median(axis=0)))
479
+ else:
480
+ for i in cells:
481
+ centroids.append(list(data[annot[annot.columns[0]] == i].sum(axis=0)/(data[annot[annot.columns[0]] == i].sum(axis=0).sum())))
482
+
483
+ dis_t = scipy.spatial.distance.pdist(centroids, metric = metric)
484
+ dis = scipy.spatial.distance.squareform(dis_t, force ='no', checks = True)
485
+ cost = pd.DataFrame.from_dict(dis).T
486
+ cost.columns=annot.cell_type.unique()
487
+ cost['cell_types']=annot.cell_type.unique()
488
+ cost=cost.set_index('cell_types')
474
489
 
475
490
  return dis,cost
476
491
 
@@ -1724,3 +1739,172 @@ clusters_col=clusters_col,sample_col=sample_col,status=status)
1724
1739
  adata.uns['real_labels']=return_real_labels(annot)
1725
1740
 
1726
1741
 
1742
+
1743
+
1744
+
1745
+ def feature_importance(adata,
1746
+ feature_matrix,
1747
+ feature_names,
1748
+ width = 20,
1749
+ height = 35,
1750
+ xlim = 5,
1751
+ p_val = 1,
1752
+ plot_cell = True,
1753
+ point_size = 100,
1754
+ color_back = 'white',
1755
+ fontsize = 20,
1756
+ alpha = 1,
1757
+ cmap_proportions = 'viridis',
1758
+ cmap_heatmap = 'Blues',
1759
+ save_as_pdf = True,
1760
+ figsize = (12, 12),
1761
+ col_cluster = True,
1762
+ row_cluster = False, path='Results_PILOT/plots/'):
1763
+ """
1764
+ Order cells based on estimated time and visualize feature importance.
1765
+
1766
+ Parameters
1767
+ ----------
1768
+ adata : AnnData
1769
+ Annotated data matrix containing necessary data.
1770
+ feature_matrix : str
1771
+ name of the pd.DataFrame in the anndata uns slot containing the features to be analysed. Should be a dataframe of features x samples
1772
+ feature_names : str
1773
+ name of the list in the anndata uns slot containing the names of the features to be analysed (should correspond to feature_matrix)
1774
+ width : int, optional
1775
+ Width of the plot, by default 40.
1776
+ height : int, optional
1777
+ Height of the plot, by default 35.
1778
+ xlim : int, optional
1779
+ Limit for x-axis in the plot, by default 5.
1780
+ p_val : float, optional
1781
+ P-value for filtering the fitting models, by default 0.05.
1782
+ plot_cell : bool, optional
1783
+ Whether to plot the cell type importance, by default True.
1784
+ point_size : int, optional
1785
+ Size of points in the plot, by default 100.
1786
+ color_back : str, optional
1787
+ Background color of the plot, by default 'white'.
1788
+ fontsize : int, optional
1789
+ Font size for labels and annotations, by default 20.
1790
+ alpha : float, optional
1791
+ Transparency level for plotting, by default 1.
1792
+ cmap_proportions : str, optional
1793
+ Colormap for plotting proportions over time, by default 'viridis'.
1794
+ cmap_heatmap : str, optional
1795
+ Colormap for plotting heatmap, by default 'Blues_r'.
1796
+ save_as_pdf : bool, optional
1797
+ Whether to save the plot as PDF, by default False.
1798
+ figsize : tuple, optional
1799
+ Figure size of the heatmap (width, height) in inches, by default (12, 12).
1800
+ col_cluster : bool, optional
1801
+ Whether to cluster columns in the heatmap, by default True.
1802
+ row_cluster : bool, optional
1803
+ Whether to cluster rows in the heatmap, by default False.
1804
+
1805
+ path : str, optional
1806
+ The path to save the results and plots.
1807
+
1808
+ Returns
1809
+ -------
1810
+ None
1811
+ Visualizes and saves the cell type importance plot.
1812
+ """
1813
+
1814
+
1815
+ if not os.path.exists(path):
1816
+ os.makedirs(path)
1817
+ real_labels = adata.uns['real_labels']
1818
+ pseudotime = adata.uns['pseudotime']
1819
+ annot = adata.uns['annot']
1820
+ bins = adata.uns[feature_matrix]
1821
+ embedding_diff = adata.uns['embedding']
1822
+ cell_types_propo = bins
1823
+ patients_id = bins.keys()
1824
+ cell_types =adata.uns[feature_names]
1825
+ emd = embedding_diff
1826
+ labels = real_labels
1827
+ emd_dataframe = pd.DataFrame({'sampleID': list(patients_id),
1828
+ 'pseudotime': pseudotime,
1829
+ 'lables': list(labels)}, dtype = object)
1830
+ emd_dataframe_sort = emd_dataframe.sort_values('pseudotime', ascending = True)
1831
+ emd_dataframe_sort['pseudotime'] = np.arange(1, len(emd_dataframe) + 1, 1).tolist()
1832
+ pathies_cell_proportions = pd.DataFrame.from_dict(bins).T
1833
+ pathies_cell_proportions.columns = cell_types
1834
+
1835
+
1836
+ pathies_cell_proportions.index.name = 'sampleID'
1837
+
1838
+ ### got error slice(None, None, None)
1839
+ # df_join = pd.merge(emd_dataframe_sort['sampleID'], pathies_cell_proportions,
1840
+ # how='inner', on = 'sampleID')
1841
+ df_join = pathies_cell_proportions.loc[emd_dataframe_sort['sampleID']] ## same fix as before
1842
+ #df_join = df_join.set_index('sampleID')
1843
+ # Normalizing the proportions for heat map
1844
+ normalized_df = (df_join - df_join.min()) / (df_join.max() - df_join.min())
1845
+
1846
+ #Saving Heat map based on sorte pseuduscores of the Trajectory
1847
+
1848
+ #heatmaps_df(normalized_df[cell_types], row_cluster=row_cluster,
1849
+ # col_cluster = col_cluster, cmap = cmap_heatmap, figsize = figsize)
1850
+ #Building a model based on Regression and pseuduscores
1851
+ pathies_cell_proportions['Time_score'] = list(emd_dataframe['pseudotime'])
1852
+ pathies_cell_proportions = pathies_cell_proportions.sort_values('Time_score', ascending = True)
1853
+ pathies_cell_proportions['Time_score'] = np.arange(1, len(emd_dataframe) + 1, 1).tolist()
1854
+ pathies_cell_proportions = pathies_cell_proportions.reset_index()
1855
+ RNA_data = pd.DataFrame()
1856
+ RNA_data['label'] = pathies_cell_proportions['Time_score']
1857
+ RNA_target = np.transpose(pathies_cell_proportions.iloc[:, 1:len(adata.uns['coloc_names']) + 1])
1858
+ min_target = min(RNA_data['label'])
1859
+ max_target = max(RNA_data['label'])
1860
+ #sorted_best = fit_best_model_cell_types(RNA_target, RNA_data,min_target=min_target, max_target=max_target)
1861
+
1862
+
1863
+ sorted_best = fit_best_model(RNA_target, RNA_data, model_type = 'LinearRegression',
1864
+ max_iter_huber = 1, epsilon_huber = 1,
1865
+ pval_thr = p_val, modify_r2 = False)
1866
+
1867
+ if save_as_pdf:
1868
+ suffix = 'Features_Report.pdf'
1869
+ else:
1870
+ suffix = 'Features_Report.png'
1871
+
1872
+ if plot_cell:
1873
+
1874
+ with plt.rc_context():
1875
+ plot_best_matches_cell_types(RNA_target, RNA_data,pathies_cell_proportions,
1876
+ sorted_best, "Cell Proportion",
1877
+ min_target = min_target,
1878
+ max_target = max_target,
1879
+ num = len(sorted_best.keys()),
1880
+ width = width,
1881
+ height = height,
1882
+ xlim = xlim,
1883
+ point_size = point_size,
1884
+ color_back = color_back,
1885
+ fontsize = fontsize,
1886
+ alpha = alpha,
1887
+ cmap = cmap_proportions)
1888
+ plt.savefig(path + "/" + suffix)
1889
+
1890
+
1891
+ cellnames = list(sorted_best.keys())
1892
+ #return orders of samples based on the trejctory and selected cell-types
1893
+
1894
+
1895
+ if not os.path.exists(path + '/Features_Report'):
1896
+ os.makedirs(path + '/Features_Report')
1897
+
1898
+
1899
+ save_data(sorted_best,
1900
+ ['Cell name', 'Expression pattern', 'Slope', 'Fitted function',
1901
+ 'Intercept', 'Treat', 'Treat2', 'adjusted P-value', 'R-squared',
1902
+ 'mod_rsquared_adj'], path + '/Cell_type_Report/', 'Cells_Importance',
1903
+ p_val = p_val, pro = None)
1904
+
1905
+
1906
+
1907
+ adata.uns[feature_matrix+'_names'] = cellnames
1908
+ adata.uns[feature_matrix+'_orders'] = pathies_cell_proportions[['sampleID', 'Time_score']]
1909
+
1910
+
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pilotpy
3
- Version: 2.0.12
3
+ Version: 2.0.14
4
4
  Summary: PatIent Level analysis with Optimal Transport (PILOT)
5
5
  Home-page: https://github.com/CostaLab/PILOT
6
6
  Author: Mehdi Joodaki
@@ -50,7 +50,7 @@ Although clinical applications represent the next challenge in single-cell genom
50
50
  ![plot](./img/plot.png)
51
51
 
52
52
 
53
- Current version for PILOT is 2.0.12
53
+ Current version for PILOT is 2.0.14
54
54
 
55
55
  ## Installation
56
56
  The easiest way to install PILOT and the required packages is using the following way:
@@ -2,7 +2,7 @@ from setuptools import find_packages, setup
2
2
 
3
3
  setup(
4
4
  name='pilotpy',
5
- version='2.0.12',
5
+ version='2.0.14',
6
6
  author='Mehdi Joodaki',
7
7
  author_email='judakimehdi@gmail.com',
8
8
  url='https://github.com/CostaLab/PILOT',
File without changes
File without changes
File without changes
File without changes
File without changes