scfocus-sc 0.0.6__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Zeyu Fu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,254 @@
1
+ Metadata-Version: 2.4
2
+ Name: scfocus-sc
3
+ Version: 0.0.6
4
+ Summary: single cell reinforcement learning for focusing
5
+ Home-page: https://github.com/PeterPonyu/scfocus
6
+ Author: Zeyu Fu
7
+ Author-email: fuzeyu99@126.com
8
+ License: MIT
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: scanpy>=1.10.4
18
+ Requires-Dist: torch>=1.13.1
19
+ Requires-Dist: joblib>=1.2.0
20
+ Requires-Dist: tqdm>=4.64.1
21
+ Requires-Dist: streamlit>=1.24.0
22
+ Dynamic: author
23
+ Dynamic: author-email
24
+ Dynamic: classifier
25
+ Dynamic: description
26
+ Dynamic: description-content-type
27
+ Dynamic: home-page
28
+ Dynamic: license
29
+ Dynamic: license-file
30
+ Dynamic: requires-dist
31
+ Dynamic: requires-python
32
+ Dynamic: summary
33
+
34
+ <div align="center">
35
+ <a href="https://peterponyu.github.io/">
36
+ <img src="https://peterponyu.github.io/assets/badges/scfocus.svg" width="64" alt="ZF Lab · scfocus">
37
+ </a>
38
+ </div>
39
+
40
+ # scFocus
41
+
42
+ ## Overview
43
+
44
+ scFocus is a reinforcement-learning-based method for analyzing lineage branching in low-dimensional single-cell embeddings. It combines branch probabilities with unsupervised structure in the latent space to help characterize continuous cell-state transitions and related visualization workflows.
45
+
46
+ ## Graphical Abstract
47
+ <p align="center">
48
+ <img src="source/_static/Pattern.png" alt="Pattern Image" width="600"/>
49
+ </p>
50
+
51
+ ## Installation
52
+
53
+ [![PyPI](https://img.shields.io/pypi/v/scfocus-sc.svg?color=brightgreen&style=flat)](https://pypi.org/project/scfocus-sc/)
54
+
55
+ ### Requirements
56
+
57
+ - Python >= 3.9
58
+ - Required packages: `scanpy>=1.10.4`, `torch>=1.13.1`, `joblib>=1.2.0`, `tqdm>=4.64.1`, `streamlit>=1.24.0`
59
+
60
+ ### Install from PyPI
61
+
62
+ ``` bash
63
+ pip install scfocus-sc
64
+ ```
65
+
66
+ From version 0.0.6 the package is published on PyPI as `scfocus-sc`; the import name is still `scfocus`. The earlier `scfocus` project on PyPI stays at 0.0.5 and is no longer updated.
67
+
68
+ ### Install from source
69
+
70
+ ```bash
71
+ git clone https://github.com/PeterPonyu/scfocus.git
72
+ cd scfocus
73
+ pip install -e .
74
+ ```
75
+
76
+ ## Quick Start
77
+
78
+ Basic example to get started with scFocus:
79
+
80
+ ```python
81
+ import scanpy as sc
82
+ import scfocus
83
+
84
+ # Load your single-cell data
85
+ adata = sc.read_h5ad('your_data.h5ad')
86
+
87
+ # Preprocess: normalize, log-transform, and compute PCA
88
+ sc.pp.normalize_total(adata, target_sum=1e4)
89
+ sc.pp.log1p(adata)
90
+ sc.pp.highly_variable_genes(adata, n_top_genes=2000)
91
+ adata = adata[:, adata.var.highly_variable]
92
+ sc.pp.pca(adata)
93
+
94
+ # Compute UMAP embedding
95
+ sc.pp.neighbors(adata, n_neighbors=15)
96
+ sc.tl.umap(adata)
97
+
98
+ # Run scFocus analysis
99
+ embedding = adata.obsm['X_umap']
100
+ focus = scfocus.focus(embedding, n=6, pct_samples=0.01)
101
+ focus.meta_focusing(n=3)
102
+ focus.merge_fp2()
103
+
104
+ # Add focus probabilities to your AnnData object
105
+ adata.obsm['focus_probs'] = focus.mfp[0]
106
+ for i in range(focus.mfp[0].shape[1]):
107
+ adata.obs[f'Fate_{i}'] = focus.mfp[0][:, i]
108
+
109
+ # Visualize results
110
+ sc.pl.umap(adata, color=[f'Fate_{i}' for i in range(focus.mfp[0].shape[1])])
111
+ ```
112
+
113
+ ## Key Parameters
114
+
115
+ The `focus` class accepts the following key parameters:
116
+
117
+ - **f** (array-like): Latent space of the original data (e.g., UMAP or t-SNE coordinates)
118
+ - **n** (int, default=8): Number of parallel agents/branches to identify
119
+ - **pct_samples** (float, default=0.125): Percentage of samples used in each training step
120
+ - **max_steps** (int, default=5): Maximum steps per training episode
121
+ - **num_episodes** (int, default=1000): Number of training episodes
122
+ - **hidden_dim** (int, default=128): Hidden layer dimension for neural networks
123
+ - **res** (float, default=0.05): Resolution for merging similar focus patterns
124
+
125
+ For a complete list of parameters and their descriptions, see the [API documentation](https://scfocus.readthedocs.io/en/latest/).
126
+
127
+ ## Documentation
128
+
129
+ [![Documentation Status](https://readthedocs.org/projects/scfocus/badge/?version=latest)](https://scfocus.readthedocs.io/en/latest/?badge=latest)
130
+
131
+ Tutorials and API documentation are available at [https://scfocus.readthedocs.io/en/latest/](https://scfocus.readthedocs.io/en/latest/), including:
132
+
133
+ - Notebooks for different datasets
134
+ - Step-by-step tutorials
135
+ - API reference
136
+
137
+ ## Web Interface
138
+
139
+ scFocus provides an interactive web interface for data analysis.
140
+
141
+ ### Online Access
142
+
143
+ Access the hosted version at [scfocus.streamlit.app](https://scfocus.streamlit.app/).
144
+
145
+ ### Local Interface
146
+
147
+ Launch the local web interface:
148
+
149
+ ```bash
150
+ scfocus ui
151
+ ```
152
+
153
+ ### Using the Web Interface
154
+
155
+ 1. **Upload Data**: Support for `.h5ad` files or 10x Genomics format (matrix.mtx, features.tsv, barcodes.tsv)
156
+ 2. **Configure Parameters**:
157
+ - Number of highly variable genes (200-5000, default: 2000)
158
+ - Number of neighbors for UMAP (2-50, default: 15)
159
+ - Minimum distance for UMAP (0.0-2.0, default: 0.5)
160
+ - Number of branches (2-10, default: 6)
161
+ 3. **Process**: Click "Process" to run the analysis pipeline
162
+ 4. **Visualize**: View UMAP plots colored by cell fate probabilities
163
+ 5. **Download**: Export processed data as `.h5ad` file
164
+
165
+ Example datasets are available in the `data/` folder of the repository.
166
+
167
+ ## Command Line Interface
168
+
169
+ ### Available Commands
170
+
171
+ ```bash
172
+ # Launch web interface
173
+ scfocus ui
174
+
175
+ # Additional CLI commands may be added in future releases
176
+ ```
177
+
178
+ ## Workflow Overview
179
+
180
+ The typical scFocus workflow consists of:
181
+
182
+ 1. **Preprocessing**: Normalize and log-transform the data, select highly variable genes
183
+ 2. **Dimensionality Reduction**: Compute PCA and UMAP/t-SNE embeddings
184
+ 3. **scFocus Analysis**: Apply reinforcement learning to identify lineage branches
185
+ 4. **Merge Patterns**: Consolidate similar focus patterns
186
+ 5. **Visualization**: Display cell fate probabilities and branch assignments
187
+
188
+ ## Troubleshooting
189
+
190
+ ### Common Issues
191
+
192
+ **Issue**: `ModuleNotFoundError: No module named 'torch'`
193
+ - **Solution**: Install PyTorch: `pip install torch>=1.13.1`
194
+
195
+ **Issue**: CUDA out of memory error
196
+ - **Solution**: The algorithm automatically uses CPU if GPU is unavailable. For large datasets, consider reducing `n` (number of agents) or `pct_samples`.
197
+
198
+ **Issue**: Streamlit command not found
199
+ - **Solution**: Install streamlit: `pip install streamlit>=1.24.0`
200
+
201
+ **Issue**: Analysis is slow
202
+ - **Solution**:
203
+ - Reduce `num_episodes` (default 1000) for faster results
204
+ - Decrease `n` (number of agents) to reduce computational load
205
+ - Use GPU if available
206
+
207
+ ### Getting Help
208
+
209
+ - Check the [documentation](https://scfocus.readthedocs.io/en/latest/)
210
+ - Open an issue on [GitHub](https://github.com/PeterPonyu/scfocus/issues)
211
+ - Review example notebooks in the documentation
212
+
213
+ ## Development
214
+
215
+ ### Setting Up Development Environment
216
+
217
+ ```bash
218
+ # Clone the repository
219
+ git clone https://github.com/PeterPonyu/scfocus.git
220
+ cd scfocus
221
+
222
+ # Install in development mode
223
+ pip install -e .
224
+
225
+ # Install additional development dependencies
226
+ pip install -r requirements.txt
227
+ ```
228
+
229
+ ### Building Documentation
230
+
231
+ The documentation is built using Sphinx:
232
+
233
+ ```bash
234
+ # Install Sphinx and dependencies
235
+ pip install sphinx sphinx-rtd-theme
236
+
237
+ # Build the documentation
238
+ cd source
239
+ make html
240
+ ```
241
+
242
+ The documentation will be built in `build/html/`.
243
+
244
+ ## License
245
+ <p>
246
+ <a href="https://choosealicense.com/licenses/mit/" target="_blank">
247
+ <img alt="license" src="https://img.shields.io/github/license/PeterPonyu/scfocus?style=flat-square&color=brightgreen"/>
248
+ </a>
249
+ </p>
250
+
251
+
252
+ ## Citation
253
+
254
+ Chen, C., Fu, Z., Yang, J., Chen, H., Huang, J., Qin, S., Wang, C., & Hu, X. (2025). scFocus: Detecting Branching Probabilities in Single-cell Data with SAC. *Computational and Structural Biotechnology Journal*, 27, 2243–2263. [https://doi.org/10.1016/j.csbj.2025.04.036](https://doi.org/10.1016/j.csbj.2025.04.036)
@@ -0,0 +1,221 @@
1
+ <div align="center">
2
+ <a href="https://peterponyu.github.io/">
3
+ <img src="https://peterponyu.github.io/assets/badges/scfocus.svg" width="64" alt="ZF Lab · scfocus">
4
+ </a>
5
+ </div>
6
+
7
+ # scFocus
8
+
9
+ ## Overview
10
+
11
+ scFocus is a reinforcement-learning-based method for analyzing lineage branching in low-dimensional single-cell embeddings. It combines branch probabilities with unsupervised structure in the latent space to help characterize continuous cell-state transitions and related visualization workflows.
12
+
13
+ ## Graphical Abstract
14
+ <p align="center">
15
+ <img src="source/_static/Pattern.png" alt="Pattern Image" width="600"/>
16
+ </p>
17
+
18
+ ## Installation
19
+
20
+ [![PyPI](https://img.shields.io/pypi/v/scfocus-sc.svg?color=brightgreen&style=flat)](https://pypi.org/project/scfocus-sc/)
21
+
22
+ ### Requirements
23
+
24
+ - Python >= 3.9
25
+ - Required packages: `scanpy>=1.10.4`, `torch>=1.13.1`, `joblib>=1.2.0`, `tqdm>=4.64.1`, `streamlit>=1.24.0`
26
+
27
+ ### Install from PyPI
28
+
29
+ ``` bash
30
+ pip install scfocus-sc
31
+ ```
32
+
33
+ From version 0.0.6 the package is published on PyPI as `scfocus-sc`; the import name is still `scfocus`. The earlier `scfocus` project on PyPI stays at 0.0.5 and is no longer updated.
34
+
35
+ ### Install from source
36
+
37
+ ```bash
38
+ git clone https://github.com/PeterPonyu/scfocus.git
39
+ cd scfocus
40
+ pip install -e .
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ Basic example to get started with scFocus:
46
+
47
+ ```python
48
+ import scanpy as sc
49
+ import scfocus
50
+
51
+ # Load your single-cell data
52
+ adata = sc.read_h5ad('your_data.h5ad')
53
+
54
+ # Preprocess: normalize, log-transform, and compute PCA
55
+ sc.pp.normalize_total(adata, target_sum=1e4)
56
+ sc.pp.log1p(adata)
57
+ sc.pp.highly_variable_genes(adata, n_top_genes=2000)
58
+ adata = adata[:, adata.var.highly_variable]
59
+ sc.pp.pca(adata)
60
+
61
+ # Compute UMAP embedding
62
+ sc.pp.neighbors(adata, n_neighbors=15)
63
+ sc.tl.umap(adata)
64
+
65
+ # Run scFocus analysis
66
+ embedding = adata.obsm['X_umap']
67
+ focus = scfocus.focus(embedding, n=6, pct_samples=0.01)
68
+ focus.meta_focusing(n=3)
69
+ focus.merge_fp2()
70
+
71
+ # Add focus probabilities to your AnnData object
72
+ adata.obsm['focus_probs'] = focus.mfp[0]
73
+ for i in range(focus.mfp[0].shape[1]):
74
+ adata.obs[f'Fate_{i}'] = focus.mfp[0][:, i]
75
+
76
+ # Visualize results
77
+ sc.pl.umap(adata, color=[f'Fate_{i}' for i in range(focus.mfp[0].shape[1])])
78
+ ```
79
+
80
+ ## Key Parameters
81
+
82
+ The `focus` class accepts the following key parameters:
83
+
84
+ - **f** (array-like): Latent space of the original data (e.g., UMAP or t-SNE coordinates)
85
+ - **n** (int, default=8): Number of parallel agents/branches to identify
86
+ - **pct_samples** (float, default=0.125): Percentage of samples used in each training step
87
+ - **max_steps** (int, default=5): Maximum steps per training episode
88
+ - **num_episodes** (int, default=1000): Number of training episodes
89
+ - **hidden_dim** (int, default=128): Hidden layer dimension for neural networks
90
+ - **res** (float, default=0.05): Resolution for merging similar focus patterns
91
+
92
+ For a complete list of parameters and their descriptions, see the [API documentation](https://scfocus.readthedocs.io/en/latest/).
93
+
94
+ ## Documentation
95
+
96
+ [![Documentation Status](https://readthedocs.org/projects/scfocus/badge/?version=latest)](https://scfocus.readthedocs.io/en/latest/?badge=latest)
97
+
98
+ Tutorials and API documentation are available at [https://scfocus.readthedocs.io/en/latest/](https://scfocus.readthedocs.io/en/latest/), including:
99
+
100
+ - Notebooks for different datasets
101
+ - Step-by-step tutorials
102
+ - API reference
103
+
104
+ ## Web Interface
105
+
106
+ scFocus provides an interactive web interface for data analysis.
107
+
108
+ ### Online Access
109
+
110
+ Access the hosted version at [scfocus.streamlit.app](https://scfocus.streamlit.app/).
111
+
112
+ ### Local Interface
113
+
114
+ Launch the local web interface:
115
+
116
+ ```bash
117
+ scfocus ui
118
+ ```
119
+
120
+ ### Using the Web Interface
121
+
122
+ 1. **Upload Data**: Support for `.h5ad` files or 10x Genomics format (matrix.mtx, features.tsv, barcodes.tsv)
123
+ 2. **Configure Parameters**:
124
+ - Number of highly variable genes (200-5000, default: 2000)
125
+ - Number of neighbors for UMAP (2-50, default: 15)
126
+ - Minimum distance for UMAP (0.0-2.0, default: 0.5)
127
+ - Number of branches (2-10, default: 6)
128
+ 3. **Process**: Click "Process" to run the analysis pipeline
129
+ 4. **Visualize**: View UMAP plots colored by cell fate probabilities
130
+ 5. **Download**: Export processed data as `.h5ad` file
131
+
132
+ Example datasets are available in the `data/` folder of the repository.
133
+
134
+ ## Command Line Interface
135
+
136
+ ### Available Commands
137
+
138
+ ```bash
139
+ # Launch web interface
140
+ scfocus ui
141
+
142
+ # Additional CLI commands may be added in future releases
143
+ ```
144
+
145
+ ## Workflow Overview
146
+
147
+ The typical scFocus workflow consists of:
148
+
149
+ 1. **Preprocessing**: Normalize and log-transform the data, select highly variable genes
150
+ 2. **Dimensionality Reduction**: Compute PCA and UMAP/t-SNE embeddings
151
+ 3. **scFocus Analysis**: Apply reinforcement learning to identify lineage branches
152
+ 4. **Merge Patterns**: Consolidate similar focus patterns
153
+ 5. **Visualization**: Display cell fate probabilities and branch assignments
154
+
155
+ ## Troubleshooting
156
+
157
+ ### Common Issues
158
+
159
+ **Issue**: `ModuleNotFoundError: No module named 'torch'`
160
+ - **Solution**: Install PyTorch: `pip install torch>=1.13.1`
161
+
162
+ **Issue**: CUDA out of memory error
163
+ - **Solution**: The algorithm automatically uses CPU if GPU is unavailable. For large datasets, consider reducing `n` (number of agents) or `pct_samples`.
164
+
165
+ **Issue**: Streamlit command not found
166
+ - **Solution**: Install streamlit: `pip install streamlit>=1.24.0`
167
+
168
+ **Issue**: Analysis is slow
169
+ - **Solution**:
170
+ - Reduce `num_episodes` (default 1000) for faster results
171
+ - Decrease `n` (number of agents) to reduce computational load
172
+ - Use GPU if available
173
+
174
+ ### Getting Help
175
+
176
+ - Check the [documentation](https://scfocus.readthedocs.io/en/latest/)
177
+ - Open an issue on [GitHub](https://github.com/PeterPonyu/scfocus/issues)
178
+ - Review example notebooks in the documentation
179
+
180
+ ## Development
181
+
182
+ ### Setting Up Development Environment
183
+
184
+ ```bash
185
+ # Clone the repository
186
+ git clone https://github.com/PeterPonyu/scfocus.git
187
+ cd scfocus
188
+
189
+ # Install in development mode
190
+ pip install -e .
191
+
192
+ # Install additional development dependencies
193
+ pip install -r requirements.txt
194
+ ```
195
+
196
+ ### Building Documentation
197
+
198
+ The documentation is built using Sphinx:
199
+
200
+ ```bash
201
+ # Install Sphinx and dependencies
202
+ pip install sphinx sphinx-rtd-theme
203
+
204
+ # Build the documentation
205
+ cd source
206
+ make html
207
+ ```
208
+
209
+ The documentation will be built in `build/html/`.
210
+
211
+ ## License
212
+ <p>
213
+ <a href="https://choosealicense.com/licenses/mit/" target="_blank">
214
+ <img alt="license" src="https://img.shields.io/github/license/PeterPonyu/scfocus?style=flat-square&color=brightgreen"/>
215
+ </a>
216
+ </p>
217
+
218
+
219
+ ## Citation
220
+
221
+ Chen, C., Fu, Z., Yang, J., Chen, H., Huang, J., Qin, S., Wang, C., & Hu, X. (2025). scFocus: Detecting Branching Probabilities in Single-cell Data with SAC. *Computational and Structural Biotechnology Journal*, 27, 2243–2263. [https://doi.org/10.1016/j.csbj.2025.04.036](https://doi.org/10.1016/j.csbj.2025.04.036)
@@ -0,0 +1,118 @@
1
+ import streamlit as st
2
+ import scanpy as sc
3
+ import matplotlib.pyplot as plt
4
+ import numpy as np
5
+ import seaborn as sns
6
+ import joblib
7
+ import io
8
+ import tempfile
9
+ import sys
10
+ import os
11
+
12
+ # Handle imports for both direct execution and package import
13
+ try:
14
+ from .utils import read_files, preprocess, run_umap, run_tsne, run_focus
15
+ except ImportError:
16
+ # Add parent directory to path for direct execution
17
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18
+ from utils import read_files, preprocess, run_umap, run_tsne, run_focus
19
+
20
+ st.set_page_config(page_title="scFocus", page_icon="🔬", layout="wide")
21
+ st.markdown("<h1 style='text-align: center;'>scFocus</h1>", unsafe_allow_html=True)
22
+
23
+ if 'adata' not in st.session_state:
24
+ st.session_state.adata = None
25
+ if 'embedding' not in st.session_state:
26
+ st.session_state.embedding = None
27
+ if 'processed' not in st.session_state:
28
+ st.session_state.processed = False
29
+
30
+ if not st.session_state.adata:
31
+ uploaded_files = st.sidebar.file_uploader("Sequencing files", accept_multiple_files=True)
32
+ if len(uploaded_files) < 1:
33
+ st.warning("Please upload your single-cell data files to begin analysis.")
34
+ else:
35
+ st.session_state.adata = read_files(uploaded_files)
36
+
37
+ if st.session_state.adata is not None:
38
+
39
+ n_top_genes = st.sidebar.number_input(
40
+ "Number of highly variable genes",
41
+ min_value=200, max_value=5000, value=2000, step=100
42
+ )
43
+ n_neighbors = st.sidebar.number_input(
44
+ "Number of neighbors",
45
+ min_value=2, max_value=50, value=15, step=1
46
+ )
47
+ min_dist = st.sidebar.number_input(
48
+ "Minimum distance",
49
+ min_value=0.0, max_value=2.0, value=0.5, step=.1
50
+ )
51
+ n_branch = st.sidebar.number_input(
52
+ "Number of branch",
53
+ min_value=2, max_value=10, value=6, step=1
54
+ )
55
+
56
+
57
+ if st.sidebar.button("Process"):
58
+ preprocess(st.session_state.adata, n_top_genes)
59
+ st.success("Preprocessing completed!")
60
+ st.session_state.embedding = run_umap(st.session_state.adata, n_neighbors, min_dist)
61
+ st.success("UMAP embedding completed!")
62
+ st.write(st.session_state.adata)
63
+
64
+ mfp = run_focus(st.session_state.embedding, n_branch)
65
+ st.session_state.adata.obsm['mfp'] = mfp
66
+ for i in range(mfp.shape[1]):
67
+ st.session_state.adata.obs[f'Fate_{i}'] = mfp[:,i]
68
+ st.session_state.processed = True
69
+
70
+ if st.session_state.processed:
71
+
72
+ adata = st.session_state.adata
73
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.h5ad') as tmp_file:
74
+ adata.write_h5ad(tmp_file.name)
75
+ tmp_file.seek(0)
76
+ buffer = io.BytesIO()
77
+ with open(tmp_file.name,'rb')as f:
78
+ buffer.write(f.read())
79
+ buffer.seek(0)
80
+ st.sidebar.download_button(label="Download scFocus Processed Data",data=buffer,file_name='adata.h5ad',mime='application/x-h5ad')
81
+
82
+ color = st.selectbox('Please select the observation for coloring', options=list(st.session_state.adata.obs))
83
+ sc.pl.umap(st.session_state.adata, color=color, show=False)
84
+ fig = plt.gcf()
85
+ st.pyplot(fig)
86
+
87
+ if st.sidebar.button("FateProbs"):
88
+ sc.set_figure_params()
89
+ mfp = st.session_state.adata.obsm['mfp']
90
+ sc.pl.umap(st.session_state.adata, color=[f'Fate_{i}' for i in range(mfp.shape[1])], show=False)
91
+ fig = plt.gcf()
92
+ st.pyplot(fig)
93
+
94
+ if st.sidebar.button("Heatmap"):
95
+ mfp = st.session_state.adata.obsm['mfp']
96
+ focus_labs = np.argmax(mfp, axis=1)
97
+ st.session_state.adata.obs['focus_labels'] = focus_labs.astype(str)
98
+ with st.spinner("Generating heatmap..."):
99
+ mfp1 = mfp[np.argsort(np.argmax(mfp, axis=1)),:]
100
+ container = []
101
+ idxs = []
102
+ labels=[]
103
+
104
+ for i in range(mfp1.shape[1]):
105
+ idx = np.where(np.argmax(mfp1, axis=1) == i)[0]
106
+ idx1 = np.argsort(mfp1[idx, i])[::-1] + idx.min()
107
+ idxs.append(idx.min())
108
+ container.append(mfp1[idx1, :])
109
+ labels.extend([str(i)] * len(idx1))
110
+ mfp2 = np.vstack(container)
111
+ fig = plt.figure(figsize=(5,5), dpi=300)
112
+ ax = sns.heatmap(mfp2, yticklabels=False, vmax=1, vmin=0, cmap='viridis')
113
+ ax.set_xticklabels([f'Fate_{i}' for i in range(mfp2.shape[1])], rotation=60, ha='right')
114
+ st.pyplot(fig)
115
+
116
+
117
+
118
+
@@ -0,0 +1,67 @@
1
+ """
2
+ scFocus: Single-cell Reinforcement Learning for Lineage Focusing
3
+
4
+ scFocus is a Python package for analyzing single-cell RNA sequencing data using
5
+ reinforcement learning techniques. It identifies distinct lineage branches and cell
6
+ fate probabilities without requiring prior knowledge of cell types or differentiation
7
+ starting points.
8
+
9
+ The package implements the Soft Actor-Critic (SAC) reinforcement learning framework
10
+ to enhance cell subtype discrimination and discover biologically meaningful patterns
11
+ in single-cell data.
12
+
13
+ Main Classes
14
+ ------------
15
+ focus : Main class for performing scFocus analysis
16
+ Implements the reinforcement learning-based approach for identifying cell lineages.
17
+
18
+ Functions
19
+ ---------
20
+ main : Command-line interface entry point
21
+ Provides CLI access to scFocus functionality.
22
+
23
+ Examples
24
+ --------
25
+ Basic usage with UMAP embedding:
26
+
27
+ >>> import scanpy as sc
28
+ >>> import scfocus
29
+ >>> # Load and preprocess data
30
+ >>> adata = sc.read_h5ad('data.h5ad')
31
+ >>> sc.pp.normalize_total(adata, target_sum=1e4)
32
+ >>> sc.pp.log1p(adata)
33
+ >>> sc.pp.pca(adata)
34
+ >>> sc.pp.neighbors(adata)
35
+ >>> sc.tl.umap(adata)
36
+ >>> # Run scFocus
37
+ >>> embedding = adata.obsm['X_umap']
38
+ >>> focus_obj = scfocus.focus(embedding, n=6)
39
+ >>> focus_obj.meta_focusing(n=3)
40
+ >>> focus_obj.merge_fp2()
41
+ >>> # Add results to AnnData
42
+ >>> adata.obsm['focus_probs'] = focus_obj.mfp[0]
43
+
44
+ See Also
45
+ --------
46
+ scanpy : Single-cell analysis in Python
47
+ torch : PyTorch deep learning framework
48
+
49
+ Notes
50
+ -----
51
+ For detailed documentation and tutorials, visit:
52
+ https://scfocus.readthedocs.io/
53
+
54
+ Citation
55
+ --------
56
+ Chen, C., Fu, Z., Yang, J., Chen, H., Huang, J., Qin, S., Wang, C., & Hu, X. (2025).
57
+ scFocus: Detecting Branching Probabilities in Single-cell Data with SAC.
58
+ Computational and Structural Biotechnology Journal.
59
+ https://doi.org/10.1016/j.csbj.2025.04.036
60
+ """
61
+
62
+ from .focus import focus
63
+ from .cli import main
64
+
65
+ __all__ = ['focus', 'main']
66
+
67
+ __version__ = '0.0.6'