{
    "cells": [
        {
            "cell_type": "code",
            "execution_count": 1,
            "metadata": {},
            "outputs": [],
            "source": [
                "import anndata as ad\n",
                "import ACTIONet as anet"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 2,
            "metadata": {},
            "outputs": [],
            "source": [
                "%load_ext autoreload\n",
                "%autoreload 2\n",
                "%aimport ACTIONet"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 3,
            "metadata": {},
            "outputs": [],
            "source": [
                "adata = ad.read_h5ad(\"data/pfc5k_ACTIONet_v2_python.h5ad\")"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 4,
            "metadata": {},
            "outputs": [
                {
                    "data": {
                        "text/plain": [
                            "AnnData object with n_obs × n_vars = 4505 × 17658\n",
                            "    obs: 'umis', 'genes', 'mito.perc', 'sizeFactors', 'Celltype', 'assigned_archetype', 'node_centrality'\n",
                            "    uns: 'ACTION', '__annotations___colors', 'metadata', 'obsm_annot', 'varm_annot'\n",
                            "    obsm: 'ACTION', 'ACTION_B', 'ACTION_normalized', 'ACTIONet2D', 'ACTIONet3D', 'ACTIONred', 'C_stacked', 'C_unified', 'H_stacked', 'H_unified', 'archetype_footprint', 'denovo_color'\n",
                            "    varm: 'ACTION_A', 'ACTION_V', 'unified_feature_profile', 'unified_feature_specificity'\n",
                            "    obsp: 'ACTIONet'"
                        ]
                    },
                    "execution_count": 4,
                    "metadata": {},
                    "output_type": "execute_result"
                }
            ],
            "source": [
                "adata"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 5,
            "metadata": {},
            "outputs": [
                {
                    "name": "stderr",
                    "output_type": "stream",
                    "text": [
                        "/Users/mohammadi/miniconda3/envs/actionet/lib/python3.10/site-packages/scanpy/plotting/_tools/scatterplots.py:392: UserWarning:\n",
                        "\n",
                        "No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\n",
                        "\n"
                    ]
                },
                {
                    "data": {
                        "text/plain": [
                            "<AxesSubplot: title={'center': '__annotations__'}, xlabel='actionet2d1', ylabel='actionet2d2'>"
                        ]
                    },
                    "execution_count": 5,
                    "metadata": {},
                    "output_type": "execute_result"
                },
                {
                    "data": {
                        "image/png": "[encoded data, 133904 characters]",
                        "text/plain": [
                            "<Figure size 640x480 with 1 Axes>"
                        ]
                    },
                    "metadata": {},
                    "output_type": "display_data"
                }
            ],
            "source": [
                "anet.pl.plot_ACTIONet(adata, adata.obs[\"Celltype\"])"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 6,
            "metadata": {},
            "outputs": [],
            "source": [
                "import json\n",
                "import itertools\n",
                "\n",
                "f = open('tmp/markers.json')\n",
                " \n",
                "all_markers = json.load(f)\n",
                "\n",
                "markers = all_markers[\"Brain\"][\"PFC\"][\"Mohammadi2020\"][\"marker.genes\"]"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 7,
            "metadata": {},
            "outputs": [
                {
                    "data": {
                        "text/plain": [
                            "dict_keys(['Ast', 'Endo', 'Ex-L2/3', 'Ex-L4', 'Ex-L4/5', 'Ex-L5', 'Ex-L5/6', 'Ex-L5/6-CC', 'Ex-NRGN', 'In-PV (Basket)', 'In-PV (Chandelier)', 'In-Rosehip', 'In-SST', 'In-VIP', 'Mic', 'Oli', 'OPC'])"
                        ]
                    },
                    "execution_count": 7,
                    "metadata": {},
                    "output_type": "execute_result"
                }
            ],
            "source": [
                "markers.keys()"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 8,
            "metadata": {},
            "outputs": [],
            "source": [
                "import pandas as pd\n",
                "import numpy as np\n",
                "from scipy import sparse\n",
                "\n",
                "network_normalization_code = 0\n",
                "feature_names = pd.Series(\n",
                "    [\n",
                "        x.decode() if isinstance(x, (bytes, bytearray)) else x\n",
                "        for x in list(adata.var.index)\n",
                "    ]\n",
                ")\n",
                "masks = np.array(\n",
                "    pd.DataFrame([feature_names.isin(markers[key]) * 1 for key in markers.keys()]).T\n",
                ")\n",
                "S = sparse.csc_matrix(adata.X.T)\n",
                "marker_mat = sparse.csc_matrix(masks)\n",
                "\n",
                "G = sparse.csc_matrix(adata.obsp[\"ACTIONet\"])\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 9,
            "metadata": {},
            "outputs": [
                {
                    "name": "stdout",
                    "output_type": "stream",
                    "text": [
                        "Smoothing geneset scores ... done\n"
                    ]
                }
            ],
            "source": [
                "import _ACTIONet as _an\n",
                "out = _an.aggregate_genesets(\n",
                "    G, S, marker_mat, network_normalization_code, 0.85, 0\n",
                ")\n",
                "marker_stats = out[\"stats_norm_smoothed\"]\n",
                "Enrichment = pd.DataFrame(\n",
                "    marker_stats, index=adata.obs.index, columns=markers.keys()\n",
                ")\n",
                "\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 14,
            "metadata": {},
            "outputs": [],
            "source": [
                "from scipy.sparse import csc_matrix\n",
                "\n",
                "marker_stats_raw = out[\"stats_norm\"]\n",
                "marker_stats_raw[marker_stats_raw < 0] = 0\n",
                "G_norm = csc_matrix(_an.normalize_spmat(G, 1).T)\n",
                "# logPvals = _an.assess_label_enrichment(G_norm, marker_stats_raw)\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 16,
            "metadata": {},
            "outputs": [],
            "source": [
                "logPvals = _an.assess_label_enrichment(G_norm, marker_stats_raw)\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 8,
            "metadata": {},
            "outputs": [
                {
                    "name": "stdout",
                    "output_type": "stream",
                    "text": [
                        "Smoothing geneset scores ... done\n"
                    ]
                }
            ],
            "source": [
                "Labels, Conf, Enrichment = anet.po.cells.annotate(adata, markers)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 9,
            "metadata": {},
            "outputs": [
                {
                    "name": "stderr",
                    "output_type": "stream",
                    "text": [
                        "/Users/mohammadi/miniconda3/envs/actionet/lib/python3.10/site-packages/scanpy/plotting/_tools/scatterplots.py:392: UserWarning:\n",
                        "\n",
                        "No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\n",
                        "\n"
                    ]
                },
                {
                    "data": {
                        "text/plain": [
                            "<AxesSubplot: title={'center': '__annotations__'}, xlabel='actionet2d1', ylabel='actionet2d2'>"
                        ]
                    },
                    "execution_count": 9,
                    "metadata": {},
                    "output_type": "execute_result"
                },
                {
                    "data": {
                        "image/png": "[encoded data, 125968 characters]",
                        "text/plain": [
                            "<Figure size 640x480 with 1 Axes>"
                        ]
                    },
                    "metadata": {},
                    "output_type": "display_data"
                }
            ],
            "source": [
                "anet.pl.plot_ACTIONet(adata, Labels.values)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 32,
            "metadata": {},
            "outputs": [],
            "source": [
                "markers_Velmeshev = all_markers[\"Brain\"][\"PFC\"][\"Velmeshev2019\"][\"marker.genes\"]"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 35,
            "metadata": {},
            "outputs": [
                {
                    "name": "stdout",
                    "output_type": "stream",
                    "text": [
                        "Smoothing geneset scores ... done\n",
                        "\tLPA iteration 3/3"
                    ]
                }
            ],
            "source": [
                "Labels_Velmeshev, Conf_Velmeshev, Enrichment_Velmeshev = anet.po.cells.annotate(adata, markers_Velmeshev)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 37,
            "metadata": {},
            "outputs": [
                {
                    "name": "stderr",
                    "output_type": "stream",
                    "text": [
                        "/Users/mohammadi/miniconda3/envs/actionet/lib/python3.10/site-packages/scanpy/plotting/_tools/scatterplots.py:392: UserWarning:\n",
                        "\n",
                        "No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored\n",
                        "\n"
                    ]
                },
                {
                    "data": {
                        "text/plain": [
                            "<AxesSubplot: title={'center': '__annotations__'}, xlabel='actionet2d1', ylabel='actionet2d2'>"
                        ]
                    },
                    "execution_count": 37,
                    "metadata": {},
                    "output_type": "execute_result"
                },
                {
                    "data": {
                        "image/png": "[encoded data, 121836 characters]",
                        "text/plain": [
                            "<Figure size 640x480 with 1 Axes>"
                        ]
                    },
                    "metadata": {},
                    "output_type": "display_data"
                }
            ],
            "source": [
                "anet.pl.plot_ACTIONet(adata, Labels_Velmeshev.values)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": []
        }
    ],
    "metadata": {
        "interpreter": {
            "hash": "e6b19d727065d69898d5719ef57bdd3f52a377d995ad1aaa3251e7a9df51309b"
        },
        "kernelspec": {
            "display_name": "Python 3.8.8 64-bit",
            "name": "python3"
        },
        "language_info": {
            "codemirror_mode": {
                "name": "ipython",
                "version": 3
            },
            "file_extension": ".py",
            "mimetype": "text/x-python",
            "name": "python",
            "nbconvert_exporter": "python",
            "pygments_lexer": "ipython3",
            "version": "3.10.6"
        },
        "orig_nbformat": 4
    },
    "nbformat": 4,
    "nbformat_minor": 2
}
