aristoteleo / dynamo-release

Inclusive model of expression dynamics with conventional or metabolic labeling based scRNA-seq / multiomics, vector field reconstruction and differential geometry analyses
https://dynamo-release.readthedocs.io/en/latest/
BSD 3-Clause "New" or "Revised" License
418 stars 59 forks source link

TypeError: 'tuple' object does not support item assignment and AttributeError: 'LeastActionPath' object has no attribute 'action' #553

Closed Mingsenli closed 8 months ago

Mingsenli commented 1 year ago

@Xiaojieqiu, Hi, Dr.Qiu: Congratulations on setting up your own independent lab!Looking forward to your better works I am meetting two errors when plotting the kinetic heatmap of the transcription factor expression along LAP. I hope you can help to solve. Thank you very much.

The codes are as follows:

develope_keys = ["adult_LSC->adult_cornea.superficial"]
from dynamo.plot.utils import map2color
def plot_lap(paths):
    fig, ax = plt.subplots(figsize=(5, 4))
    ax = dyn.pl.streamline_plot(
        adata, basis="umap", save_show_or_return="return", ax=ax, color="leiden_anno", frontier=True
    )
    ax = ax[0]
    x, y = 0, 1
    # plot paths
    for path in paths:
        lap_dict = transition_graph[path]["LAP_umap"]
        for prediction, action in zip(lap_dict["prediction"], lap_dict["action"]):
            ax.scatter(*prediction[:, [x, y]].T, c=map2color(action))
            ax.plot(*prediction[:, [x, y]].T, c="k")
plot_lap(develope_keys)
action_df = pd.DataFrame(index=cell_type, columns=cell_type)
t_df = pd.DataFrame(index=cell_type, columns=cell_type)
for i, start in enumerate(
    [
      #E_cornea_basal_cells_indices,
      #E_cornea_superficial_cells_indices,
       adult_LSC_cells_indices,
       adult_cornea_superficial_cells_indices,

    ]
):
    for j, end in enumerate(
        [
         #E_cornea_basal_cells_indices,
         #E_cornea_superficial_cells_indices,
         adult_LSC_cells_indices,
         adult_cornea_superficial_cells_indices,

        ]
    ):
        if start is not end:
            print(cell_type[i] + "->" + cell_type[j], end=",")
            lap = transition_graph[cell_type[i] + "->" + cell_type[j]]["lap"]  # lap
            gtraj = transition_graph[cell_type[i] + "->" + cell_type[j]]["gtraj"]
            ranking = transition_graph[cell_type[i] + "->" + cell_type[j]]["ranking"].copy()
            ranking["TF"] = [i in human_tfs_names for i in list(ranking["all"])]
            genes = ranking.query("TF == True").head(10)["all"].to_list()
            arr = gtraj.select_gene(genes)
            action_df.loc[cell_type[i], cell_type[j]] = lap.action()[-1]
            t_df.loc[cell_type[i], cell_type[j]] = lap.t[-1]

adult_LSC->adult_cornea.superficial,

AttributeError Traceback (most recent call last) Cell In[52], line 29 27 genes = ranking.query("TF == True").head(10)["all"].to_list() 28 arr = gtraj.select_gene(genes) ---> 29 action_df.loc[cell_type[i], cell_type[j]] = lap.action()[-1] 30 t_df.loc[cell_type[i], cell_type[j]] = lap.t[-1]

AttributeError: 'LeastActionPath' object has no attribute 'action'

init_cells = [adata.obs_names[adult_LSC_cells_indices[0][0]]]
target_cells = [adata.obs_names[adult_cornea_superficial_cells_indices[0][0]]]
dyn.configuration.set_pub_style(scaler=0.6)
lap = dyn.pd.least_action(
    adata,
    init_cells=init_cells,
    target_cells=target_cells,
    basis="pca",
    adj_key="cosine_transition_matrix",)
with open("./Homo_sapiens_TF.csv", 'r') as f:
 human_tfs = f.read().splitlines()
human_tfs_names = list(human_tfs)

is_human_tfs = [gene in human_tfs_names for gene in adata.var_names[adata.var.use_for_transition]]
human_genes = adata.var_names[adata.var.use_for_transition][is_human_tfs]
dyn.configuration.set_pub_style(scaler=0.6)
sns.set(font_scale=0.8)
sns_heatmap = dyn.pl.kinetic_heatmap(
    adata,
    basis="pca",
    mode="lap",
    figsize=(10, 5),
    genes=human_genes,
    project_back_to_high_dim=True,
    save_show_or_return="return",
    color_map="bwr",
    transpose=True,
    xticklabels=True,
    yticklabels=False
)
plt.setp(sns_heatmap.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)
plt.tight_layout()

TypeError Traceback (most recent call last) Cell In[55], line 5 3 dyn.configuration.set_pub_style(scaler=0.6) 4 sns.set(font_scale=0.8) ----> 5 sns_heatmap = dyn.pl.kinetic_heatmap( 6 adata, 7 basis="pca", 8 mode="lap", 9 figsize=(10, 5), 10 genes=human_genes, 11 project_back_to_high_dim=True, 12 save_show_or_return="return", 13 color_map="bwr", 14 transpose=True, 15 xticklabels=True, 16 yticklabels=False 17 ) 19 plt.setp(sns_heatmap.ax_heatmap.yaxis.get_majorticklabels(), rotation=0) 20 plt.tight_layout()

File ~/.local/lib/python3.8/site-packages/dynamo/plot/time_series.py:408, in kinetic_heatmap(adata, genes, mode, basis, layer, project_back_to_high_dim, tkey, dist_threshold, color_map, gene_order_method, show_colorbar, cluster_row_col, figsize, standard_scale, n_convolve, spaced_num, traj_ind, log, gene_group, gene_group_cmap, cell_group, cell_group_cmap, enforce, hline_rows, hlines_kwargs, vline_cols, vlines_kwargs, save_show_or_return, save_kwargs, transpose, **kwargs) 406 if transpose: 407 row_colors, col_colors = col_colors, row_colors --> 408 cluster_row_col[0], cluster_row_col[1] = cluster_row_col[1], cluster_row_col[0] 409 df = df.T 411 heatmap_kwargs = dict( 412 xticklabels=False, 413 yticklabels=1, (...) 421 standard_scale=None, 422 )

TypeError: 'tuple' object does not support item assignment

Sichao25 commented 1 year ago

Hi, thank you very much for reporting those issues. After looking into it, I've identified some bugs within those functions. I will fix it as soon as possible and keep you updated.

Sichao25 commented 1 year ago

Hi @Mingsenli, thank you again for raising those issues. For the first error, you can change the lap.action() to lap.action_t(). We will update the LAP tutorial soon. Sorry for the confusion. The second error will be fixed in this pull request. I also updated the networkx API. You can update networkx version If you have some problems with from_scipy_sparse_matrix/from_scipy_sparse_array. Let me know if you have further questions.

Mingsenli commented 1 year ago

Hi @Sichao25 ,Thank you for your help. I don't understand how to solve the second error. How to update networkx version?

Sichao25 commented 1 year ago

Once the pull request has been merged, you can download the latest Dynamo from GitHub and the kinetic_heatmap problem will be gone. If the latest Dynamo raises an error like networkx.convert_matrix has no attribute called from_scipy_sparse_array, you may need to update your networkx version. You can do that by pip install <package_name> -U or conda update <package_name> depending on your environment.

Mingsenli commented 1 year ago

Hi, @Sichao25 , I installed the latest Dynamo from GitHub (v1.3.2), but dyn.pl.kinetic_heatmap still failed to work. The same error was reported.

Sichao25 commented 1 year ago

It's because the pull request has not been merged. It will be merged in a few days after review.

Mingsenli commented 1 year ago

Hi, @Sichao25 , I see that the pull request has been merged and I installed the latest Dynamo. But dyn.pl.kinetic_heatmap still failed to work. The same error was reported.

Sichao25 commented 1 year ago

I see. Could you tell me how you install the Dynamo? If you are using the v1.3.2 Dynamo, the same error will be reported because the released version is "tagged" on a specific commit. You may need to install it from the latest code or wait for the next release.

Mingsenli commented 1 year ago

I downloaded the latest dynamo-release-master from "code" and the time_series.py in my installation file has been updated as indicated in the Github "pull requests". I installed this newest dynamo in a new enviroment. So it is very strange.

Mingsenli commented 1 year ago

hi @Sichao25, so how can i solve this problem related to dyn.pl.kinetic_heatmap?

Sichao25 commented 1 year ago

I see. Is the error message still the same? The kinetic_map works in my environment and Google Colab with Dynamo installed from github. Could you also try using Colab to test it, you can find the link in our readthedocs.

github-actions[bot] commented 1 year ago

This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 14 days

github-actions[bot] commented 9 months ago

This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 14 days