{ "cells": [ { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "# RECOVAR visualization and analysis (copied from cryoDRGN's)\n", "\n", "This jupyter notebook provides a template for analyzing results, including:\n", "* plotting of mean, mask and eigenvector\n", "* resolution of mean and decay of eigenvalues\n", "* latent space visualization with PCA/UMAP\n", "* clustering\n", "* trajectories\n", "\n", "\n", "\n", "\n", "Note that this is a simple template for data analysis, and not a polished UI. Experience with Python/Pandas is recommended." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "tags": [] }, "outputs": [], "source": [ "import recovar.config\n", "from importlib import reload\n", "import numpy as np\n", "from recovar import plot_utils\n", "from recovar import output, dataset\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "import plotly.graph_objs as go\n", "import plotly.offline as py\n", "from recovar import simulator, regularization\n", "reload(simulator)\n", "import jax\n", "import warnings\n", "from recovar.fourier_transform_utils import fourier_transform_utils\n", "import jax.numpy as jnp\n", "ftu = fourier_transform_utils(jnp)\n" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "### Load result from pipeline.py" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "tags": [] }, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: '/scratch/gpfs/mg6942/cryodrgn_empiar/empiar10180/inputs/paper_run//model/params.pkl'", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mFileNotFoundError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[2]\u001b[39m\u001b[32m, line 3\u001b[39m\n\u001b[32m 1\u001b[39m \u001b[38;5;66;03m# Load z\u001b[39;00m\n\u001b[32m 2\u001b[39m recovar_result_dir = \u001b[33m'\u001b[39m\u001b[33m/scratch/gpfs/mg6942/cryodrgn_empiar/empiar10180/inputs/paper_run/\u001b[39m\u001b[33m'\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m3\u001b[39m pipeline_output = output.PipelineOutput(recovar_result_dir)\n\u001b[32m 4\u001b[39m cryos = pipeline_output.get(\u001b[33m'\u001b[39m\u001b[33mlazy_dataset\u001b[39m\u001b[33m'\u001b[39m)\n", "\u001b[36mFile \u001b[39m\u001b[32m~/recovar/recovar/output.py:533\u001b[39m, in \u001b[36mPipelineOutput.__init__\u001b[39m\u001b[34m(self, result_path)\u001b[39m\n\u001b[32m 532\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m__init__\u001b[39m(\u001b[38;5;28mself\u001b[39m, result_path):\n\u001b[32m--> \u001b[39m\u001b[32m533\u001b[39m \u001b[38;5;28mself\u001b[39m.params = utils.pickle_load(result_path + \u001b[33m'\u001b[39m\u001b[33m/model/params.pkl\u001b[39m\u001b[33m'\u001b[39m)\n\u001b[32m 534\u001b[39m \u001b[38;5;28mself\u001b[39m.embedding = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 535\u001b[39m \u001b[38;5;28mself\u001b[39m.embedding_loaded = \u001b[38;5;28;01mFalse\u001b[39;00m\n", "\u001b[36mFile \u001b[39m\u001b[32m~/recovar/recovar/utils.py:243\u001b[39m, in \u001b[36mpickle_load\u001b[39m\u001b[34m(file)\u001b[39m\n\u001b[32m 242\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mpickle_load\u001b[39m( file):\n\u001b[32m--> \u001b[39m\u001b[32m243\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mopen\u001b[39m(file, \u001b[33m\"\u001b[39m\u001b[33mrb\u001b[39m\u001b[33m\"\u001b[39m) \u001b[38;5;28;01mas\u001b[39;00m f:\n\u001b[32m 244\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m pickle.load(f)\n", "\u001b[31mFileNotFoundError\u001b[39m: [Errno 2] No such file or directory: '/scratch/gpfs/mg6942/cryodrgn_empiar/empiar10180/inputs/paper_run//model/params.pkl'" ] } ], "source": [ "# Load z\n", "recovar_result_dir = '/scratch/gpfs/mg6942/cryodrgn_empiar/empiar10180/inputs/paper_run/'\n", "pipeline_output = output.PipelineOutput(recovar_result_dir)\n", "cryos = pipeline_output.get('lazy_dataset')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "reload(plot_utils)\n", "plot_utils.plot_summary_t(pipeline_output,cryos, n_eigs=20)\n", "plt.figure();\n", "plt.semilogy(pipeline_output.get('s')[:20])\n", "plt.title('eigenvalues')\n", "plt.figure()\n", "plt.hist(pipeline_output.get('contrasts')[10], bins = 30)\n", "plt.title('estimated contrast')\n", "print(np.std(pipeline_output.get('contrasts')[10]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import packaging\n", "from packaging.version import parse as parse_version\n", "parse_version('0.3.1') > parse_version('0.3')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "from recovar import deconvolve_density \n", "reload(deconvolve_density)\n", "alphas = np.flip(np.logspace(-6, 2, 10))\n", "percentile_reject = 10\n", "zdim = '4_noreg'\n", "lbfgsb_sols, alphas, cost, reg_cost, density, total_covar, grids, bounds = deconvolve_density.get_deconvolved_density(pipeline_output, zdim = zdim, pca_dim_max = 4, percentile_reject = percentile_reject, kernel_option = 'sampling', num_points = 50, alphas = alphas, percentile_bound=1)\n", "plt.figure()\n", "plt.loglog(1/alphas, cost)\n", "plt.xlabel('1/(regularization parameter)')\n", "plt.ylabel('residual')\n", "plt.title('Residual vs regularization- \\n The elbow in the curve usually gives a good value of the the regularization parameter alpha')\n", "\n", "# Visualization of the result of deconvolution under different regularization\n", "deconvolve_density.plot_density(lbfgsb_sols, density, alphas)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "## Choose an index, and store the deconvolved density. You can then use it to generate trajectories with \n", "## python generate_trajectories.py ... --density [recovar_result_dir + 'deconv_density.pkl'] \n", "## See documentaiton\n", "from recovar import utils\n", "idx = 4\n", "deconv_density = lbfgsb_sols[idx]\n", "# utils.pickle_dump({ 'density' : lbfgsb_sols[idx], 'latent_space_bounds' : bounds, 'alpha': alphas[idx] }, recovar_result_dir + 'deconv_density.pkl')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# Plot a density sliced in the middle of the distribution\n", "output.plot_over_density(np.array(deconv_density), None, bounds, cmap = 'inferno', projection_function = 'slice') \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "from recovar import latent_density\n", "deconv_density = lbfgsb_sols[idx]\n", "output_dir = recovar_result_dir + 'output/analysis_4_noreg/'\n", "centers = recovar.utils.pickle_load(output_dir + 'centers.pkl')['centers']\n", "grid_to_z, z_to_grid = latent_density.get_grid_z_mappings(bounds, density.shape[0])\n", "centers_grid = z_to_grid(centers)\n", "output.plot_over_density(np.array(deconv_density), None, bounds, cmap = None, points = centers_grid, projection_function = None, annotate = True) \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# Then you can visualize the trajectory between different kmeans\n", "from recovar import output as o\n", "\n", "z_st = centers[3]\n", "z_end = centers[23]\n", "from recovar import trajectory\n", "full_path, subsampled_path = o.make_trajectory_plots_from_results(pipeline_output, 4, './path', cryos = cryos, z_st = z_st, z_end = z_end, gt_volumes= None, n_vols_along_path = 40, plot_llh = False, input_density = deconv_density, latent_space_bounds = bounds)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load result from analyze" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": "zdim = '4_noreg'\nanalysis_dir = f'{recovar_result_dir}output/analysis_{zdim}'\ncenters = recovar.utils.pickle_load(f'{analysis_dir}/data/centers.pkl')" }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": "# If you changed the output dir, specify it here\n# analysis_dir = f'{recovar_result_dir}output/analysis_{z_dim_used}'\n# Load UMAP\numap = recovar.utils.pickle_load(f'{analysis_dir}/plots/umap/embedding.pkl')\n# or run UMAP\n# z = pipeline_output.get('zs')[20]\n# umap = analysis.run_umap(z)\n\ng = sns.jointplot(x=umap[:,0], y=umap[:,1], alpha=.1, s=1)\ng.set_axis_labels('UMAP1', 'UMAP2')\n# plt.savefig('test' + 'centers_'+str(axes[0]) + str(axes[1])+'.png' )\n\ng = sns.jointplot(x=umap[:,0], y=umap[:,1], kind='hex')\ng.set_axis_labels('UMAP1', 'UMAP2')" }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": "# Load kmeans\nK = 40\n# kmeans_labels = utils.load_pkl(f'{WORKDIR}/analyze.{EPOCH}/kmeans{K}/labels.pkl')\nkmeans_results = recovar.utils.pickle_load(f'{analysis_dir}/data/centers.pkl')\nkmeans_centers = kmeans_results['centers']\nkmeans_labels = kmeans_results['labels']\n\n# Or re-run kmeans with the desired number of classes\n# kmeans_labels, kmeans_centers = analysis.cluster_kmeans(z, 20)\n\n# # Get index for on-data cluster center\n# kmeans_centers, centers_ind = analysis.get_nearest_point(z, kmeans_centers)" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### PCA" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "pc = z\n", "for k1 in range(6):\n", " for k2 in range(k1+1,6):\n", " g = sns.jointplot(x=pc[:,k1], y=pc[:,k2], alpha=.1, s=1)\n", " g.set_axis_labels('PC'+str(k1), 'PC'+str(k2))" ] } ], "metadata": { "kernelspec": { "display_name": "recovar", "language": "python", "name": "recovar" }, "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.11.13" } }, "nbformat": 4, "nbformat_minor": 4 }