Skip to content

tools._deconv


def bulk_deconv(bulk_data,
                sc_adata,
                annotation_key,
                marker_data=None,
                rename=None,
                dataset_name="",
                out_dir='.',
                different_source=True,
                cell_list=None,
                scale_factors=10000,
                trans_method="log",
                save = True,
                save_figure=True,
                n_cell=100,
                **kwargs)

Deconvolute the cell type fraction from bulk expression data with single cell dataset as reference. Reconstruct the bulk data using single cell.

Parameters:

Name Type Description Default
bulk_data dataframe

An :class:~pandas.dataframe containing the bulk expression data. The first column should be gene symbol, following column should be sample name.

required
sc_adata AnnData

An :class:~anndata.AnnData containing the single cell expression.

required
annotation_key string

The .obs key where the single cell annotation is stored. : anndata.AnnData.

required
marker_data

An :class:~pandas.dataframe which columns are cell types, rows are marker gene.

required
dataset_name string.

The prefix of output file.

''
out_dir string

The path to store the output data.

'.'
different_source boolean

True for single cell and bulk data from the same sample, which means not executing batch effect. False for single cell and bulk data from the different samples, which means executing batch effect.

True
cell_list list

The list indicate the cell type names which need to take into consideration.

None
scale_factors int

The number of counts to normalize every observation to before computing profiles. If None, no normalization is performed.

100000
trans_method string

What transformation to apply to the expression before computing the profiles. - "log" : log(x+1) - None : no transformation

'log'
save boolean

Whether save the result data during each step. If saving, the processing may be skipped.

True
save_figure boolean

Whether save figures during preprocessing. eg. scatter plot of pca data.

True
mapping_sc boolean

Whether reconstruct the bulk data with single cell data.

required
n_cell int

The number of cells within each bulk.

2000
**kwargs

Additional keyword arguments forwarded to :func:~cytobulk.preprocessing.qc_bulk_sc.

{}

Returns:

Type Description
Returns the deconvolution result and reconstructed bulk.
Source code in cytobulk\tools\_deconv.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def bulk_deconv(bulk_data,
                sc_adata,
                annotation_key,
                marker_list=None,
                rename=None,
                dataset_name="",
                out_dir='.',
                different_source=True,
                cell_list=None,
                scale_factors=100000,
                trans_method="log",
                save = True,
                save_figure=True,
                n_cell=2000,
                **kwargs):
    """
    Deconvolute the cell type fraction from bulk expression data with single cell dataset as reference.
    Reconstruct the bulk data using single cell.

    Parameters
    ----------
    bulk_data : dataframe
        An :class:`~pandas.dataframe` containing the bulk expression data. 
        The first column should be gene symbol, following column should be sample name.
    sc_adata : anndata.AnnData
        An :class:`~anndata.AnnData` containing the single cell expression.
    annotation_key : string
        The `.obs` key where the single cell annotation is stored. : anndata.AnnData.
    marker_data : 
        An :class:`~pandas.dataframe` which columns are cell types, rows are marker gene.
    dataset_name : string.
        The prefix of output file.
    out_dir : string, optional
        The path to store the output data.
    different_source : boolean, optional
        True for single cell and bulk data from the same sample, which means not executing batch effect.
        False for single cell and bulk data from the different samples, which means executing batch effect.
    cell_list : list, optional
        The list indicate the cell type names which need to take into consideration.
    scale_factors : int, optional
        The number of counts to normalize every observation to before computing profiles. If `None`, no normalization is performed. 
    trans_method : string, optional
        What transformation to apply to the expression before computing the profiles. 
        - "log" : log(x+1)
        - `None` : no transformation
    save : boolean, optional
        Whether save the result data during each step. If saving, the processing may be skipped.
    save_figure : boolean, optional
        Whether save figures during preprocessing. eg. scatter plot of pca data.
    mapping_sc : boolean, optional
        Whether reconstruct the bulk data with single cell data.
    n_cell : int, optional
        The number of cells within each bulk.
    **kwargs : 
        Additional keyword arguments forwarded to
        :func:`~cytobulk.preprocessing.qc_bulk_sc`.


    Returns
    -------
    Returns the deconvolution result and reconstructed bulk.
    """
    # check the filtered dataset. If exist, skipping preprocessing.
    bulk_ori_adata = bulk_data.copy()
    if exists(f'{out_dir}/filtered/pseudo_bulk_{dataset_name}.h5ad') and exists(f'{out_dir}/filtered/sc_data_{dataset_name}.h5ad') and \
    exists(f'{out_dir}/filtered/bulk_data_{dataset_name}.h5ad') and exists(f'{out_dir}/filtered/cells_{dataset_name}.json'):

        pseudo_bulk = sc.read_h5ad(f"{out_dir}/filtered/pseudo_bulk_{dataset_name}.h5ad")
        sc_adata = sc.read_h5ad(f"{out_dir}/filtered/sc_data_{dataset_name}.h5ad")
        bulk_adata = sc.read_h5ad(f"{out_dir}/filtered/bulk_data_{dataset_name}.h5ad")
        with open(f"{out_dir}/filtered/cells_{dataset_name}.json") as json_file:
            common_cell = json.load(json_file)
        annotation_key="curated_cell_type"
    else:
        #preprocessing
        sc_adata, pseudo_bulk, bulk_adata, common_cell,annotation_key = pp.preprocessing(bulk_data,
                                                                        sc_adata,
                                                                        annotation_key,
                                                                        is_st=False,
                                                                        marker_list=marker_list,
                                                                        rename=rename,
                                                                        dataset_name=dataset_name,
                                                                        out_dir=out_dir,
                                                                        different_source=different_source,
                                                                        cell_list=cell_list,
                                                                        scale_factors=scale_factors,
                                                                        trans_method=trans_method,
                                                                        n_sample_each_group=len(bulk_data.obs_names)*5,
                                                                        min_cells_each_group=n_cell,
                                                                        cell_gap_each_group=50,
                                                                        group_number=10,
                                                                        save = save,
                                                                        save_figure=save_figure,
                                                                        **kwargs)
    #deconvolution
    if exists(f'{out_dir}/output/{dataset_name}_prediction_frac.csv'):
        deconv_result = pd.read_csv(f'{out_dir}/output/{dataset_name}_prediction_frac.csv',index_col=0)
    else:
        deconv_result = _bulk_sc_deconv(bulk_adata, 
                                        pseudo_bulk, 
                                        sc_adata, 
                                        common_cell,
                                        annotation_key = annotation_key, 
                                        dataset_name=dataset_name, 
                                        out_dir=out_dir)
    row_sums = deconv_result.sum(axis=1)
    df_normalized = deconv_result.div(row_sums, axis=0)
    bulk_ori_adata.uns['deconv']=df_normalized
    df_normalized.to_csv(f"{out_dir}/output/{dataset_name}_prediction_frac_normalized.csv")
    bulk_ori_adata.write_h5ad(f'{out_dir}/output/{dataset_name}_bulk_adata.h5ad')

    return deconv_result,bulk_ori_adata

st_deconv(st_adata,
            sc_adata,
            annotation_key,
            marker_list=None,
            rename=None,
            dataset_name="",
            out_dir='.',
            different_source=True,
            cell_list=None,
            scale_factors=10000,
            trans_method="log",
            save = True,
            save_figure=True,
            n_cell=10,
            **kwargs)

Deconvolute the cell type fraction from spot expression data with single cell dataset as reference.

Parameters:

Name Type Description Default
st_adata AnnData

An :class:~anndata.AnnData containing the single cell expression. The first column should be gene symbol, following column should be spot name.

required
sc_adata AnnData

An :class:~anndata.AnnData containing the single cell expression.

required
annotation_key string

The .obs key where the single cell annotation is stored. : anndata.AnnData.

required
marker_list

An :class:~pandas.dataframe which columns are cell types, rows are marker gene.

None
dataset_name string.

The prefix of output file.

''
out_dir string

The path to store the output data.

'.'
different_source boolean

True for single cell and bulk data from the same sample, which means not executing batch effect. False for single cell and bulk data from the different samples, which means executing batch effect.

True
cell_list list

The list indicate the cell type names which need to take into consideration.

None
scale_factors int

The number of counts to normalize every observation to before computing profiles. If None, no normalization is performed.

10000
trans_method string

What transformation to apply to the expression before computing the profiles. - "log" : log(x+1) - None : no transformation

'log'
save boolean

Whether save the result data during each step. If saving, the processing may be skipped.

True
save_figure boolean

Whether save figures during preprocessing. eg. scatter plot of pca data.

True
n_cell int

The number of cells within each bulk.

10
**kwargs

Additional keyword arguments forwarded to :func:~cytobulk.preprocessing.qc_bulk_sc.

{}

Returns:

Type Description
Returns the deconvolution result and reconstructed st.
Source code in cytobulk\tools\_deconv.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
def st_deconv(st_adata,
            sc_adata,
            annotation_key,
            marker_list=None,
            rename=None,
            dataset_name="",
            out_dir='.',
            different_source=True,
            cell_list=None,
            scale_factors=10000,
            trans_method="log",
            save = True,
            save_figure=True,
            n_cell=10,
            max_cells=40,
            **kwargs):
    """
    Deconvolute the cell type fraction from spot expression data with single cell dataset as reference.

    Parameters
    ----------
    st_adata : anndata.AnnData
        An :class:`~anndata.AnnData` containing the single cell expression.
        The first column should be gene symbol, following column should be spot name.
    sc_adata : anndata.AnnData
        An :class:`~anndata.AnnData` containing the single cell expression.
    annotation_key : string
        The `.obs` key where the single cell annotation is stored. : anndata.AnnData.
    marker_list : 
        An :class:`~pandas.dataframe` which columns are cell types, rows are marker gene.
    dataset_name : string.
        The prefix of output file.
    out_dir : string, optional
        The path to store the output data.
    different_source : boolean, optional
        True for single cell and bulk data from the same sample, which means not executing batch effect.
        False for single cell and bulk data from the different samples, which means executing batch effect.
    cell_list : list, optional
        The list indicate the cell type names which need to take into consideration.
    scale_factors : int, optional
        The number of counts to normalize every observation to before computing profiles. If `None`, no normalization is performed. 
    trans_method : string, optional
        What transformation to apply to the expression before computing the profiles. 
        - "log" : log(x+1)
        - `None` : no transformation
    save : boolean, optional
        Whether save the result data during each step. If saving, the processing may be skipped.
    save_figure : boolean, optional
        Whether save figures during preprocessing. eg. scatter plot of pca data.
    n_cell : int, optional
        The number of cells within each bulk.
    **kwargs : 
        Additional keyword arguments forwarded to
        :func:`~cytobulk.preprocessing.qc_bulk_sc`.


    Returns
    -------
    Returns the deconvolution result and reconstructed st.
    """
    # check the filtered dataset. If exist, skipping preprocessing.
    st_ori_adata = st_adata.copy()
    if exists(f'{out_dir}/filtered/pseudo_bulk_{dataset_name}.h5ad') and exists(f'{out_dir}/filtered/sc_data_{dataset_name}.h5ad') and \
    exists(f'{out_dir}/filtered/bulk_data_{dataset_name}.h5ad') and exists(f'{out_dir}/filtered/cells_{dataset_name}.json'):
        pseudo_st = sc.read_h5ad(f"{out_dir}/filtered/pseudo_bulk_{dataset_name}.h5ad")
        sc_adata = sc.read_h5ad(f"{out_dir}/filtered/sc_data_{dataset_name}.h5ad")
        st_adata = sc.read_h5ad(f"{out_dir}/filtered/bulk_data_{dataset_name}.h5ad")
        with open(f"{out_dir}/filtered/cells_{dataset_name}.json") as json_file:
            common_cell = json.load(json_file)
        annotation_key="curated_cell_type"
    else:
        #preprocessing
        sc_adata, pseudo_st, st_adata,common_cell,annotation_key = pp.preprocessing(st_adata,
                                                                        sc_adata,
                                                                        annotation_key,
                                                                        is_st=True,
                                                                        marker_list=marker_list,
                                                                        rename=rename,
                                                                        dataset_name=dataset_name,
                                                                        out_dir=out_dir,
                                                                        different_source=different_source,
                                                                        cell_list=cell_list,
                                                                        scale_factors=scale_factors,
                                                                        trans_method=trans_method,
                                                                        n_sample_each_group=len(st_adata.obs_names)*6,
                                                                        min_cells_each_group=n_cell,
                                                                        cell_gap_each_group=1,
                                                                        group_number=5,
                                                                        save = save,
                                                                        save_figure=save_figure,
                                                                        **kwargs)
    #deconvolution
    if exists(f'{out_dir}/output/{dataset_name}_prediction_frac.csv'):
        deconv_result = pd.read_csv(f'{out_dir}/output/{dataset_name}_prediction_frac.csv',index_col=0)
    else:
        deconv_result = _bulk_sc_deconv(st_adata, 
                                        pseudo_st, 
                                        sc_adata, 
                                        common_cell,
                                        annotation_key = annotation_key, 
                                        dataset_name=dataset_name, 
                                        out_dir=out_dir,
                                        batch_effect=different_source,
                                        is_st=True)
    threshold = 1 / max_cells
    deconv_result[deconv_result < threshold] = 0
    row_sums = deconv_result.sum(axis=1)
    df_normalized = deconv_result.div(row_sums, axis=0)
    st_ori_adata.uns['deconv']=df_normalized
    df_normalized.to_csv(f"{out_dir}/output/{dataset_name}_prediction_frac_normalized.csv")
    st_ori_adata.write_h5ad(f'{out_dir}/output/{dataset_name}_st_adata.h5ad')
    return df_normalized,st_ori_adata