diff --git a/.ipynb_checkpoints/image histograms-new copy (2-10-23)-checkpoint.ipynb b/.ipynb_checkpoints/image histograms-new copy (2-10-23)-checkpoint.ipynb new file mode 100644 index 0000000..3014716 --- /dev/null +++ b/.ipynb_checkpoints/image histograms-new copy (2-10-23)-checkpoint.ipynb @@ -0,0 +1,3152 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "216adc8d", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\svc-scst291lab\\documents\\Github\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodepackbits\n", + " warnings.warn(\"failed to import %s\" % module_function)\n", + "C:\\Users\\svc-scst291lab\\documents\\Github\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodelzw\n", + " warnings.warn(\"failed to import %s\" % module_function)\n", + "C:\\Users\\svc-scst291lab\\documents\\Github\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.unpackints\n", + " warnings.warn(\"failed to import %s\" % module_function)\n" + ] + } + ], + "source": [ + "%matplotlib notebook\n", + "import numpy as np\n", + "from numpy.fft import fft2, ifft2, fftshift\n", + "import matplotlib\n", + "from matplotlib import pyplot as plt\n", + "from matplotlib import cm\n", + "import scipy\n", + "from scipy import stats\n", + "from statistics import mode\n", + "from scipy.optimize import curve_fit\n", + "from scipy.ndimage import gaussian_filter1d as gf1d\n", + "from scipy.ndimage import gaussian_filter as gf\n", + "from scipy.ndimage import uniform_filter as uf\n", + "\n", + "from skimage.transform import downscale_local_mean #For binning\n", + "from skimage.filters import threshold_otsu, threshold_local\n", + "\n", + "import xarray as xr #package for labeling and adding metadata to multi-dimensional arrays\n", + "from statistics import median\n", + "from statistics import mode\n", + "\n", + "import sys\n", + "#sys.path.append(\"../kai_colloids/PyDDM\") #must point to the PyDDM folder\n", + "#import ddm_analysis_and_fitting as ddm \n", + "\n", + "import tiff_file \n", + "\n", + "import io \n", + "import sys\n", + "import csv\n", + "\n", + "from PIL import Image\n", + "\n", + "import os\n", + "import glob #glob is helpful for searching for filenames or directories\n", + "import pickle #for saving data\n", + "### usually this block prints out \"nd2reader module not found. Reading of .nd2 files disabled.\" on the first run\n", + "### this is fine (unless you need to read .nd2 files), just re-run this block to make the error go away" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "400705c0", + "metadata": {}, + "outputs": [], + "source": [ + "def show_raw_images(row, ax, i, frame_key):\n", + " plt.gray()\n", + " index_add = arr_length * (row -1)\n", + " if time_array[i] == 0:\n", + " image = np.zeros((1440,1920))\n", + " ax.set_title('[no image]', fontsize=10)\n", + " else:\n", + " image = tiff_file.imread(files[i+index_add],key=[frame_key])\n", + " ax.set_title(\"~\" + str(time_array[i]) + \" hrs (row\"+str(row)+\") -->\", fontsize=10)\n", + " ax.imshow(image) #cmap = 'gray'\n", + " ax.axis('off')\n", + " plt.tight_layout(pad=.2)\n", + " \n", + "def show_image_histograms(row, ax, i, frame_key):\n", + " index_add = arr_length * (row -1)\n", + " if time_array[i] == 0:\n", + " plot = np.zeros((1440,1920))\n", + " ax.set_title('[no image]', fontsize=10)\n", + " ax.imshow(plot, cmap = 'gray')\n", + " else:\n", + " raw_image = tiff_file.imread(files[i+index_add],key=[frame_key])\n", + " #ax.set_title(\"~\" + str(time_array[i]) + \" hrs (row\"+str(row)+\") --> threshold\", fontsize=10)\n", + " ax.hist(raw_image.ravel(), bins=\"auto\")\n", + " #ax.axis('off')\n", + " plt.tight_layout(pad=.2)\n", + " \n", + "def all_pixel_values(frame_key, i):\n", + " all_vals_list = []\n", + " time_index = i\n", + " for l in range(len(files_list)):\n", + " list_to_add = files_list[l]\n", + " if l < 2:\n", + " for j in range(0,54, 9):\n", + " #print(list_to_add[j])\n", + " im_array = tiff_file.imread(list_to_add[j+time_index],key=[frame_key]) \n", + " im_ravel = filtimage_and_hist(im_array, 1000)\n", + " all_vals_list.extend(im_ravel)\n", + " else:\n", + " for j in range(0,26, 9):\n", + " #print(list_to_add[j+time_index])\n", + " im_array = tiff_file.imread(list_to_add[j+time_index],key=[frame_key]) \n", + " im_ravel = filtimage_and_hist(im_array, 1000)\n", + " all_vals_list.extend(im_ravel)\n", + " print(len(all_vals_list))\n", + " return all_vals_list\n", + " \n", + "def zerolistmaker(n):\n", + " listofzeros = ['none found'] * n\n", + " return listofzeros\n", + "\n", + "def filtimage_and_hist(image, filtersize):\n", + " image = (image*1.0) - ((uf(image,filtersize))*1) #(image) - unifrom-filtered(image) subtracts background\n", + " flat_im = image.ravel()\n", + " shifted_im = flat_im + np.abs(flat_im.min())\n", + " return shifted_im\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4eb0be71", + "metadata": {}, + "outputs": [], + "source": [ + "raw_image = tiff_file.imread(files[0],key=[0])\n", + "im = filtimage_and_hist(raw_image, 1000)\n", + "print(im.min())\n", + "print(np.abs(im.min()))" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "4eb1ae74", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " \t9-5-22_s1_theBigOne \t9-5-22_s2_theBigOne \t10-15-22_s1_theBigOne2 \t10-15-22_s2_theBigOne2\n", + " 0 \t row1_t1.tif \t\t row1_t1.tif \t\t row1_t01.tif \t\t row1_t01.tif\n", + " 1 \t row1_t2.tif \t\t row1_t2.tif \t\t row1_t02.tif \t\t row1_t02.tif\n", + " 2 \t row1_t3.tif \t\t row1_t3.tif \t\t row1_t03.tif \t\t row1_t03.tif\n", + " 3 \t row1_t4.tif \t\t row1_t4.tif \t\t row1_t04.tif \t\t row1_t04.tif\n", + " 4 \t row1_t5.tif \t\t row1_t5.tif \t\t row1_t05.tif \t\t row1_t05.tif\n", + " 5 \t row1_t6.tif \t\t row1_t6.tif \t\t row1_t06.tif \t\t row1_t06.tif\n", + " 6 \t row1_t7.tif \t\t row1_t7.tif \t\t row1_t07.tif \t\t row1_t07.tif\n", + " 7 \t row1_t8.tif \t\t row1_t8.tif \t\t row1_t08.tif \t\t row1_t08.tif\n", + " 8 \t row1_t9.tif \t\t row1_t9.tif \t\t row1_t09.tif \t\t row1_t09.tif\n", + " 9 \t row2_t1.tif \t\t row2_t1.tif \t\t row2_t01.tif \t\t row2_t01.tif\n", + " 10 \t row2_t2.tif \t\t row2_t2.tif \t\t row2_t02.tif \t\t row2_t02.tif\n", + " 11 \t row2_t3.tif \t\t row2_t3.tif \t\t row2_t03.tif \t\t row2_t03.tif\n", + " 12 \t row2_t4.tif \t\t row2_t4.tif \t\t row2_t04.tif \t\t row2_t04.tif\n", + " 13 \t row2_t5.tif \t\t row2_t5.tif \t\t row2_t05.tif \t\t row2_t05.tif\n", + " 14 \t row2_t6.tif \t\t row2_t6.tif \t\t row2_t06.tif \t\t row2_t06.tif\n", + " 15 \t row2_t7.tif \t\t row2_t7.tif \t\t row2_t07.tif \t\t row2_t07.tif\n", + " 16 \t row2_t8.tif \t\t row2_t8.tif \t\t row2_t08.tif \t\t row2_t08.tif\n", + " 17 \t row2_t9.tif \t\t row2_t9.tif \t\t row2_t09.tif \t\t row2_t09.tif\n", + " 18 \t row3_t1.tif \t\t row3_t1.tif \t\t row3_t01.tif \t\t row3_t01.tif\n", + " 19 \t row3_t2.tif \t\t row3_t2.tif \t\t row3_t02.tif \t\t row3_t02.tif\n", + " 20 \t row3_t3.tif \t\t row3_t3.tif \t\t row3_t03.tif \t\t row3_t03.tif\n", + " 21 \t row3_t4.tif \t\t row3_t4.tif \t\t row3_t04.tif \t\t row3_t04.tif\n", + " 22 \t row3_t5.tif \t\t row3_t5.tif \t\t row3_t05.tif \t\t row3_t05.tif\n", + " 23 \t row3_t6.tif \t\t row3_t6.tif \t\t row3_t06.tif \t\t row3_t06.tif\n", + " 24 \t row3_t7.tif \t\t row3_t7.tif \t\t row3_t07.tif \t\t row3_t07.tif\n", + " 25 \t row3_t8.tif \t\t row3_t8.tif \t\t row3_t08.tif \t\t row3_t08.tif\n", + " 26 \t row3_t9.tif \t\t row3_t9.tif \t\t row3_t09.tif \t\t row3_t09.tif\n", + " 27 \t row4_t1.tif \t\t row4_t1.tif \t\t none found \t\t none found\n", + " 28 \t row4_t2.tif \t\t row4_t2.tif \t\t none found \t\t none found\n", + " 29 \t row4_t3.tif \t\t row4_t3.tif \t\t none found \t\t none found\n", + " 30 \t row4_t4.tif \t\t row4_t4.tif \t\t none found \t\t none found\n", + " 31 \t row4_t5.tif \t\t row4_t5.tif \t\t none found \t\t none found\n", + " 32 \t row4_t6.tif \t\t row4_t6.tif \t\t none found \t\t none found\n", + " 33 \t row4_t7.tif \t\t row4_t7.tif \t\t none found \t\t none found\n", + " 34 \t row4_t8.tif \t\t row4_t8.tif \t\t none found \t\t none found\n", + " 35 \t row4_t9.tif \t\t row4_t9.tif \t\t none found \t\t none found\n", + " 36 \t row5_t1.tif \t\t row5_t1.tif \t\t none found \t\t none found\n", + " 37 \t row5_t2.tif \t\t row5_t2.tif \t\t none found \t\t none found\n", + " 38 \t row5_t3.tif \t\t row5_t3.tif \t\t none found \t\t none found\n", + " 39 \t row5_t4.tif \t\t row5_t4.tif \t\t none found \t\t none found\n", + " 40 \t row5_t5.tif \t\t row5_t5.tif \t\t none found \t\t none found\n", + " 41 \t row5_t6.tif \t\t row5_t6.tif \t\t none found \t\t none found\n", + " 42 \t row5_t7.tif \t\t row5_t7.tif \t\t none found \t\t none found\n", + " 43 \t row5_t8.tif \t\t row5_t8.tif \t\t none found \t\t none found\n", + " 44 \t row5_t9.tif \t\t row5_t9.tif \t\t none found \t\t none found\n", + " 45 \t row6_t1.tif \t\t row6_t1.tif \t\t none found \t\t none found\n", + " 46 \t row6_t2.tif \t\t row6_t2.tif \t\t none found \t\t none found\n", + " 47 \t row6_t3.tif \t\t row6_t3.tif \t\t none found \t\t none found\n", + " 48 \t row6_t4.tif \t\t row6_t4.tif \t\t none found \t\t none found\n", + " 49 \t row6_t5.tif \t\t row6_t5.tif \t\t none found \t\t none found\n", + " 50 \t row6_t6.tif \t\t row6_t6.tif \t\t none found \t\t none found\n", + " 51 \t row6_t7.tif \t\t row6_t7.tif \t\t none found \t\t none found\n", + " 52 \t row6_t8.tif \t\t row6_t8.tif \t\t none found \t\t none found\n", + " 53 \t row6_t9.tif \t\t row6_t9.tif \t\t none found \t\t none found\n" + ] + } + ], + "source": [ + "directory = \"Z\"\n", + "exp1 = \"9-5-22_s1_theBigOne\"\n", + "exp2 = \"9-5-22_s2_theBigOne\"\n", + "exp3 = \"10-15-22_s1_theBigOne2\"\n", + "exp4 = \"10-15-22_s2_theBigOne2\"\n", + "### \"data_dir\" is the pathway to the folder holding the tiff files to be analyzed \n", + "data_dir_95_s1 = directory+\":\\\\Gregor L\\\\__Kai Colloids\\\\\"+exp1+\"\\\\all tiff files\\\\\" \n", + "data_dir_95_s2 = directory+\":\\\\Gregor L\\\\__Kai Colloids\\\\\"+exp2+\"\\\\all tiff files\\\\\" \n", + "data_dir_1015_s1 = directory+\":\\\\Gregor L\\\\__Kai Colloids\\\\\"+exp3+\"\\\\all tiff files\\\\\" \n", + "data_dir_1015_s2 = directory+\":\\\\Gregor L\\\\__Kai Colloids\\\\\"+exp4+\"\\\\all tiff files\\\\\" \n", + "data_saveto = directory+\":\\\\Gregor L\\\\__Kai Colloids\\\\pixel intensity analysis\\\\\" #bottom_row_t01\\\\\n", + "\n", + "files_1015_s1 = glob.glob(data_dir_1015_s1+\"*_t*\") \n", + "files_1015_s2 = glob.glob(data_dir_1015_s2+\"*_t*\") \n", + "add_zeros = zerolistmaker((len(files_1015_s1)*2))\n", + "files_95_s1 = glob.glob(data_dir_95_s1+\"*_t*\")\n", + "files_95_s1.extend(add_zeros)\n", + "files_95_s2 = glob.glob(data_dir_95_s2+\"*_t*\") \n", + "files_95_s2.extend(add_zeros)\n", + "#print(\"found %i files\" % len(files_95_s1))\n", + "print (' \\t'+ exp1 + ' \\t' + exp2 + ' \\t' + exp3 + ' \\t' + exp4)\n", + "for i,f in enumerate(files_1015_s1): \n", + " print (' %i \\t %s \\t\\t %s \\t\\t %s \\t\\t %s' % (i, f.split('\\\\')[-1], files_1015_s2[i].split('\\\\')[-1], \n", + " files_95_s1[i].split('\\\\')[-1], files_95_s2[i].split('\\\\')[-1]))" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "6935872a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "tiff file dimensions: (5, 1440, 1920)\n", + "total number of time points: 9\n", + "(for image previews) number of rows = 5\n" + ] + } + ], + "source": [ + "frame_names = [\"1-3 kA-WT\", \"WT (no kA)\", \"EA KaiC\", \"AE KaiC\"]\n", + "### array containing the name for each frame in a tiff file to be run \n", + "### e.g. frame 1 is an image of the \"50% bKaiB\" condition, frame 2 is an image of the \"35% bKaiB\" condition, etc.\n", + "\n", + "total_rows = 6\n", + "\n", + "time_array = [1, 4, 7, 10, 13, 19, 22, 25, 28]\n", + "#s1 [1.1, 4.0, 7.4, 10.3, 14.7, 17.7, 20.3, 23.8, 27.0]\n", + "#s2 [1.2, 4.4, 7.8, 10.8, 15.2, 18.3, 20.8, 24.3, 28.0]\n", + "### array containing the time points corresponding to consecutive tiff files\n", + "### e.g. tiff files \"bottom_row_t1\", \"middle_row_t1\", and \"top_row_t1\" all correspond to t = 0.5 hrs, time_array[0]\n", + "\n", + "pixel_size = 0.364 # 4*0.091 = 0.364\n", + "### pixel size (microns per pixel) of frames/ images in the tiff files --- 40x olympus objective => 0.091 um/px\n", + "### IF 2x2 BINNING: multiply the original pixel size by 2^2 = 4, e.g. 4*(0.091 um/px) = 0.364 um/px\n", + "\n", + "fig_size = 10,10/1.618\n", + "### size of output figures\n", + "font_size = 10\n", + "### font size\n", + "dpi_num = 600\n", + "### image quality level (recommendation: 600)\n", + "\n", + "eg_im= tiff_file.imread(files_1015_s1[0])\n", + "print(\"tiff file dimensions: \"+ str(eg_im.shape))\n", + "\n", + "num_times = int((len(files_1015_s1))/total_rows)\n", + "print(\"total number of time points: \"+ str(num_times))\n", + "if num_times % 2 == 0:\n", + " num_rows = int(num_times/2)\n", + "else:\n", + " num_rows = int((num_times+1)/2)\n", + "print(\"(for image previews) number of rows = \" + str(num_rows))\n", + "\n", + "list_length = 49766400\n", + "means = np.zeros((4,num_times))\n", + "medians = np.zeros((4,num_times))\n", + "modes = np.zeros((4,num_times))\n", + "std_devs = np.zeros((4,num_times))\n", + "WTkA_pixel_val = np.zeros((num_times, list_length))\n", + "WTnokA_pixel_val = np.zeros((num_times, list_length))\n", + "EA_pixel_val = np.zeros((num_times, list_length))\n", + "AE_pixel_val = np.zeros((num_times, list_length))" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "3b7fb31a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "pixels per bin 9953\n" + ] + } + ], + "source": [ + "bins_num = 5000 #int(49766400 / 100000)\n", + "\n", + "all_counts = np.zeros((num_times, bins_num))\n", + "all_bins = np.zeros((num_times, bins_num))\n", + "\n", + "AE_all_probs = np.zeros((num_times, bins_num))\n", + "EA_all_probs = np.zeros((num_times, bins_num))\n", + "WTkA_all_probs = np.zeros((num_times, bins_num))\n", + "WTnokA_all_probs = np.zeros((num_times, bins_num))\n", + "AE_all_bins = np.zeros((num_times, bins_num+1))\n", + "EA_all_bins = np.zeros((num_times, bins_num+1))\n", + "WTkA_all_bins = np.zeros((num_times, bins_num+1))\n", + "WTnokA_all_bins = np.zeros((num_times, bins_num+1))\n", + "\n", + "print(\"pixels per bin \" + str(int(49766400/bins_num)))\n", + "all_FWHM = [0.0]*num_times" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bba68e55", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "font_size = 16\n", + "fig, ax = plt.subplots(figsize=(9,6))\n", + "plt.plot(bins[:-1], counts, '-o', c=cmap(0.65))\n", + "plt.ylabel(\"FWHM\",fontsize=font_size)\n", + "plt.xlabel(\"time (hours)\",fontsize=font_size) \n", + "ax.tick_params(direction='in', which='both', labelsize=font_size-2)\n", + "plt.title(title, fontsize=font_size)\n", + "#plt.ylim(100, 500)\n", + "plt.show()\n", + "#fig.savefig(data_saveto+\"FWHM- \"+title+\".jpg\", dpi=600)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0a7bf682", + "metadata": {}, + "outputs": [], + "source": [ + "for i in range(num_times):\n", + " all_times_all_values[i] = all_pixel_values(0, i)\n", + " #means[frame_key][i] = sum(all_times_all_values[i]) / len(all_times_all_values[i])\n", + " #medians[frame_key][i] = median(all_times_all_values[i])\n", + " #modes[frame_key][i] = mode(all_times_all_values[i])\n", + " #std_devs[frame_key][i] = np.std(all_times_all_values[i])\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "2ae8bc57", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5001\n" + ] + } + ], + "source": [ + "files_list = [files_1015_s1, files_1015_s2, files_95_s1, files_95_s2]\n", + "\n", + "for i in range(num_times):\n", + " #all_times_all_values[i] = all_pixel_values(frame_key, i)\n", + " WTkA_pixel_val[i] = all_pixel_values(0, i)\n", + " #WTnokA_pixel_val[i] = all_pixel_values(1, i)\n", + " EA_pixel_val[i] = all_pixel_values(2, i)\n", + " AE_pixel_val[i] = all_pixel_values(3, i)\n", + " #WTkA_all_probs[i], WTkA_all_bins[i] = np.histogram(all_pixel_values(0, i), bins=bins_num, density = True)\n", + " #WTnokA_all_probs[i], WTnokA_all_bins[i] = np.histogram(all_pixel_values(1, i), bins=bins_num, density = True)\n", + " #EA_all_probs[i], EA_all_bins[i] = np.histogram(all_pixel_values(2, i), bins=bins_num, density = True)\n", + " #AE_all_probs[i], AE_all_bins[i] = np.histogram(all_pixel_values(3, i), bins=bins_num, density = True)\n", + " \n", + " \n", + "print(len(AE_all_bins[0]))" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "585fc3a0", + "metadata": {}, + "outputs": [], + "source": [ + "def show_histograms(i, ax, array):\n", + " #print(files[i+index_add])\n", + " if time_array[i] == 0:\n", + " empty_im = np.zeros((1440,1920))\n", + " ax.imshow(empty_im, cmap = 'gray')\n", + " ax.set_title('[no image]', fontsize=10)\n", + " else:\n", + " ax.hist(array[i], density=True, bins=bins_num)\n", + " titles = condition + \", t= \" + str(time_array[i]) + \" hrs, bins= \"+str(bins_num)+\")\"\n", + " ax.set_title(titles, fontsize=font_size-1)\n", + " ax.set( ylabel='probability')\n", + " ax.set( xlabel='pixel intensity')\n", + " ax.set_xlim(0, 2500)\n", + " ax.set_ylim(0, 0.0095)\n", + " ax.tick_params(axis='both', which='major', labelsize=(font_size-3))\n", + " ax.xaxis.get_label().set_fontsize(font_size-2)\n", + " ax.yaxis.get_label().set_fontsize(font_size-2)\n", + " plt.tight_layout(pad=.25)\n", + "\n", + "cmap_num = (num_times*2) - 3\n", + "def stack_histograms(i, ax, array):\n", + " #print(files[i+index_add])\n", + " ax.hist(array[i], density=True, bins=bins_num, color=cmap(0.9-(i/cmap_num)))\n", + " \n", + "def FWHM(X,Y):\n", + " frac = 2 #For FWHM frac = 2, FWtenthM, frac = 10, etc\n", + " half_max = max(Y) / 2.\n", + " #find when function crosses line half_max (when sign of diff flips)\n", + " d = Y - (max(Y) / frac)\n", + " #plot(X[0:len(d)],d) #if you are interested\n", + " #find the left and right most indexes\n", + " indexes = np.where(d > 0)[0]\n", + " return abs(X[indexes[-1]] - X[indexes[0]]) #return the difference (full width)\n", + "\n", + "def select_data(frame_key):\n", + " if frame_key == 0:\n", + " print(\"WT+kaiA histograms\")\n", + " print((WTkA_all_bins[0][0:10]))\n", + " return WTkA_pixel_val, matplotlib.cm.get_cmap('Reds'), \"1:3 :: KaiA:WT KaiC, \"+str(time)+\" hrs\"\n", + " elif frame_key == 1:\n", + " print(\"WT w/o kaiA histograms\")\n", + " return WTnokA_pixel_val, matplotlib.cm.get_cmap('Blues'), \"WT KaiC (no KaiA), \"+str(time)+\" hrs\"\n", + " elif frame_key == 2:\n", + " print(\"EA histograms\")\n", + " return EA_pixel_val, matplotlib.cm.get_cmap('Greens'), \"EA KaiC (fixed binding), \"+str(time)+\" hrs\"\n", + " elif frame_key == 3:\n", + " print(\"AE histograms\")\n", + " return AE_pixel_val, matplotlib.cm.get_cmap('Greys'), \"AE KaiC (non-binding), \"+str(time)+\" hrs\"\n", + "\n", + "# My axis should display 10⁻¹ but you can switch to e-notation 1.00e+01\n", + "def log_tick_formatter(val, pos=None):\n", + " print(val)\n", + " return f\"$10^{{{int(val)}}}$\" # remove int() if you don't use MaxNLocator\n", + " # return f\"{10**val:.2e}\" # e-Notation" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "741a3942", + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (fig.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", + " if (this.ResizeObserver === undefined) {\n", + " if (window.ResizeObserver !== undefined) {\n", + " this.ResizeObserver = window.ResizeObserver;\n", + " } else {\n", + " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", + " this.ResizeObserver = obs.ResizeObserver;\n", + " }\n", + " }\n", + "\n", + " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " if (entry.contentBoxSize instanceof Array) {\n", + " // Chrome 84 implements new version of spec.\n", + " width = entry.contentBoxSize[0].inlineSize;\n", + " height = entry.contentBoxSize[0].blockSize;\n", + " } else {\n", + " // Firefox implements old version of spec.\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " }\n", + " } else {\n", + " // Chrome <84 implements even older version of spec.\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " if (entry.devicePixelContentBoxSize) {\n", + " // Chrome 84 implements new version of spec.\n", + " canvas.setAttribute(\n", + " 'width',\n", + " entry.devicePixelContentBoxSize[0].inlineSize\n", + " );\n", + " canvas.setAttribute(\n", + " 'height',\n", + " entry.devicePixelContentBoxSize[0].blockSize\n", + " );\n", + " } else {\n", + " canvas.setAttribute('width', width * fig.ratio);\n", + " canvas.setAttribute('height', height * fig.ratio);\n", + " }\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " this.resizeObserverInstance.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " event.preventDefault();\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / fig.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", + " var x1 = msg['x1'] / fig.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / fig.ratio,\n", + " fig.canvas.height / fig.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * this.ratio;\n", + " var y = canvas_pos.y * this.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "\n", + "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", + "// prettier-ignore\n", + "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + " fig.cell_info[0].output_area.element.on(\n", + " 'cleared',\n", + " { fig: fig },\n", + " fig._remove_fig_handler\n", + " );\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / fig.ratio;\n", + " fig.cell_info[0].output_area.element.off(\n", + " 'cleared',\n", + " fig._remove_fig_handler\n", + " );\n", + " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / this.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function (event) {\n", + " var fig = event.data.fig;\n", + " if (event.target !== this) {\n", + " // Ignore bubbled events from children.\n", + " return;\n", + " }\n", + " fig.close_ws(fig, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "AE histograms\n", + "49766400\n", + "WT+kaiA histograms\n", + "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + "EA histograms\n" + ] + } + ], + "source": [ + "\n", + "%matplotlib notebook\n", + "font_size = 16\n", + "fig, ax = plt.subplots(figsize=(9,6))\n", + "ax.tick_params(axis='both', which='major', labelsize=font_size-2)\n", + "\n", + "time_key = 0\n", + "time = time_array[time_key]\n", + "title = \"time = \"+str(time) +\" hrs, (bins= \"+str(bins_num)+\")\"\n", + "\n", + "add = 0\n", + "alpha_num = 0.02*time_key + add/10\n", + "\n", + "#ax.set_yscale(\"log\")\n", + "pixel_vals, cmap, data_label = select_data(3)\n", + "print(len(pixel_vals[time_key]))\n", + "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=0.6 + 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", + "pixel_vals, cmap, data_label = select_data(0)\n", + "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=0.5+ 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", + "pixel_vals, cmap, data_label = select_data(2)\n", + "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=0.45+ 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", + "\n", + "#counts, bins = np.histogram(pixel_vals[time_key], bins=bins_num, density = True)\n", + "#ax.bar(bins[:-1], counts, color=cmap(0.99-((time_key-add)*0.1)), \n", + " #alpha=0.6+alpha_num, label=data_label)\n", + "#pixel_vals, cmap, data_label = select_data(0)\n", + "#ax.bar(probabilities[time_key], bins[time_key][:-1], color=cmap(0.99-((time_key-add)*0.1)), alpha=0.5+alpha_num, label=data_label)\n", + "#pixel_vals, cmap, data_label = select_data(2)\n", + "#ax.bar(probabilities[time_key], bins[time_key][:-1], color=cmap(0.99-((time_key-add)*0.1)), alpha=0.45+alpha_num, label=data_label)\n", + " #print(all_FWHM[i])\n", + " #counts, bins, bars =ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num)\n", + " #print(counts.shape, bins.shape, bars)\n", + " \n", + "plt.ylabel('probability', fontsize=font_size)\n", + "plt.xlabel('pixel intensities', fontsize=font_size)\n", + "#plt.ylim(0.00001, 0.012)\n", + "#plt.ylim(0, 0.012)\n", + "#plt.xlim(0, 1500)\n", + "plt.xlim(0, 2500)\n", + "plt.title(title, fontsize=font_size)\n", + "plt.legend()\n", + "plt.show()\n", + "#fig.savefig(data_saveto+\"logy EA, AE, WT histograms- \"+title+\".jpg\", dpi=1000)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "df2f1fdf", + "metadata": {}, + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (fig.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", + " if (this.ResizeObserver === undefined) {\n", + " if (window.ResizeObserver !== undefined) {\n", + " this.ResizeObserver = window.ResizeObserver;\n", + " } else {\n", + " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", + " this.ResizeObserver = obs.ResizeObserver;\n", + " }\n", + " }\n", + "\n", + " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " if (entry.contentBoxSize instanceof Array) {\n", + " // Chrome 84 implements new version of spec.\n", + " width = entry.contentBoxSize[0].inlineSize;\n", + " height = entry.contentBoxSize[0].blockSize;\n", + " } else {\n", + " // Firefox implements old version of spec.\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " }\n", + " } else {\n", + " // Chrome <84 implements even older version of spec.\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " if (entry.devicePixelContentBoxSize) {\n", + " // Chrome 84 implements new version of spec.\n", + " canvas.setAttribute(\n", + " 'width',\n", + " entry.devicePixelContentBoxSize[0].inlineSize\n", + " );\n", + " canvas.setAttribute(\n", + " 'height',\n", + " entry.devicePixelContentBoxSize[0].blockSize\n", + " );\n", + " } else {\n", + " canvas.setAttribute('width', width * fig.ratio);\n", + " canvas.setAttribute('height', height * fig.ratio);\n", + " }\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " this.resizeObserverInstance.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " event.preventDefault();\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / fig.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", + " var x1 = msg['x1'] / fig.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / fig.ratio,\n", + " fig.canvas.height / fig.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * this.ratio;\n", + " var y = canvas_pos.y * this.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "\n", + "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", + "// prettier-ignore\n", + "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + " fig.cell_info[0].output_area.element.on(\n", + " 'cleared',\n", + " { fig: fig },\n", + " fig._remove_fig_handler\n", + " );\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / fig.ratio;\n", + " fig.cell_info[0].output_area.element.off(\n", + " 'cleared',\n", + " fig._remove_fig_handler\n", + " );\n", + " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / this.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function (event) {\n", + " var fig = event.data.fig;\n", + " if (event.target !== this) {\n", + " // Ignore bubbled events from children.\n", + " return;\n", + " }\n", + " fig.close_ws(fig, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "AE histograms\n" + ] + } + ], + "source": [ + "\n", + "fig = plt.figure(figsize=(9,6))\n", + "ax = fig.add_subplot(projection='3d')\n", + "ax.tick_params(axis='both', which='major', labelsize=font_size-7)\n", + "\n", + "frame_key = 3\n", + "condition = frame_names[frame_key]\n", + "pixel_vals, cmap, data_label = select_data(frame_key)\n", + "title = frame_names[frame_key] +\" (bins= \"+str(bins_num)+\")\"\n", + "\n", + "yticks = [0, 1, 2, 3, 4, 5, 6, 7, 8]\n", + "#for c, k in zip(colors, yticks):\n", + "for i in range(num_times):\n", + " #ax.set_zscale(\"log\")\n", + " time = str(time_array[8-i])+\" hrs\"\n", + " #ax.set_zlim(0.00001, 0.012)\n", + " # Plot the bar graph given by xs and ys on the plane y=k with 80% opacity.\n", + " counts, bins = np.histogram(pixel_vals[i], bins=bins_num, density = True)\n", + " ax.bar(bins[:-1], counts, zs=(8-i), zdir='y', color=cmap(0.99-(i*0.1)), alpha=1, label=time)\n", + " #counts, bins, bars = ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, \n", + " # bins=bins_num, stacked=True, alpha=alpha_num, color=cmap(0.99-(i*0.11)), label=time)\n", + " #ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))\n", + " #ax.zaxis.set_major_locator(mticker.MaxNLocator(integer=True))\n", + " all_counts[i] = counts \n", + " all_bins[i] = bins[:-1]\n", + "\n", + "ax.set_xlabel('pixel intensities', fontsize=font_size, labelpad= 8.0)\n", + "ax.set_ylabel('time (hours)', fontsize=font_size, labelpad= 7.0)\n", + "ax.set_zlabel('probability', fontsize=font_size, labelpad= 8.0)\n", + "ax.set_xlim(0, 2000)\n", + "\n", + "\n", + "#['1', '4', '7', '10', '13', '19', '22', '25', '28']\n", + "\n", + "# On the y axis let's only label the discrete values that we have data for.\n", + "ax.set_yticks(yticks)\n", + "ax.set_yticklabels(['1', '4', '7', '10', '13', '19', '22', '25', '28'])\n", + "\n", + "ax.set_title(title, fontsize=font_size)\n", + "ax.view_init(elev=15., azim=-70)\n", + "ax.legend(loc = 'upper left')\n", + "plt.show()\n", + "fig.savefig(data_saveto+\"3D histograms- \"+title+\".jpg\", dpi=1000)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f2505fe", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "font_size = 16\n", + "fig, ax = plt.subplots(figsize=(9,6))\n", + "ax.tick_params(axis='both', which='major', labelsize=font_size-2)\n", + "\n", + "frame_key = 0\n", + "condition = frame_names[frame_key]\n", + "all_times_all_values, cmap = select_data(frame_key)\n", + "title = frame_names[frame_key] +\" (bins= \"+str(bins_num)+\")\"\n", + "\n", + "for i in range(num_times):\n", + " time = str(time_array[i])+ \" hrs\"\n", + " #alpha_num = 0.83 + 0.02*i\n", + " alpha_num = 0.99 - 0.08*i\n", + " #print(0.99-(i*0.11)) #0.10 + (i*0.11) \n", + " print(alpha_num)\n", + " ax.set_yscale(\"log\")\n", + " #ax.hist(all_times_all_values[i], histtype=\"step\", density=True, bins=bins_num, stacked=True, \n", + " # alpha=1, color=cmap(0.99-(i*0.11)), fill=False)\n", + " counts, bins, bars = ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=alpha_num, color=cmap(0.99-(i*0.11)), label=time)\n", + " \n", + " all_FWHM[i] = FWHM(bins[:-1],counts)\n", + " all_counts[i] = counts \n", + " all_bins[i] = bins[:-1]\n", + " #print(all_FWHM[i])\n", + " #counts, bins, bars =ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num)\n", + " #print(counts.shape, bins.shape, bars)\n", + " \n", + "print(all_counts.shape, all_bins.shape)\n", + "plt.ylabel('probability', fontsize=font_size)\n", + "plt.xlabel('pixel intensities', fontsize=font_size)\n", + "plt.ylim(0.00001, 0.015)\n", + "plt.xlim(0, 2500)\n", + "plt.title(title, fontsize=font_size)\n", + "plt.legend()\n", + "plt.show()\n", + "#fig.savefig(data_saveto+\"logy stacked histograms- \"+title+\".jpg\", dpi=2000)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "29d84baa", + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "font_size = 16\n", + "fig, ax = plt.subplots(figsize=(9,6))\n", + "ax.tick_params(axis='both', which='major', labelsize=font_size-2)\n", + "\n", + "frame_key = 0\n", + "condition = frame_names[frame_key]\n", + "all_times_all_values, cmap = select_data(frame_key)\n", + "title = frame_names[frame_key] +\" (bins= \"+str(bins_num)+\")\"\n", + "\n", + "for i in range(num_times):\n", + " time = str(time_array[i])+ \" hrs\"\n", + " #alpha_num = 0.83 + 0.02*i\n", + " alpha_num = 0.99 - 0.08*i\n", + " #print(0.99-(i*0.11)) #0.10 + (i*0.11) \n", + " print(alpha_num)\n", + " ax.set_yscale(\"log\")\n", + " #ax.hist(all_times_all_values[i], histtype=\"step\", density=True, bins=bins_num, stacked=True, \n", + " # alpha=1, color=cmap(0.99-(i*0.11)), fill=False)\n", + " counts, bins, bars = ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=alpha_num, color=cmap(0.99-(i*0.11)), label=time)\n", + " \n", + " all_FWHM[i] = FWHM(bins[:-1],counts)\n", + " all_counts[i] = counts \n", + " all_bins[i] = bins[:-1]\n", + " #print(all_FWHM[i])\n", + " #counts, bins, bars =ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num)\n", + " #print(counts.shape, bins.shape, bars)\n", + " \n", + "print(all_counts.shape, all_bins.shape)\n", + "plt.ylabel('probability', fontsize=font_size)\n", + "plt.xlabel('pixel intensities', fontsize=font_size)\n", + "plt.ylim(0.00001, 0.015)\n", + "plt.xlim(0, 2500)\n", + "plt.title(title, fontsize=font_size)\n", + "plt.legend()\n", + "plt.show()\n", + "#fig.savefig(data_saveto+\"logy stacked histograms- \"+title+\".jpg\", dpi=2000)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "461a6277", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "font_size = 16\n", + "fig, ax = plt.subplots(figsize=(9,6))\n", + "plt.plot(time_array, all_FWHM, '-o', c=cmap(0.65))\n", + "plt.ylabel(\"FWHM\",fontsize=font_size)\n", + "plt.xlabel(\"time (hours)\",fontsize=font_size) \n", + "ax.tick_params(direction='in', which='both', labelsize=font_size-2)\n", + "plt.title(title, fontsize=font_size)\n", + "plt.ylim(100, 500)\n", + "plt.show()\n", + "fig.savefig(data_saveto+\"FWHM- \"+title+\".jpg\", dpi=600)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ca985634", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "font_size = 16\n", + "fig, ax = plt.subplots(figsize=(9,6))\n", + "ax.tick_params(axis='both', which='major', labelsize=font_size-2)\n", + "\n", + "time_key = 0\n", + "time = time_array[time_key]\n", + "all_times_all_values, cmap = select_data(frame_key)\n", + "title = str(time) +\"hrs, (bins= \"+str(bins_num)+\")\"\n", + "\n", + "\n", + " alpha_num = 0.83 + 0.02*i\n", + " #alpha_num = 0.99 - 0.02*i\n", + " #print(0.99-(i*0.1)) #logy??\n", + " #print(alpha_num)\n", + " ax.set_yscale(\"log\")\n", + " counts, bins, bars = ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=alpha_num, color=cmap(0.99-(i*0.11)), label=time)\n", + " all_FWHM[i] = FWHM(bins[:-1],counts)\n", + " all_counts[i] = counts \n", + " all_bins[i] = bins[:-1]\n", + " #print(all_FWHM[i])\n", + " #counts, bins, bars =ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num)\n", + " #print(counts.shape, bins.shape, bars)\n", + " \n", + "print(all_counts.shape, all_bins.shape)\n", + "plt.ylabel('probability', fontsize=font_size)\n", + "plt.xlabel('pixel intensities', fontsize=font_size)\n", + "plt.ylim(0.00001, 0.015)\n", + "#plt.xlim(0, 2000)\n", + "plt.title(title, fontsize=font_size)\n", + "plt.legend()\n", + "plt.show()\n", + "fig.savefig(data_saveto+\"logy stacked histograms- \"+title+\".jpg\", dpi=2000)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "af3f7c44", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "font_size = 10\n", + "\n", + "fig, axs = plt.subplots(3, 3, figsize=(9.5,9))\n", + "for i, ax in enumerate(axs.flatten()):\n", + " show_histograms(i, ax, all_times_all_values)\n", + "plt.show()\n", + "fig.savefig(data_saveto+\"all histograms for -\"+condition+\" (bins= \"+str(bins_num)+\").jpg\", dpi=800)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3d72074a", + "metadata": {}, + "outputs": [], + "source": [ + "frame_key = 2\n", + "time_index = 8\n", + "condition = frame_names[frame_key]\n", + "time = time_array[time_index]\n", + "details = condition + \", t= \" + str(time) + \" hrs, fsize= 1000\"\n", + "\n", + "#def all_pixel_values\n", + "files_list = [files_1015_s1, files_1015_s2, files_95_s1, files_95_s2]\n", + "all_vals_list = []\n", + "for l in range(4):\n", + " list_to_add = files_list[l]\n", + " if l < 2:\n", + " for j in range(0,54, arr_length):\n", + " #print(list_to_add[j])\n", + " im_array = tiff_file.imread(list_to_add[j+time_index],key=[frame_key]) \n", + " im_array = filtimage(im_array, 1000)\n", + " im_ravel = im_array.ravel()\n", + " all_vals_list.extend(im_ravel)\n", + " else:\n", + " for j in range(0,26, arr_length):\n", + " #print(list_to_add[j+time_index])\n", + " im_array = tiff_file.imread(list_to_add[j+time_index],key=[frame_key]) \n", + " im_array = filtimage(im_array, 1000)\n", + " im_ravel = im_array.ravel()\n", + " all_vals_list.extend(im_ravel) \n", + " #print(len(im_ravel))\n", + " #print(list_to_add[0])\n", + " #print(' ')\n", + "print(\"pixel intensities found for all images of \"+ details)\n", + "list_length = 49766400 #len(all_vals_list)\n", + "print(\"total number of pixel values = \"+ str(list_length))\n", + "mean = sum(all_vals_list) / len(all_vals_list)\n", + "print(\"mean intensity value = %5.3f\" %(mean))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "965f4521", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "445bb71f", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "aaa6e0c6", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "078a49a9", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "\n", + "\n", + "frame_key = 3\n", + "condition = frame_names[frame_key]\n", + "#details = condition + \", t= \" + str(time) + \" hrs, fsize= 1000\"\n", + "details = condition + \", fsize= 1000\"\n", + "\n", + "files_list = [files_1015_s1, files_1015_s2, files_95_s1, files_95_s2]\n", + "all_times_all_values = np.zeros((num_times, list_length))\n", + "\n", + "for i in range(num_times):\n", + " all_times_all_values[i] = all_pixel_values(frame_key, i)\n", + " means[frame_key][i] = sum(all_times_all_values[i]) / len(all_times_all_values[i])\n", + " medians[frame_key][i] = median(all_times_all_values[i])\n", + " modes[frame_key][i] = mode(all_times_all_values[i])\n", + " std_devs[frame_key][i] = np.std(all_times_all_values[i])\n", + "\n", + "print(\"pixel intensities found for all images of \"+ details)\n", + "print(\"means:\")\n", + "print(means)\n", + "print(' ')\n", + "print(\"medians:\")\n", + "print(medians)\n", + "print(' ')\n", + "print(\"modes:\")\n", + "print(modes)\n", + "print(' ')\n", + "print(\"std_devs:\")\n", + "print(std_devs)\n", + "print(' ')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "eba2cff0", + "metadata": {}, + "outputs": [], + "source": [ + "print(\"pixel intensities found for all images of \"+ details)\n", + "print(\"means:\")\n", + "print(np.stack(means))\n", + "print(' ')\n", + "print(\"medians:\")\n", + "print(medians)\n", + "print(' ')\n", + "print(\"modes:\")\n", + "print(modes)\n", + "print(' ')\n", + "print(\"std_devs:\")\n", + "print(std_devs)\n", + "print(' ')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ab7ba4bb", + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "### plot average values and std. error for L1 correlation lengths\n", + "cmap_num = (arr_length*2) - 2\n", + "fig_size = 9.5, 20 #20/1.618\n", + "fig = plt.figure(figsize=(fig_size))\n", + "gs = fig.add_gridspec(4, top=0.95, hspace=0.09)\n", + "axs = gs.subplots(sharex=False, sharey=False)\n", + "#fig, axs = plt.subplots(3, figsize=(fig_size))\n", + "markerSize = 8\n", + "font_size = 16\n", + "title = condition \n", + "\n", + "ylim = 200, 650\n", + "\n", + "#axs[0].set_title(title, fontsize= (font_size))\n", + "axs[0].set( ylabel='mean intensity')\n", + "axs[0].set_ylim(ylim)\n", + "axs[0].plot(time_array, means[0],'-o', ms=markerSize, c='r', label = frame_names[0])\n", + "#axs[0].plot(time_array, means[1],'-o', ms=markerSize, c='b', label = frame_names[1])\n", + "axs[0].plot(time_array, means[2],'-o', ms=markerSize, c='g', label = frame_names[2])\n", + "axs[0].plot(time_array, means[3],'-o', ms=markerSize, c='k', label = frame_names[3])\n", + "axs[0].legend()\n", + "\n", + "axs[1].set( ylabel='median intensity')\n", + "axs[1].set_ylim(ylim)\n", + "axs[1].plot(time_array, medians[0],'-o', ms=markerSize, c='r', label = frame_names[0])\n", + "#axs[1].plot(time_array, medians[1],'-o', ms=markerSize, c='b', label = frame_names[1])\n", + "axs[1].plot(time_array, medians[2],'-o', ms=markerSize, c='g', label = frame_names[2])\n", + "axs[1].plot(time_array, medians[3],'-o', ms=markerSize, c='k', label = frame_names[3])\n", + "axs[1].legend()\n", + "\n", + "axs[2].set( ylabel='mode intensity')\n", + "axs[2].set_ylim(ylim)\n", + "axs[2].plot(time_array, modes[0],'-o', ms=markerSize, c='r', label = frame_names[0])\n", + "#axs[2].plot(time_array, modes[1],'-o', ms=markerSize, c='b', label = frame_names[1])\n", + "axs[2].plot(time_array, modes[2],'-o', ms=markerSize, c='g', label = frame_names[2])\n", + "axs[2].plot(time_array, modes[3],'-o', ms=markerSize, c='k', label = frame_names[3])\n", + "axs[2].legend()\n", + "\n", + "axs[3].set( ylabel='std deviation')\n", + "axs[3].set( xlabel=\"Time (hrs after adding KaiC)\")\n", + "axs[3].set_ylim(100, 550)\n", + "axs[3].plot(time_array, std_devs[0],'-o', ms=markerSize, c='r', label = frame_names[0])\n", + "#axs[3].plot(time_array, std_devs[1],'-o', ms=markerSize, c='b', label = frame_names[1])\n", + "axs[3].plot(time_array, std_devs[2],'-o', ms=markerSize, c='g', label = frame_names[2])\n", + "axs[3].plot(time_array, std_devs[3],'-o', ms=markerSize, c='k', label = frame_names[3])\n", + "axs[3].legend()\n", + " \n", + "for ax in axs.flat:\n", + " ax.tick_params(axis='both', which='major', labelsize=(font_size-3))\n", + " ax.xaxis.get_label().set_fontsize(font_size)\n", + " ax.yaxis.get_label().set_fontsize(font_size)\n", + "\n", + "#plt.subplot_tool()\n", + "plt.show()\n", + "fig.savefig(data_saveto+\"all histograms results.jpg\", dpi=800)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0baddb6f", + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "key = 0\n", + "condition = frame_names[key]\n", + "num_rows = 3\n", + "fig_height = num_rows*3#2.3\n", + "#time_array.append(0)\n", + "fig, axs = plt.subplots(num_rows, 3, figsize=(9.5,fig_height))\n", + "for i, ax in enumerate(axs.flatten()):\n", + " show_histograms(i, ax, all_times_all_values)\n", + "plt.show()\n", + "fig.savefig(data_saveto+\"all histograms for -\"+condition+\" (fsize= 1000).jpg\", dpi=800)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "acdc9d21", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "fig, ax = plt.subplots(figsize=(9,6))\n", + "ax.tick_params(axis='both', which='major', labelsize=font_size)\n", + "plt.hist(all_vals_list, density=True, bins='auto') # density=False would make counts\n", + "plt.ylabel('probability', fontsize=font_size)\n", + "plt.xlabel('pixel intensities', fontsize=font_size)\n", + "title = details\n", + "plt.title(title, fontsize=font_size)\n", + "plt.show()\n", + "fig.savefig(data_saveto+\"histogram for all rows -\"+details+\".jpg\", dpi=dpi_num)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e48321e5", + "metadata": {}, + "outputs": [], + "source": [ + "frame_key = 3\n", + "### \"frame_key\" specifies which frame of each tiff file will be analyzed (each frame of my tiff is for a different condition)\n", + "### e.g. \"key = 0\" dictates that the first frame of each tiff file should be analyzed\n", + "condition = frame_names[frame_key]\n", + "print(\"condition: \"+condition)\n", + "\n", + "row = 1\n", + "### choose which set of tiff files should be analyzed, row1, row2 or row3\n", + "\n", + "fig_height = num_rows*2.3\n", + "time_array.append(0)\n", + "i = 0\n", + "fig, axs = plt.subplots(num_rows, 4, figsize=(10,fig_height))\n", + "for j, ax in enumerate(axs.flatten()):\n", + " if j % 2 == 0:\n", + " show_raw_images(row, ax, i, frame_key)\n", + " else:\n", + " show_image_histograms(row, ax, i, frame_key)\n", + " i = i + 1 \n", + "plt.show()\n", + "time_array.remove(0)\n", + "print(time_array)\n", + "details = \" (row\"+str(row)+\")\"\n", + "### option to save this figure (uncomment below)\n", + "fig.savefig(data_saveto+\"histograms for \"+condition+details+\".jpg\", dpi=dpi_num)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "07f0fd03", + "metadata": {}, + "outputs": [], + "source": [ + "image = tiff_file.imread(files[9],key=[0])\n", + "print(np.median(image))\n", + "print(np.mean(image))\n", + "print(np.std(image))\n", + "\n", + "return_which = \" \"\n", + "\n", + "def analyze_image(image, return_which):\n", + " median_val = np.median(image)\n", + " mean_val = np.mean(image)\n", + " std_dev_val = np.std(image)\n", + " if return_which == \"mean\":\n", + " return mean_val\n", + " if return_which == \"median\":\n", + " return median_val\n", + " if return_which == \"std_dev\":\n", + " return std_dev_val\n", + " \n", + "analyze_image(image, \"mean\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1710b5dc", + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "### \"key\" specifies which frame of each tiff file will be analyzed (each frame of my tiff is for a different condition)\n", + "### e.g. \"key = 0\" dictates that the first frame of each tiff file should be analyzed, tiff_file.imread(files[i],key=[key]\n", + "key = 3\n", + "condition = frame_names[key]\n", + "print(condition)\n", + "\n", + "### cmap dictates the color gradient used in plots; options: 'Reds' 'Blues' 'Greens' 'Greys' 'Purples' ...\n", + "cmap = matplotlib.cm.get_cmap('Greys') \n", + "\n", + "### Set up empty arrays to save results in\n", + "all_means = np.zeros((total_rows,arr_length))\n", + "avg_means = np.empty(arr_length)\n", + "stderror_means = np.empty(arr_length)\n", + "\n", + "all_medians = np.zeros((total_rows,arr_length))\n", + "avg_medians = np.empty(arr_length)\n", + "stderror_medians = np.empty(arr_length)\n", + "\n", + "all_std_dev = np.zeros((total_rows,arr_length))\n", + "avg_std_dev = np.empty(arr_length)\n", + "stderror_std_dev = np.empty(arr_length)\n", + "\n", + "### cmap_num is used the when plotting each curve to adjust the color gradient according to the total number of time points\n", + "### e.g. for i in range(arr_length): the color of each curve is determined by c=cmap(0.9-(i/cmap_num))\n", + "cmap_num = (arr_length*2) - 2\n", + "\n", + "for i in range(arr_length): \n", + "### \"im_corr\" is the actual SIA function which filters, bins, and fourier transforms tiff images to generate SIA curves\n", + " all_means[0,i] = analyze_image(tiff_file.imread(files[i],key=[key]), \"mean\")\n", + " all_means[1,i] = analyze_image(tiff_file.imread(files[i+arr_length],key=[key]), \"mean\")\n", + " all_means[2,i] = analyze_image(tiff_file.imread(files[i+(arr_length*2)],key=[key]), \"mean\")\n", + " all_means[3,i] = analyze_image(tiff_file.imread(files[i+(arr_length*3)],key=[key]), \"mean\")\n", + " all_means[4,i] = analyze_image(tiff_file.imread(files[i+(arr_length*4)],key=[key]), \"mean\")\n", + " all_means[5,i] = analyze_image(tiff_file.imread(files[i+(arr_length*5)],key=[key]), \"mean\")\n", + " \n", + " all_medians[0,i] = analyze_image(tiff_file.imread(files[i],key=[key]), \"median\")\n", + " all_medians[1,i] = analyze_image(tiff_file.imread(files[i+arr_length],key=[key]), \"median\")\n", + " all_medians[2,i] = analyze_image(tiff_file.imread(files[i+(arr_length*2)],key=[key]), \"median\")\n", + " all_medians[3,i] = analyze_image(tiff_file.imread(files[i+(arr_length*3)],key=[key]), \"median\")\n", + " all_medians[4,i] = analyze_image(tiff_file.imread(files[i+(arr_length*4)],key=[key]), \"median\")\n", + " all_medians[5,i] = analyze_image(tiff_file.imread(files[i+(arr_length*5)],key=[key]), \"median\")\n", + " \n", + " all_std_dev[0,i] = analyze_image(tiff_file.imread(files[i],key=[key]), \"std_dev\")\n", + " all_std_dev[1,i] = analyze_image(tiff_file.imread(files[i+arr_length],key=[key]), \"std_dev\")\n", + " all_std_dev[2,i] = analyze_image(tiff_file.imread(files[i+(arr_length*2)],key=[key]), \"std_dev\")\n", + " all_std_dev[3,i] = analyze_image(tiff_file.imread(files[i+(arr_length*3)],key=[key]), \"std_dev\")\n", + " all_std_dev[4,i] = analyze_image(tiff_file.imread(files[i+(arr_length*4)],key=[key]), \"std_dev\")\n", + " all_std_dev[5,i] = analyze_image(tiff_file.imread(files[i+(arr_length*5)],key=[key]), \"std_dev\")\n", + " \n", + "### corresponding x-values calculated according to the length of a SIA curve array (r1_corr_rad_array[0]) and pixel size\n", + "avg_means = all_means.mean(axis=0)\n", + "stderror_means = all_means.std(axis=0)/np.sqrt(total_rows)\n", + "\n", + "avg_medians = all_medians.mean(axis=0)\n", + "stderror_medians = all_medians.std(axis=0)/np.sqrt(total_rows)\n", + "\n", + "avg_std_dev = all_std_dev.mean(axis=0)\n", + "stderror_std_dev = all_std_dev.std(axis=0)/np.sqrt(total_rows)\n", + "print(avg_means)\n", + "print(avg_medians)\n", + "print(avg_std_dev)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6fee41da", + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "### plot average values and std. error for L1 correlation lengths\n", + "fig = plt.figure(figsize=(9.5, 20))\n", + "gs = fig.add_gridspec(3, top=0.95, hspace=0.09)\n", + "axs = gs.subplots(sharex=False, sharey=False)\n", + "#fig, axs = plt.subplots(3, figsize=(fig_size))\n", + "markerSize = 8\n", + "title = condition +\" image intensity analysis\"\n", + "\n", + "for i in range(arr_length):\n", + " axs[0].set_title(title, fontsize= (font_size))\n", + " axs[0].set( ylabel='mean image intensity')\n", + " #axs[0].set_ylim(0, 400)\n", + " axs[0].plot(time_array[i], avg_means[i],'s', ms=markerSize, c=cmap(0.9-(i/cmap_num)))\n", + " axs[0].errorbar(time_array[i], avg_means[i], yerr = stderror_means[i], fmt = 'none', \n", + " ecolor=cmap(0.9-(i/cmap_num)), capsize=10)\n", + " \n", + " axs[1].set( ylabel='median image intensity')\n", + " #axs[1].set_ylim(0, 60)\n", + " axs[1].plot(time_array[i], avg_medians[i],'s', ms=markerSize, c=cmap(0.9-(i/cmap_num)))\n", + " axs[1].errorbar(time_array[i], avg_medians[i], yerr = stderror_medians[i], fmt = 'none', \n", + " ecolor=cmap(0.9-(i/cmap_num)), capsize=10)\n", + " \n", + " axs[2].set( ylabel='std dev of image intensity')\n", + " #axs[2].set_ylim(0, 60)\n", + " axs[2].plot(time_array[i], avg_std_dev[i],'s', ms=markerSize, c=cmap(0.9-(i/cmap_num)))\n", + " axs[2].errorbar(time_array[i], avg_std_dev[i], yerr = avg_std_dev[i], fmt = 'none', \n", + " ecolor=cmap(0.9-(i/cmap_num)), capsize=10)\n", + " \n", + "for ax in axs.flat:\n", + " ax.tick_params(axis='both', which='major', labelsize=(font_size-3))\n", + " ax.xaxis.get_label().set_fontsize(font_size)\n", + " ax.yaxis.get_label().set_fontsize(font_size)\n", + "\n", + "#plt.subplot_tool()\n", + "plt.show()\n", + "fig.savefig(data_saveto+title+\".jpg\", dpi=dpi_num)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6f7416d2", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "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.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.ipynb_checkpoints/simplified image histograms (2-10-23)-checkpoint.ipynb b/.ipynb_checkpoints/simplified image histograms (2-10-23)-checkpoint.ipynb new file mode 100644 index 0000000..c999067 --- /dev/null +++ b/.ipynb_checkpoints/simplified image histograms (2-10-23)-checkpoint.ipynb @@ -0,0 +1,4055 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 5, + "id": "f7f0d53e", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib notebook\n", + "import numpy as np\n", + "from numpy.fft import fft2, ifft2, fftshift\n", + "import matplotlib\n", + "from matplotlib import pyplot as plt\n", + "from matplotlib import cm\n", + "import scipy\n", + "from scipy import stats\n", + "from statistics import mode\n", + "from scipy.optimize import curve_fit\n", + "from scipy.ndimage import gaussian_filter1d as gf1d\n", + "from scipy.ndimage import gaussian_filter as gf\n", + "from scipy.ndimage import uniform_filter as uf\n", + "\n", + "from skimage.transform import downscale_local_mean #For binning\n", + "from skimage.filters import threshold_otsu, threshold_local\n", + "\n", + "import xarray as xr #package for labeling and adding metadata to multi-dimensional arrays\n", + "from statistics import median\n", + "from statistics import mode\n", + "\n", + "import sys\n", + "#sys.path.append(\"../kai_colloids/PyDDM\") #must point to the PyDDM folder\n", + "#import ddm_analysis_and_fitting as ddm \n", + "\n", + "import tiff_file \n", + "\n", + "import io \n", + "import sys\n", + "import csv\n", + "\n", + "from PIL import Image\n", + "\n", + "import os\n", + "import glob #glob is helpful for searching for filenames or directories\n", + "import pickle #for saving data\n", + "### usually this block prints out \"nd2reader module not found. Reading of .nd2 files disabled.\" on the first run\n", + "### this is fine (unless you need to read .nd2 files), just re-run this block to make the error go away" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "f41c7dfa", + "metadata": {}, + "outputs": [], + "source": [ + "def filter_and_shift(image, filtersize):\n", + " image = (image*1.0) - ((uf(image,filtersize))*1) #(image) - unifrom-filtered(image) subtracts background\n", + " flat_im = image.ravel()\n", + " shifted_im = flat_im + np.abs(flat_im.min())\n", + " return shifted_im\n", + "\n", + "def subtract_mean_and_shift(image):\n", + " image = (image*1.0) - (np.mean(image)) \n", + " flat_im = image.ravel()\n", + " shifted_im = flat_im + np.abs(flat_im.min())\n", + " return shifted_im" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "617edfe1", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "found 3 files\n", + " 0 \t top_s1_40x_t1_MMStack_Pos0.ome.tif\n", + " 1 \t top_s1_40x_t2_MMStack_Pos0.ome.tif\n", + " 2 \t top_s1_40x_t3_MMStack_Pos0.ome.tif\n" + ] + } + ], + "source": [ + "date = \"9-7-22\"\n", + "exp = \"top\"\n", + "\n", + "### \"data_dir\" is the pathway to the folder holding the tiff files to be analyzed --> change to your folder location\n", + "data_dir = \"Z:\\\\Maya N\\\\data\\\\\"+date+\"\\\\\"+exp +\"\\\\\"\n", + "data_save = \"Z:\\\\Maya N\\\\analysis\\\\\"+date+\"\\\\\"\n", + "### \"plot_saveto\" is the pathway to the folder where plots and results will be saved\n", + "plot_saveto = data_save\n", + "\n", + "files = glob.glob(data_dir+\"*tif\") ### this should generate an ordered list of files in \"data_dir\" which have \"_t\" in their name\n", + "print(\"found %i files\" % len(files))\n", + "for i,f in enumerate(files): print (' %i \\t %s' % (i, f.split('\\\\')[-1]))" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "1213e586", + "metadata": {}, + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (fig.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", + " if (this.ResizeObserver === undefined) {\n", + " if (window.ResizeObserver !== undefined) {\n", + " this.ResizeObserver = window.ResizeObserver;\n", + " } else {\n", + " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", + " this.ResizeObserver = obs.ResizeObserver;\n", + " }\n", + " }\n", + "\n", + " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " if (entry.contentBoxSize instanceof Array) {\n", + " // Chrome 84 implements new version of spec.\n", + " width = entry.contentBoxSize[0].inlineSize;\n", + " height = entry.contentBoxSize[0].blockSize;\n", + " } else {\n", + " // Firefox implements old version of spec.\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " }\n", + " } else {\n", + " // Chrome <84 implements even older version of spec.\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " if (entry.devicePixelContentBoxSize) {\n", + " // Chrome 84 implements new version of spec.\n", + " canvas.setAttribute(\n", + " 'width',\n", + " entry.devicePixelContentBoxSize[0].inlineSize\n", + " );\n", + " canvas.setAttribute(\n", + " 'height',\n", + " entry.devicePixelContentBoxSize[0].blockSize\n", + " );\n", + " } else {\n", + " canvas.setAttribute('width', width * fig.ratio);\n", + " canvas.setAttribute('height', height * fig.ratio);\n", + " }\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " this.resizeObserverInstance.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " event.preventDefault();\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / fig.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", + " var x1 = msg['x1'] / fig.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / fig.ratio,\n", + " fig.canvas.height / fig.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * this.ratio;\n", + " var y = canvas_pos.y * this.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "\n", + "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", + "// prettier-ignore\n", + "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + " fig.cell_info[0].output_area.element.on(\n", + " 'cleared',\n", + " { fig: fig },\n", + " fig._remove_fig_handler\n", + " );\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / fig.ratio;\n", + " fig.cell_info[0].output_area.element.off(\n", + " 'cleared',\n", + " fig._remove_fig_handler\n", + " );\n", + " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / this.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function (event) {\n", + " var fig = event.data.fig;\n", + " if (event.target !== this) {\n", + " // Ignore bubbled events from children.\n", + " return;\n", + " }\n", + " fig.close_ws(fig, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (fig.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", + " if (this.ResizeObserver === undefined) {\n", + " if (window.ResizeObserver !== undefined) {\n", + " this.ResizeObserver = window.ResizeObserver;\n", + " } else {\n", + " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", + " this.ResizeObserver = obs.ResizeObserver;\n", + " }\n", + " }\n", + "\n", + " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " if (entry.contentBoxSize instanceof Array) {\n", + " // Chrome 84 implements new version of spec.\n", + " width = entry.contentBoxSize[0].inlineSize;\n", + " height = entry.contentBoxSize[0].blockSize;\n", + " } else {\n", + " // Firefox implements old version of spec.\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " }\n", + " } else {\n", + " // Chrome <84 implements even older version of spec.\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " if (entry.devicePixelContentBoxSize) {\n", + " // Chrome 84 implements new version of spec.\n", + " canvas.setAttribute(\n", + " 'width',\n", + " entry.devicePixelContentBoxSize[0].inlineSize\n", + " );\n", + " canvas.setAttribute(\n", + " 'height',\n", + " entry.devicePixelContentBoxSize[0].blockSize\n", + " );\n", + " } else {\n", + " canvas.setAttribute('width', width * fig.ratio);\n", + " canvas.setAttribute('height', height * fig.ratio);\n", + " }\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " this.resizeObserverInstance.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " event.preventDefault();\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / fig.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", + " var x1 = msg['x1'] / fig.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / fig.ratio,\n", + " fig.canvas.height / fig.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * this.ratio;\n", + " var y = canvas_pos.y * this.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "\n", + "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", + "// prettier-ignore\n", + "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + " fig.cell_info[0].output_area.element.on(\n", + " 'cleared',\n", + " { fig: fig },\n", + " fig._remove_fig_handler\n", + " );\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / fig.ratio;\n", + " fig.cell_info[0].output_area.element.off(\n", + " 'cleared',\n", + " fig._remove_fig_handler\n", + " );\n", + " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / this.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function (event) {\n", + " var fig = event.data.fig;\n", + " if (event.target !== this) {\n", + " // Ignore bubbled events from children.\n", + " return;\n", + " }\n", + " fig.close_ws(fig, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (fig.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", + " if (this.ResizeObserver === undefined) {\n", + " if (window.ResizeObserver !== undefined) {\n", + " this.ResizeObserver = window.ResizeObserver;\n", + " } else {\n", + " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", + " this.ResizeObserver = obs.ResizeObserver;\n", + " }\n", + " }\n", + "\n", + " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " if (entry.contentBoxSize instanceof Array) {\n", + " // Chrome 84 implements new version of spec.\n", + " width = entry.contentBoxSize[0].inlineSize;\n", + " height = entry.contentBoxSize[0].blockSize;\n", + " } else {\n", + " // Firefox implements old version of spec.\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " }\n", + " } else {\n", + " // Chrome <84 implements even older version of spec.\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " if (entry.devicePixelContentBoxSize) {\n", + " // Chrome 84 implements new version of spec.\n", + " canvas.setAttribute(\n", + " 'width',\n", + " entry.devicePixelContentBoxSize[0].inlineSize\n", + " );\n", + " canvas.setAttribute(\n", + " 'height',\n", + " entry.devicePixelContentBoxSize[0].blockSize\n", + " );\n", + " } else {\n", + " canvas.setAttribute('width', width * fig.ratio);\n", + " canvas.setAttribute('height', height * fig.ratio);\n", + " }\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " this.resizeObserverInstance.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " event.preventDefault();\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / fig.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", + " var x1 = msg['x1'] / fig.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / fig.ratio,\n", + " fig.canvas.height / fig.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * this.ratio;\n", + " var y = canvas_pos.y * this.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "\n", + "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", + "// prettier-ignore\n", + "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + " fig.cell_info[0].output_area.element.on(\n", + " 'cleared',\n", + " { fig: fig },\n", + " fig._remove_fig_handler\n", + " );\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / fig.ratio;\n", + " fig.cell_info[0].output_area.element.off(\n", + " 'cleared',\n", + " fig._remove_fig_handler\n", + " );\n", + " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / this.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function (event) {\n", + " var fig = event.data.fig;\n", + " if (event.target !== this) {\n", + " // Ignore bubbled events from children.\n", + " return;\n", + " }\n", + " fig.close_ws(fig, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (fig.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", + " if (this.ResizeObserver === undefined) {\n", + " if (window.ResizeObserver !== undefined) {\n", + " this.ResizeObserver = window.ResizeObserver;\n", + " } else {\n", + " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", + " this.ResizeObserver = obs.ResizeObserver;\n", + " }\n", + " }\n", + "\n", + " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " if (entry.contentBoxSize instanceof Array) {\n", + " // Chrome 84 implements new version of spec.\n", + " width = entry.contentBoxSize[0].inlineSize;\n", + " height = entry.contentBoxSize[0].blockSize;\n", + " } else {\n", + " // Firefox implements old version of spec.\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " }\n", + " } else {\n", + " // Chrome <84 implements even older version of spec.\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " if (entry.devicePixelContentBoxSize) {\n", + " // Chrome 84 implements new version of spec.\n", + " canvas.setAttribute(\n", + " 'width',\n", + " entry.devicePixelContentBoxSize[0].inlineSize\n", + " );\n", + " canvas.setAttribute(\n", + " 'height',\n", + " entry.devicePixelContentBoxSize[0].blockSize\n", + " );\n", + " } else {\n", + " canvas.setAttribute('width', width * fig.ratio);\n", + " canvas.setAttribute('height', height * fig.ratio);\n", + " }\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " this.resizeObserverInstance.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " event.preventDefault();\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / fig.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", + " var x1 = msg['x1'] / fig.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / fig.ratio,\n", + " fig.canvas.height / fig.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * this.ratio;\n", + " var y = canvas_pos.y * this.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "\n", + "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", + "// prettier-ignore\n", + "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + " fig.cell_info[0].output_area.element.on(\n", + " 'cleared',\n", + " { fig: fig },\n", + " fig._remove_fig_handler\n", + " );\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / fig.ratio;\n", + " fig.cell_info[0].output_area.element.off(\n", + " 'cleared',\n", + " fig._remove_fig_handler\n", + " );\n", + " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / this.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function (event) {\n", + " var fig = event.data.fig;\n", + " if (event.target !== this) {\n", + " // Ignore bubbled events from children.\n", + " return;\n", + " }\n", + " fig.close_ws(fig, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "chosen_tiff = files[2]\n", + "\n", + "chosen_image = tiff_file.imread(chosen_tiff,key=[2]) #key=[ ] selects which frame of the tiff file will be read\n", + "\n", + "%matplotlib notebook\n", + "fig, ax = plt.subplots(figsize=(6,4)) #set up 'figure 1'\n", + "title = str((chosen_tiff.split('\\\\')[-1])[:-4]) #splits the full file name into only the relevent info\n", + "ax.set_title(title, fontsize=10)\n", + "ax.imshow(chosen_image, cmap='gray') #'cmap' is the color map used to display the image, 'gray' is short for greyscale\n", + "ax.axis('off')\n", + "\n", + "num_of_bins = 500 # number of histogram bins, changing this effects the histogram (can be set to \"auto\")\n", + "\n", + "fig, ax2 = plt.subplots(figsize=(6,4)) #set up 'figure 2'\n", + "ax2.hist(chosen_image.ravel(), bins=num_of_bins) #plots a histogram for a given list; \n", + " #___.ravel() converts a 2D image array to a 1D list of pixel intensities\n", + "ax2.set_xlabel(\"pixel intensity\")\n", + "ax2.set_ylabel(\"count\")\n", + "plt.show()\n", + "\n", + "fig, ax3 = plt.subplots(figsize=(6,4)) #set up 'figure 2'\n", + "intensities_list = filter_and_shift(chosen_image, 1000) \n", + "ax3.hist(intensities_list, bins=num_of_bins)\n", + "ax3.set_xlabel(\"pixel intensity\")\n", + "ax3.set_ylabel(\"count\")\n", + "plt.show()\n", + "\n", + "fig, ax4 = plt.subplots(figsize=(6,4)) #set up 'figure 2'\n", + "intensities_list = subtract_mean_and_shift(chosen_image) #subtract_mean_and_shift\n", + "ax4.hist(intensities_list, bins=num_of_bins)\n", + "ax4.set_xlabel(\"pixel intensity\")\n", + "ax4.set_ylabel(\"count\")\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7760f419", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "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.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.ipynb_checkpoints/simplified image histograms - maya-checkpoint.ipynb b/.ipynb_checkpoints/simplified image histograms - maya-checkpoint.ipynb new file mode 100644 index 0000000..8bbe372 --- /dev/null +++ b/.ipynb_checkpoints/simplified image histograms - maya-checkpoint.ipynb @@ -0,0 +1,1819 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "f7f0d53e", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodepackbits\n", + " warnings.warn(\"failed to import %s\" % module_function)\n", + "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodelzw\n", + " warnings.warn(\"failed to import %s\" % module_function)\n", + "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.unpackints\n", + " warnings.warn(\"failed to import %s\" % module_function)\n" + ] + } + ], + "source": [ + "%matplotlib notebook\n", + "import numpy as np\n", + "from numpy.fft import fft2, ifft2, fftshift\n", + "import matplotlib\n", + "from matplotlib import pyplot as plt\n", + "from matplotlib import cm\n", + "import scipy\n", + "from scipy import stats\n", + "from statistics import mode\n", + "from scipy.optimize import curve_fit\n", + "from scipy.ndimage import gaussian_filter1d as gf1d\n", + "from scipy.ndimage import gaussian_filter as gf\n", + "from scipy.ndimage import uniform_filter as uf\n", + "\n", + "from skimage.transform import downscale_local_mean #For binning\n", + "from skimage.filters import threshold_otsu, threshold_local\n", + "\n", + "import xarray as xr #package for labeling and adding metadata to multi-dimensional arrays\n", + "from statistics import median\n", + "from statistics import mode\n", + "\n", + "import sys\n", + "#sys.path.append(\"../kai_colloids/PyDDM\") #must point to the PyDDM folder\n", + "#import ddm_analysis_and_fitting as ddm \n", + "\n", + "import tiff_file \n", + "\n", + "import io \n", + "import sys\n", + "import csv\n", + "\n", + "from PIL import Image\n", + "\n", + "import os\n", + "import glob #glob is helpful for searching for filenames or directories\n", + "import pickle #for saving data\n", + "### usually this block prints out \"nd2reader module not found. Reading of .nd2 files disabled.\" on the first run\n", + "### this is fine (unless you need to read .nd2 files), just re-run this block to make the error go away" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "f41c7dfa", + "metadata": {}, + "outputs": [], + "source": [ + "def subtract_mean_and_shift(image):\n", + " image = (image*1.0) - (np.mean(image)) \n", + " flat_im = image.ravel()\n", + " shifted_im = flat_im + np.abs(flat_im.min())\n", + " return shifted_im\n", + "\n", + "def filter_and_shift(image, filtersize):\n", + " image = (image*1.0) - ((uf(image,filtersize))*1) #(image) - unifrom-filtered(image) subtracts background\n", + " flat_im = image.ravel()\n", + " shifted_im = flat_im + np.abs(flat_im.min())\n", + " return shifted_im" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "7d00cb42", + "metadata": {}, + "outputs": [], + "source": [ + "def subtract_mean_and_shift_list(pixel_list):\n", + " pixel_list = (pixel_list*1) - (np.mean(pixel_list)) \n", + " flat_im = pixel_list.ravel()\n", + " shifted_im_list = flat_im + np.abs(flat_im.min())\n", + " return shifted_im_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "617edfe1", + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "found 19 files\n", + " 0 \t row1_t2_MMStack_Pos0.ome.tif\n", + " 1 \t row1_t3_MMStack_Pos0.ome.tif\n", + " 2 \t row1_t4_MMStack_Pos0.ome.tif\n", + " 3 \t row2_t1_MMStack_Pos0.ome.tif\n", + " 4 \t row2_t2_MMStack_Pos0.ome.tif\n", + " 5 \t row2_t3_MMStack_Pos0.ome.tif\n", + " 6 \t row2_t4_MMStack_Pos0.ome.tif\n", + " 7 \t row3_t1_MMStack_Pos0.ome.tif\n", + " 8 \t row3_t2_MMStack_Pos0.ome.tif\n", + " 9 \t row3_t3_MMStack_Pos0.ome.tif\n", + " 10 \t row3_t4_MMStack_Pos0.ome.tif\n", + " 11 \t row4_t1_MMStack_Pos0.ome.tif\n", + " 12 \t row4_t2_MMStack_Pos0.ome.tif\n", + " 13 \t row4_t3_MMStack_Pos0.ome.tif\n", + " 14 \t row4_t4_MMStack_Pos0.ome.tif\n", + " 15 \t row5_t1_MMStack_Pos0.ome.tif\n", + " 16 \t row5_t2_MMStack_Pos0.ome.tif\n", + " 17 \t row5_t3_MMStack_Pos0.ome.tif\n", + " 18 \t row5_t4_MMStack_Pos0.ome.tif\n" + ] + } + ], + "source": [ + "date = \"04-03-23\"\n", + "exp0 = \"AE-3.31µM\"\n", + "exp1 = \"AE-6.62µM\"\n", + "exp2 = \"WT-3.31µM\"\n", + "exp3 = \"WT-6.62µM\"\n", + "\n", + "time_array = [1, 7, 15, 25] #time corresponding with each tiff file\n", + "\n", + "### \"data_dir\" is the pathway to the folder holding the tiff files to be analyzed --> change to your folder location\n", + "data_dir = \"Z:\\\\Maya N\\\\data\\\\\"+date+\"\\\\all tiff files\\\\\"\n", + "data_save = \"Z:\\\\Maya N\\\\analysis\\\\\"+date+\"\\\\\"\n", + "### \"plot_saveto\" is the pathway to the folder where plots and results will be saved\n", + "plot_saveto = data_save\n", + "\n", + "files = glob.glob(data_dir+\"*tif\") ### this should generate an ordered list of files in \"data_dir\" which have \"_t\" in their name\n", + "print(\"found %i files\" % len(files))\n", + "for i,f in enumerate(files): print (' %i \\t %s' % (i, f.split('\\\\')[-1]))" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "6e67b266", + "metadata": {}, + "outputs": [], + "source": [ + "#time_array = [1, 7, 15, 25] #time corresponding with each tiff file\n", + "#time_key = 0\n", + "#time = time_array[time_key]\n", + "#image_time = \"time 3\"" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "a5007731", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "next time\n", + "0 row1_t2_MMStack_Pos0.ome.tif\n", + "4 row2_t2_MMStack_Pos0.ome.tif\n", + "8 row3_t2_MMStack_Pos0.ome.tif\n", + "12 row4_t2_MMStack_Pos0.ome.tif\n", + "16 row5_t2_MMStack_Pos0.ome.tif\n", + "next time\n", + "1 row1_t3_MMStack_Pos0.ome.tif\n", + "5 row2_t3_MMStack_Pos0.ome.tif\n", + "9 row3_t3_MMStack_Pos0.ome.tif\n", + "13 row4_t3_MMStack_Pos0.ome.tif\n", + "17 row5_t3_MMStack_Pos0.ome.tif\n", + "next time\n", + "2 row1_t4_MMStack_Pos0.ome.tif\n", + "6 row2_t4_MMStack_Pos0.ome.tif\n", + "10 row3_t4_MMStack_Pos0.ome.tif\n", + "14 row4_t4_MMStack_Pos0.ome.tif\n", + "18 row5_t4_MMStack_Pos0.ome.tif\n", + "next time\n", + "3 row2_t1_MMStack_Pos0.ome.tif\n", + "7 row3_t1_MMStack_Pos0.ome.tif\n", + "11 row4_t1_MMStack_Pos0.ome.tif\n", + "15 row5_t1_MMStack_Pos0.ome.tif\n" + ] + } + ], + "source": [ + "## pixel value lists for first condition \n", + "\n", + "t1_pixel_list_0 = []\n", + "t2_pixel_list_0 = []\n", + "t3_pixel_list_0 = []\n", + "t4_pixel_list_0 = []\n", + "all_times_list_0 = [t1_pixel_list_0, t2_pixel_list_0, t3_pixel_list_0, t4_pixel_list_0]\n", + "\n", + "for i in range(4):\n", + " print(\"next time\")\n", + " list_to_add_to0 = all_times_list_0[i]\n", + " for j in range(i, 19, 4):\n", + " print(str(j) + \" \" + files[j].split('\\\\')[-1])\n", + " chosen_image0 = tiff_file.imread(files[j], key=[0])\n", + " shifted_chosen_image0 = subtract_mean_and_shift(chosen_image0)\n", + " raveled_im0 = shifted_chosen_image0.ravel()\n", + " list_to_add_to0.extend(raveled_im0)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "1452f4ff", + "metadata": {}, + "outputs": [], + "source": [ + "## pixel value lists for second condition \n", + "\n", + "t1_pixel_list_1 = []\n", + "t2_pixel_list_1 = []\n", + "t3_pixel_list_1 = []\n", + "t4_pixel_list_1 = []\n", + "all_times_list_1 = [t1_pixel_list_1, t2_pixel_list_1, t3_pixel_list_1, t4_pixel_list_1]\n", + "\n", + "for i in range(4):\n", + " #print(\"next time\")\n", + " list_to_add_to1 = all_times_list_1[i]\n", + " for j in range(i, 19, 4):\n", + " #print(str(j) + \" \" + files[j].split('\\\\')[-1])\n", + " chosen_image1 = tiff_file.imread(files[j], key=[1])\n", + " shifted_chosen_image1 = subtract_mean_and_shift(chosen_image1)\n", + " raveled_im1 = shifted_chosen_image1.ravel()\n", + " list_to_add_to1.extend(raveled_im1)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "df252a5a", + "metadata": {}, + "outputs": [], + "source": [ + "## pixel value lists for third condition \n", + "\n", + "t1_pixel_list_2 = []\n", + "t2_pixel_list_2 = []\n", + "t3_pixel_list_2 = []\n", + "t4_pixel_list_2 = []\n", + "all_times_list_2 = [t1_pixel_list_2, t2_pixel_list_2, t3_pixel_list_2, t4_pixel_list_2]\n", + "\n", + "for i in range(4):\n", + " #print(\"next time\")\n", + " list_to_add_to2 = all_times_list_2[i]\n", + " for j in range(i, 19, 4):\n", + " #print(str(j) + \" \" + files[j].split('\\\\')[-1])\n", + " chosen_image2 = tiff_file.imread(files[j], key=[2])\n", + " shifted_chosen_image2 = subtract_mean_and_shift(chosen_image2)\n", + " raveled_im2 = shifted_chosen_image2.ravel()\n", + " list_to_add_to2.extend(raveled_im2)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "e44a053c", + "metadata": {}, + "outputs": [], + "source": [ + "## pixel value lists for fourth condition \n", + "\n", + "t1_pixel_list_3 = []\n", + "t2_pixel_list_3 = []\n", + "t3_pixel_list_3 = []\n", + "t4_pixel_list_3 = []\n", + "all_times_list_3 = [t1_pixel_list_3, t2_pixel_list_3, t3_pixel_list_3, t4_pixel_list_3]\n", + "\n", + "for i in range(4):\n", + " #print(\"next time\")\n", + " list_to_add_to3 = all_times_list_3[i]\n", + " for j in range(i, 19, 4):\n", + " #print(str(j) + \" \" + files[j].split('\\\\')[-1])\n", + " shifted_chosen_image3 = tiff_file.imread(files[j], key=[3])\n", + " shifted_chosen_image3 = subtract_mean_and_shift(chosen_image3)\n", + " raveled_im3 = shifted_chosen_image3.ravel()\n", + " list_to_add_to3.extend(raveled_im3)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "9450287f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "13824000\n", + "[179.0, 165.0, 139.0, 142.0]\n", + "[180.0, 180.0, 178.0, 202.0]\n", + "[491.0, 480.0, 460.0, 440.0]\n", + "[150.0, 163.0, 153.0, 189.0]\n", + "13824000\n", + "[217.0, 231.0, 239.0, 240.0]\n", + "[312.0, 282.0, 283.0, 330.0]\n", + "[322.0, 331.0, 297.0, 349.0]\n", + "[173.0, 146.0, 171.0, 163.0]\n", + "13824000\n", + "[340.0, 327.0, 333.0, 321.0]\n", + "[686.0, 715.0, 663.0, 679.0]\n", + "[379.0, 362.0, 379.0, 442.0]\n", + "[643.0, 635.0, 646.0, 594.0]\n", + "13824000\n", + "[759.0, 773.0, 774.0, 773.0]\n", + "[759.0, 773.0, 774.0, 773.0]\n", + "[759.0, 773.0, 774.0, 773.0]\n", + "[759.0, 773.0, 774.0, 773.0]\n" + ] + } + ], + "source": [ + "## checkpoint to make sure data is not overwritten\n", + "\n", + "print(len(t1_pixel_list_0))\n", + "print(t1_pixel_list_0[0:4])\n", + "print(t2_pixel_list_0[0:4])\n", + "print(t3_pixel_list_0[0:4])\n", + "print(t4_pixel_list_0[0:4])\n", + "\n", + "print(len(t1_pixel_list_1))\n", + "print(t1_pixel_list_1[0:4])\n", + "print(t2_pixel_list_1[0:4])\n", + "print(t3_pixel_list_1[0:4])\n", + "print(t4_pixel_list_1[0:4])\n", + "\n", + "print(len(t1_pixel_list_2))\n", + "print(t1_pixel_list_2[0:4])\n", + "print(t2_pixel_list_2[0:4])\n", + "print(t3_pixel_list_2[0:4])\n", + "print(t4_pixel_list_2[0:4])\n", + "\n", + "print(len(t1_pixel_list_3))\n", + "print(t1_pixel_list_3[0:4])\n", + "print(t2_pixel_list_3[0:4])\n", + "print(t3_pixel_list_3[0:4])\n", + "print(t4_pixel_list_3[0:4])" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "63fa82fa", + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'chosen_tiff5 = files[16]\\nchosen_image5 = tiff_file.imread(chosen_tiff5, key=[image_key])'" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "image_key = 3\n", + "##experimental condition [1/2xAE, 1xAE, 1/2xWT, 1xWT]\n", + "\n", + "chosen_tiff1 = files[3]\n", + "chosen_image1 = tiff_file.imread(chosen_tiff1, key=[image_key])\n", + "chosen_tiff2 = files[7]\n", + "chosen_image2 = tiff_file.imread(chosen_tiff2, key=[image_key])\n", + "chosen_tiff3 = files[11]\n", + "chosen_image3 = tiff_file.imread(chosen_tiff3, key=[image_key])\n", + "chosen_tiff4 = files[15]\n", + "chosen_image4 = tiff_file.imread(chosen_tiff4, key=[image_key])\n", + "'''chosen_tiff5 = files[16]\n", + "chosen_image5 = tiff_file.imread(chosen_tiff5, key=[image_key])'''" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "364de232", + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (fig.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", + " if (this.ResizeObserver === undefined) {\n", + " if (window.ResizeObserver !== undefined) {\n", + " this.ResizeObserver = window.ResizeObserver;\n", + " } else {\n", + " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", + " this.ResizeObserver = obs.ResizeObserver;\n", + " }\n", + " }\n", + "\n", + " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " if (entry.contentBoxSize instanceof Array) {\n", + " // Chrome 84 implements new version of spec.\n", + " width = entry.contentBoxSize[0].inlineSize;\n", + " height = entry.contentBoxSize[0].blockSize;\n", + " } else {\n", + " // Firefox implements old version of spec.\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " }\n", + " } else {\n", + " // Chrome <84 implements even older version of spec.\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " if (entry.devicePixelContentBoxSize) {\n", + " // Chrome 84 implements new version of spec.\n", + " canvas.setAttribute(\n", + " 'width',\n", + " entry.devicePixelContentBoxSize[0].inlineSize\n", + " );\n", + " canvas.setAttribute(\n", + " 'height',\n", + " entry.devicePixelContentBoxSize[0].blockSize\n", + " );\n", + " } else {\n", + " canvas.setAttribute('width', width * fig.ratio);\n", + " canvas.setAttribute('height', height * fig.ratio);\n", + " }\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " this.resizeObserverInstance.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " event.preventDefault();\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / fig.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", + " var x1 = msg['x1'] / fig.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / fig.ratio,\n", + " fig.canvas.height / fig.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * this.ratio;\n", + " var y = canvas_pos.y * this.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "\n", + "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", + "// prettier-ignore\n", + "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + " fig.cell_info[0].output_area.element.on(\n", + " 'cleared',\n", + " { fig: fig },\n", + " fig._remove_fig_handler\n", + " );\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / fig.ratio;\n", + " fig.cell_info[0].output_area.element.off(\n", + " 'cleared',\n", + " fig._remove_fig_handler\n", + " );\n", + " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / this.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function (event) {\n", + " var fig = event.data.fig;\n", + " if (event.target !== this) {\n", + " // Ignore bubbled events from children.\n", + " return;\n", + " }\n", + " fig.close_ws(fig, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%matplotlib notebook\n", + "\n", + " #AE = yellow, EA = blue, WT = magenta\n", + "c1 = \"magenta\" #AE: 1/4x = darkgolenrod, 1/2x = gold, 1x = khaki\n", + "c2 = \"violet\" #EA: 1/4x = darkblue, 1/2x = blue, 1x = dodgerblue\n", + "c3 = \"darkmagenta\" #WT: 1/4x = darkmagenta, 1/2x = magenta, 1x = violet\n", + "c4 = \"violet\"\n", + "\n", + "bin_num = 100 # number of histogram bins, changing this effects the histogram (can be set to \"auto\")\n", + "\n", + "fig, ax = plt.subplots(figsize=(6,4)) #set up 'figure 1' - mean subtraction\n", + "all_intensities_list0 = t3_pixel_list_3\n", + "all_intensities_list1 = subtract_mean_and_shift(chosen_image1)\n", + "all_intensities_list2 = subtract_mean_and_shift(chosen_image2)\n", + "all_intensities_list3 = subtract_mean_and_shift(chosen_image3)\n", + "all_intensities_list4 = subtract_mean_and_shift(chosen_image4)\n", + "'''all_intensities_list5 = subtract_mean_and_shift(chosen_image5)\n", + "'''\n", + "probabilities0, bins0 = np.histogram(all_intensities_list0, bins=bin_num, density = True)\n", + "ax.plot(bins0[:-1], probabilities0, 'o-', linewidth=2, markersize=0, color = c3, alpha = 1, label = \"all images\")\n", + "counts0, bins0, bars0 = ax.hist(all_intensities_list0, bins=bin_num, density = True, \n", + " color = c4, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities1, bins1 = np.histogram(all_intensities_list1, bins=bin_num, density = True)\n", + "ax.plot(bins1[:-1], probabilities1, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts1, bins1, bars1 = ax.hist(all_intensities_list1, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities2, bins2 = np.histogram(all_intensities_list2, bins=bin_num, density = True)\n", + "ax.plot(bins2[:-1], probabilities2, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts2, bins2, bars2 = ax.hist(all_intensities_list2, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities3, bins3 = np.histogram(all_intensities_list3, bins=bin_num, density = True)\n", + "ax.plot(bins3[:-1], probabilities3, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts3, bins3, bars3 = ax.hist(all_intensities_list3, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "probabilities4, bins4 = np.histogram(all_intensities_list4, bins=bin_num, density = True)\n", + "ax.plot(bins4[:-1], probabilities4, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts4, bins4, bars4 = ax.hist(all_intensities_list4, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "'''probabilities5, bins5 = np.histogram(all_intensities_list5, bins=bin_num, density = True)\n", + "ax.plot(bins5[:-1], probabilities5, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts5, bins5, bars5 = ax.hist(all_intensities_list5, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")'''\n", + "\n", + "\n", + "ax.set_xlim(0,3000)\n", + "ax.set_ylim(10E-6, 10E-3)\n", + "ax.tick_params(axis='both', labelsize=20)\n", + "ax.set_yscale('log')\n", + "#ax.set_xlabel(\"Pixel Intensity\")\n", + "#ax.set_ylabel(\"Probability\")\n", + "ax.legend(loc = \"upper right\", fontsize=18)\n", + "#ax.set_title(\"Probability Distribution at \" + str(time) + \" hr\", fontsize=12)\n", + "#fig.savefig(plot_saveto + \"probability histogram for \" + exp3 + \".jpg\", dpi=800, bbox_inches = 'tight', transparent=True) \n", + "fig.savefig(plot_saveto + \"single image histogram\" + exp3 + \"1hr.jpg\", dpi=800, bbox_inches = 'tight', transparent=True)\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "504f3c42", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fa5b8a39", + "metadata": {}, + "outputs": [], + "source": [ + "#histogram tests\n", + "\n", + "fig, ax2 = plt.subplots(figsize=(6,4)) #set up 'figure 1' - raw intensity values\n", + "probabilities, bins = np.histogram(chosen_image1.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins[:-1], probabilities, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"1\")\n", + "counts, bins, bars = ax2.hist(chosen_image1.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities2, bins2 = np.histogram(chosen_image2.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins2[:-1], probabilities2, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"2\", linestyle='dashed')\n", + "counts2, bins2, bars2 = ax2.hist(chosen_image2.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "\n", + "\n", + "probabilities3, bins3 = np.histogram(chosen_image3.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins3[:-1], probabilities3, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"3\", linestyle='dotted')\n", + "counts3, bins3, bars3 = ax2.hist(chosen_image3.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "probabilities4, bins4 = np.histogram(chosen_image4.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins4[:-1], probabilities4, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"4\", linestyle='dotted')\n", + "counts4, bins4, bars4 = ax2.hist(chosen_image4.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "probabilities5, bins5 = np.histogram(chosen_image5.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins5[:-1], probabilities5, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"5\", linestyle='dotted')\n", + "counts5, bins5, bars5 = ax2.hist(chosen_image5.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + " #plots a histogram for a given list; \n", + " #___.ravel() converts a 2D image array to a 1D list of pixel intensities\n", + "ax2.set_xlim(0,3500)\n", + "ax2.set_ylim(10E-6, 10E-3) \n", + "ax2.tick_params(axis='both', labelsize=20)\n", + "ax2.set_yscale('log')\n", + "#ax2.set_xlabel(\"Pixel Intensity\")\n", + "#ax2.set_ylabel(\"Probability\")\n", + "#ax2.legend(loc = \"upper right\", fontsize=18)\n", + "#ax2.set_title(\"Probability Distribution at \" + str(time) + \" hr\", fontsize=12)\n", + "#fig.savefig(plot_saveto + \"histogram for AE \" + image_time + \".jpg\", dpi=800, bbox_inches = 'tight', transparent=True) \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "405fea85", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(figsize=(6,4)) #set up 'figure 1' - mean subtraction\n", + "all_intensities_list0 = subtract_mean_and_shift(chosen_image1) #subtract_mean_and_shift\n", + "all_intensities_list1 = subtract_mean_and_shift(chosen_image2)\n", + "all_intensities_list2 = subtract_mean_and_shift(chosen_image3)\n", + "all_intensities_list3 = subtract_mean_and_shift(chosen_image4)\n", + "all_intensities_list4 = subtract_mean_and_shift(chosen_image5)\n", + "\n", + "probabilities0, bins0 = np.histogram(all_intensities_list0, bins=bin_num, density = True)\n", + "ax.plot(bins0[:-1], probabilities0, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[0])\n", + "counts0, bins0, bars0 = ax.hist(all_intensities_list0, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities1, bins1 = np.histogram(all_intensities_list1, bins=bin_num, density = True)\n", + "ax.plot(bins1[:-1], probabilities1, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[1], \n", + " linestyle='dashed')\n", + "counts1, bins1, bars1 = ax.hist(all_intensities_list1, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities2, bins2 = np.histogram(all_intensities_list2, bins=bin_num, density = True)\n", + "ax.plot(bins2[:-1], probabilities2, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[2], \n", + " linestyle='dotted')\n", + "counts2, bins2, bars2 = ax.hist(all_intensities_list2, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities3, bins3 = np.histogram(all_intensities_list3, bins=bin_num, density = True)\n", + "ax.plot(bins3[:-1], probabilities3, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[3], \n", + " linestyle='dashdot')\n", + "counts3, bins3, bars3 = ax.hist(all_intensities_list3, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities4, bins4 = np.histogram(all_intensities_list4, bins=bin_num, density = True)\n", + "ax.plot(bins4[:-1], probabilities4, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[3], \n", + " linestyle='dashdot')\n", + "counts4, bins4, bars4 = ax.hist(all_intensities_list4, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "ax.set_xlim(0,3000)\n", + "ax.set_ylim(10E-6, 10E-3)\n", + "ax.tick_params(axis='both', labelsize=20)\n", + "ax.set_yscale('log')\n", + "#ax.set_xlabel(\"Pixel Intensity\")\n", + "#ax.set_ylabel(\"Probability\")\n", + "#ax.legend(loc = \"upper right\", title=\"Time (hrs)\", fontsize=18)\n", + "#ax.set_title(\"Probability Distribution at \" + str(time) + \" hr\", fontsize=12)\n", + "#fig.savefig(plot_saveto + \"probability histogram for \" + exp1 + \".jpg\", dpi=800, bbox_inches = 'tight', transparent=True) \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a7baceb0", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3bbd28c2", + "metadata": {}, + "outputs": [], + "source": [ + "histogram_dict = {} #makes dictionary\n", + "\n", + "histogram_dict[\"AE\"] = {} #makes subdictionary for AE files\n", + "histogram_dict[\"AE\"][probabilities] = probabilities\n", + "histogram_dict[\"AE\"][probabilities] = probabilities_subtract_mean\n", + "histogram_dict[\"AE\"][bins] = bins\n", + "histogram_dict[\"AE\"][bins]= bins_subtract_mean\n", + "\n", + "histogram_dict[\"EA\"] = {} #makes subdictionary for EA files\n", + "histogram_dict[\"EA\"][probabilities] = probabilities2\n", + "histogram_dict[\"EA\"][probabilities] = probabilities_subtract_mean2\n", + "histogram_dict[\"EA\"][bins] = bins2\n", + "histogram_dict[\"EA\"][bins]= bins_subtract_mean2\n", + "\n", + "histogram_dict[\"WT\"] = {} #makes subdictionary for WT files\n", + "histogram_dict[\"WT\"][probabilities] = probabilities3\n", + "histogram_dict[\"WT\"][probabilities] = probabilities_subtract_mean3\n", + "histogram_dict[\"WT\"][bins] = bins3\n", + "histogram_dict[\"WT\"][bins]= bins_subtract_mean3\n", + "\n", + "with open(\"1x WT bead\" + date + \".pkl\", 'wb') as f: #saves intensity data\n", + " pickle.dump(histogram_dict, f)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1c3a6677", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d5bca1c6", + "metadata": {}, + "outputs": [], + "source": [ + "## plots raw histogram (not updated)\n", + "\n", + "fig, ax2 = plt.subplots(figsize=(6,4)) #set up 'figure 1' - raw intensity values\n", + "probabilities, bins = np.histogram(chosen_image1.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins[:-1], probabilities, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = exp1)\n", + "counts, bins, bars = ax2.hist(chosen_image1.ravel(), bins=bin_num, density = True, color = c1, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities2, bins2 = np.histogram(chosen_image2.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins2[:-1], probabilities2, 'o-', linewidth=2, markersize=0, color = c2, alpha = 1, label = exp2, linestyle='dashed')\n", + "counts2, bins2, bars2 = ax2.hist(chosen_image2.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "\n", + "\n", + "probabilities3, bins3 = np.histogram(chosen_image3.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins3[:-1], probabilities3, 'o-', linewidth=2, markersize=0, color = c3, alpha = 1, label = exp3, linestyle='dotted')\n", + "counts3, bins3, bars3 = ax2.hist(chosen_image3.ravel(), bins=bin_num, density = True, color = c3, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + " #plots a histogram for a given list; \n", + " #___.ravel() converts a 2D image array to a 1D list of pixel intensities\n", + "ax2.set_xlim(1000,3500)\n", + "ax2.set_ylim(10E-6, 10E-3) \n", + "ax2.tick_params(axis='both', labelsize=20)\n", + "ax2.set_yscale('log')\n", + "#ax2.set_xlabel(\"Pixel Intensity\")\n", + "#ax2.set_ylabel(\"Probability\")\n", + "ax2.legend(loc = \"upper right\", fontsize=18)\n", + "#ax2.set_title(\"Probability Distribution at \" + str(time) + \" hr\", fontsize=12)\n", + "fig.savefig(plot_saveto + \"probability histogram for AE \" + image_time + \".jpg\", dpi=800, bbox_inches = 'tight', transparent=True) \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "51527778", + "metadata": {}, + "outputs": [], + "source": [ + "## plots shifted histogram (not updated)\n", + "\n", + "fig, ax3 = plt.subplots(figsize=(6,4)) #set up 'figure 3' - background subtraction\n", + "all_intensities_list = filter_and_shift(chosen_image, 1000) \n", + "ax3.hist(all_intensities_list, bins=bin_num, density = True, color = c)\n", + "ax3.set_xlim(0,1500)\n", + "ax3.set_ylim(10E-6, 10E-3)\n", + "ax3.set_yscale('log')\n", + "ax3.set_xlabel(\"pixel intensity\")\n", + "ax3.set_ylabel(\"probability\")\n", + "fig.savefig(plot_saveto + \"filtered histogram for \" + title + \".jpg\") \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "95b732fb", + "metadata": {}, + "outputs": [], + "source": [ + "## attempt to only include certain files\n", + "\n", + "print(files[0])\n", + "print(files[0].split('\\\\'))\n", + "print(files[0].split('\\\\')[-1])\n", + "print((files[0].split('\\\\')[-1])[0:4])\n", + "obj_mag = (files[0].split('\\\\')[-1])[0:3]\n", + "\n", + "new_files_list = []\n", + "\n", + "for i in range(len(files)):\n", + " current_file = files[i]\n", + " obj_mag = (current_file.split('\\\\')[-1])[0:3]\n", + " if obj_mag != \"20x\":\n", + " new_files_list.extend(current_file)\n", + " #new_files_list[i] = current_file\n", + " \n", + "print(\"found %i files\" % len(new_files_list))\n", + "for i,f in enumerate(new_files_list): print (' %i \\t %s' % (i, f.split('\\\\')[-1]))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "88e12437", + "metadata": {}, + "outputs": [], + "source": [ + "#image_key[1/2x AE, 1x AE, 1/2x WT, 1x WT]\n", + "image_key = 0\n", + "number_of_images = 5\n", + "\n", + "#file number\n", + "a=0\n", + "b=4\n", + "c=8\n", + "d=12\n", + "e=16\n", + "\n", + "chosen_tiff1 = files[a]\n", + "chosen_image1 = tiff_file.imread(chosen_tiff1, key=[image_key]) #key=[ ] selects which frame of the tiff file will be read\n", + "chosen_tiff2 = files[b]\n", + "chosen_image2 = tiff_file.imread(chosen_tiff2, key=[image_key])\n", + "chosen_tiff3 = files[c]\n", + "chosen_image3 = tiff_file.imread(chosen_tiff3, key=[image_key])\n", + "chosen_tiff4 = files[d]\n", + "chosen_image4 = tiff_file.imread(chosen_tiff4, key=[image_key])\n", + "chosen_tiff5 = files[e]\n", + "chosen_image5 = tiff_file.imread(chosen_tiff5, key=[image_key])\n", + "\n", + "\n", + "all_pixel_values = []\n", + "for i in range(number_of_images):\n", + " image_array_2D = tiff_file.imread(chosen_tiff[i], key=[image_key])\n", + " raveled_im = image_array_2D.ravel()\n", + " all_pixel_values.extend(raveled_im)\n", + "#print('List 1 before extend():', chosen_image1)\n", + "\n", + "\n", + "#might say \"list index out of range\" - if so, just change first key from i→1, run then change back to i and rerun\n", + "\n", + " # image_array_2D2 = tiff_file.imread(chosen_tiff2, key=[image_key])\n", + " # pixel_values_list2 = image_array_2D2.ravel()\n", + " # image_array_2D3 = tiff_file.imread(chosen_tiff3, key=[image_key])\n", + " # pixel_values_list3 = image_array_2D3.ravel() \n", + " # image_array_2D4 = tiff_file.imread(chosen_tiff4, key=[image_key])\n", + " # pixel_values_list4 = image_array_2D4.ravel() \n", + " # image_array_2D5 = tiff_file.imread(chosen_tiff5, key=[image_key])\n", + " # pixel_values_list5 = image_array_2D5.ravel()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3a961b57", + "metadata": {}, + "outputs": [], + "source": [ + "##prints images (not updated)\n", + "\n", + "fig, ax4 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff1.split('\\\\')[-1])[:-21]) #splits the full file name into only the relevent info\n", + "ax4.set_title(title, fontsize=10)\n", + "ax4.imshow(chosen_image1, cmap='gray') #'cmap' is the color map used to display the image, 'gray' is short for greyscale\n", + "ax4.axis('off')\n", + "\n", + "'''fig, ax9 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff1.split('\\\\')[-1])[:-21]) #splits the full file name into only the relevent info\n", + "ax9.set_title(title, fontsize=10)\n", + "ax9.imshow(subtract_mean_and_shift(chosen_image1), cmap='gray') #'cmap' is the color map used to display the image, 'gray' is short for greyscale\n", + "ax9.axis('off')'''\n", + "\n", + "fig, ax5 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff2.split('\\\\')[-1])[:-21]) \n", + "ax5.set_title(title, fontsize=10)\n", + "ax5.imshow(chosen_image2, cmap='gray') \n", + "ax5.axis('off')\n", + "\n", + "fig, ax6 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff3.split('\\\\')[-1])[:-21]) \n", + "ax6.set_title(title, fontsize=10)\n", + "ax6.imshow(chosen_image3, cmap='gray')\n", + "ax6.axis('off')\n", + "\n", + "fig, ax7 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff4.split('\\\\')[-1])[:-21]) \n", + "ax7.set_title(title, fontsize=10)\n", + "ax7.imshow(chosen_image4, cmap='gray')\n", + "ax7.axis('off')\n", + "\n", + "fig, ax8 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff5.split('\\\\')[-1])[:-21]) \n", + "ax8.set_title(title, fontsize=10)\n", + "ax8.imshow(chosen_image5, cmap='gray')\n", + "ax8.axis('off')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "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.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.ipynb_checkpoints/single image SIA (user friendly)-checkpoint.ipynb b/.ipynb_checkpoints/single image SIA (user friendly)-checkpoint.ipynb index 101d748..35801f9 100644 --- a/.ipynb_checkpoints/single image SIA (user friendly)-checkpoint.ipynb +++ b/.ipynb_checkpoints/single image SIA (user friendly)-checkpoint.ipynb @@ -2,22 +2,9 @@ "cells": [ { "cell_type": "code", - "execution_count": 2, + "execution_count": 19, "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodepackbits\n", - " warnings.warn(\"failed to import %s\" % module_function)\n", - "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodelzw\n", - " warnings.warn(\"failed to import %s\" % module_function)\n", - "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.unpackints\n", - " warnings.warn(\"failed to import %s\" % module_function)\n" - ] - } - ], + "outputs": [], "source": [ "%matplotlib notebook\n", "import numpy as np\n", @@ -32,7 +19,7 @@ "from skimage.filters import threshold_otsu, threshold_local\n", "from skimage.transform import downscale_local_mean #For binning\n", "\n", - "#import xarray as xr #package for labeling and adding metadata to multi-dimensional arrays \n", + "import xarray as xr #package for labeling and adding metadata to multi-dimensional arrays \n", "import tiff_file \n", "\n", "import io \n", @@ -55,7 +42,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 20, "metadata": {}, "outputs": [], "source": [ @@ -186,7 +173,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 31, "metadata": { "scrolled": false }, @@ -195,27 +182,22 @@ "name": "stdout", "output_type": "stream", "text": [ - "found 9 files\n", - " 0 \t row1_t01.tif\n", - " 1 \t row1_t02.tif\n", - " 2 \t row1_t03.tif\n", - " 3 \t row1_t04.tif\n", - " 4 \t row1_t05.tif\n", - " 5 \t row1_t06.tif\n", - " 6 \t row1_t07.tif\n", - " 7 \t row1_t08.tif\n", - " 8 \t row1_t09.tif\n" + "found 3 files\n", + " 0 \t top_s1_40x_t1_MMStack_Pos0.ome.tif\n", + " 1 \t top_s1_40x_t2_MMStack_Pos0.ome.tif\n", + " 2 \t top_s1_40x_t3_MMStack_Pos0.ome.tif\n" ] } ], "source": [ - "exp = \"single tiffs (demo)\"\n", + "date = \"9-7-22\"\n", + "exp = \"top\"\n", "\n", - "#C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\n", "### \"data_dir\" is the pathway to the folder holding the tiff files to be analyzed --> change to your folder location\n", - "data_dir = \"C:\\\\Users\\\\svc-scst291lab\\\\Documents\\\\GitHub\\\\user-friendly-SIA\\\\\"+exp +\"\\\\\" \n", + "data_dir = \"Z:\\\\Maya N\\\\data\\\\\"+date+\"\\\\\"+exp +\"\\\\\"\n", + "data_save = \"Z:\\\\Maya N\\\\analysis\\\\\"+date+\"\\\\\"+exp +\"\\\\\"\n", "### \"plot_saveto\" is the pathway to the folder where plots and results will be saved\n", - "plot_saveto = data_dir\n", + "plot_saveto = data_save\n", "\n", "files = glob.glob(data_dir+\"*tif\") ### this should generate an ordered list of files in \"data_dir\" which have \"_t\" in their name\n", "print(\"found %i files\" % len(files))\n", @@ -231,29 +213,29 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "tiff file dimensions: (5, 1440, 1920)\n", - "number of files: 9\n", - "total number of time points: 9\n" + "tiff file dimensions: (4, 1440, 1920)\n", + "number of files: 3\n", + "total number of time points: 3\n" ] } ], "source": [ - "time_array = [1, 4, 7, 10, 13, 19, 22, 25, 28]\n", + "time_array = [1, 3, 28]\n", "### array containing the time points corresponding to consecutive tiff files\n", "### e.g. tiff files with '_t01_' in their filename correspond to t = 1 hour, time_array[0]\n", "\n", - "frame_names = [\"1-3 kA-WT\", \"WT (no kA)\", \"EA KaiC\", \"AE KaiC\"]\n", + "frame_names = [\"24\", \"24 + kaiA\", \"WT\", \"WT + kaiA\"]\n", "### array containing the name for each frame in a tiff file to be run \n", "\n", "pixel_size = 1 #0.0944 #0.09436 #10.597 #0.0944\n", - "px = \"pix size= \"+str(pixel_size)\n", + "px = \"pix size= \" + str(pixel_size)\n", "### pixel size (microns per pixel) of frames/ images in the tiff files --- 40x olympus objective => 0.091 um/px\n", "### IF 2x2 BINNING: multiply the original pixel size by 2^2 = 4, e.g. 4*(0.091 um/px) = 0.364 um/px\n", "\n", @@ -276,7 +258,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 34, "metadata": {}, "outputs": [], "source": [ @@ -308,7 +290,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 40, "metadata": { "scrolled": false }, @@ -317,7 +299,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "preview images for single tiffs (demo), files 0 - 8\n" + "preview images for top, files 1 - 3\n" ] }, { @@ -1281,7 +1263,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -1291,17 +1273,22 @@ "output_type": "display_data" }, { - "name": "stdout", - "output_type": "stream", - "text": [ - "preview images for single tiffs (demo), 9 files (raw images)\n" + "ename": "IndexError", + "evalue": "list index out of range", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mIndexError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 30\u001b[0m \u001b[0mdetails\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mexp\u001b[0m\u001b[1;33m+\u001b[0m \u001b[1;34m\", %3.1f files (block_size= %3i, offset= %3i)\"\u001b[0m \u001b[1;33m%\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mblock_size\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0moffset_val\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 31\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 32\u001b[1;33m \u001b[0mshow_raw_images\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0max\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mi\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mframe_key\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 33\u001b[0m \u001b[0mi\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mi\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 34\u001b[0m \u001b[0mdetails\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mexp\u001b[0m\u001b[1;33m+\u001b[0m \u001b[1;34m\", %i files (raw images)\"\u001b[0m \u001b[1;33m%\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;32m\u001b[0m in \u001b[0;36mshow_raw_images\u001b[1;34m(ax, i, frame_key)\u001b[0m\n\u001b[0;32m 89\u001b[0m \u001b[0max\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'[no image]'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfontsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 90\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 91\u001b[1;33m \u001b[0mtest_image\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mtiff_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mimread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiles\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mframe_key\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 92\u001b[0m \u001b[0mtitle\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiles\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msplit\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'\\\\'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m#OPTION: frame_array[i]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 93\u001b[0m \u001b[0max\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtitle\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfontsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mIndexError\u001b[0m: list index out of range" ] } ], "source": [ "### NOTE: this make take a while if you have many and/or large images\n", "### \"i\" --> this value determines which file index to start at \n", - "i = 0 \n", + "i = 1 \n", "num_files = int((len(files))) ### change \"num_files\" to a smaller number to skeletonize less images more quickly (e.g. 2)\n", "print(\"preview images for \"+exp+\", files \"+ str(i) + \" - \" + str(num_files - 1 + i) )\n", "\n", diff --git a/1xEA_t1_2-1-23.pkl b/1xEA_t1_2-1-23.pkl new file mode 100644 index 0000000..b33f053 Binary files /dev/null and b/1xEA_t1_2-1-23.pkl differ diff --git a/image histograms-new copy (2-10-23).ipynb b/image histograms-new copy (2-10-23).ipynb index 2546ac8..c58c1a5 100644 --- a/image histograms-new copy (2-10-23).ipynb +++ b/image histograms-new copy (2-10-23).ipynb @@ -2,23 +2,10 @@ "cells": [ { "cell_type": "code", - "execution_count": 1, + "execution_count": 4, "id": "216adc8d", "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "C:\\Users\\gleech\\Documents\\GitHub\\kai codes\\cluster-analysis\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodepackbits\n", - " warnings.warn(\"failed to import %s\" % module_function)\n", - "C:\\Users\\gleech\\Documents\\GitHub\\kai codes\\cluster-analysis\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodelzw\n", - " warnings.warn(\"failed to import %s\" % module_function)\n", - "C:\\Users\\gleech\\Documents\\GitHub\\kai codes\\cluster-analysis\\tiff_file.py:1995: UserWarning: failed to import _tifffile.unpackints\n", - " warnings.warn(\"failed to import %s\" % module_function)\n" - ] - } - ], + "outputs": [], "source": [ "%matplotlib notebook\n", "import numpy as np\n", @@ -112,7 +99,7 @@ " all_vals_list.extend(im_ravel)\n", " #print(len(all_vals_list))\n", " return all_vals_list\n", - " \n", + "\n", "def zerolistmaker(n):\n", " listofzeros = ['none found'] * n\n", " return listofzeros\n", @@ -126,10 +113,22 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "id": "4eb0be71", "metadata": {}, - "outputs": [], + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'files' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mraw_image\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mtiff_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mimread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiles\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0mim\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfiltimage_and_hist\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mraw_image\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m1000\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mim\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmin\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mabs\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mim\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmin\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mNameError\u001b[0m: name 'files' is not defined" + ] + } + ], "source": [ "raw_image = tiff_file.imread(files[0],key=[0])\n", "im = filtimage_and_hist(raw_image, 1000)\n", @@ -139,7 +138,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 6, "id": "4eb1ae74", "metadata": {}, "outputs": [ @@ -234,10 +233,18 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 8, "id": "6935872a", "metadata": {}, "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\svc-scst291lab\\documents\\Github\\user-friendly-SIA\\tiff_file.py:724: FutureWarning: arrays to stack must be passed as a \"sequence\" type such as list or tuple. Support for non-sequence iterables such as generators is deprecated as of NumPy 1.16 and will raise an error in the future.\n", + " result = numpy.vstack((p.asarray() if p else nopage)\n" + ] + }, { "name": "stdout", "output_type": "stream", @@ -296,7 +303,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 9, "id": "3b7fb31a", "metadata": {}, "outputs": [ @@ -329,141 +336,10 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "id": "bba68e55", - "metadata": {}, - "outputs": [], - "source": [ - "%matplotlib notebook\n", - "font_size = 16\n", - "fig, ax = plt.subplots(figsize=(9,6))\n", - "plt.plot(bins[:-1], counts, '-o', c=cmap(0.65))\n", - "plt.ylabel(\"FWHM\",fontsize=font_size)\n", - "plt.xlabel(\"time (hours)\",fontsize=font_size) \n", - "ax.tick_params(direction='in', which='both', labelsize=font_size-2)\n", - "plt.title(title, fontsize=font_size)\n", - "#plt.ylim(100, 500)\n", - "plt.show()\n", - "#fig.savefig(data_saveto+\"FWHM- \"+title+\".jpg\", dpi=600)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0a7bf682", - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(num_times):\n", - " all_times_all_values[i] = all_pixel_values(0, i)\n", - " #means[frame_key][i] = sum(all_times_all_values[i]) / len(all_times_all_values[i])\n", - " #medians[frame_key][i] = median(all_times_all_values[i])\n", - " #modes[frame_key][i] = mode(all_times_all_values[i])\n", - " #std_devs[frame_key][i] = np.std(all_times_all_values[i])\n", - " " - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "2ae8bc57", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5001\n" - ] - } - ], - "source": [ - "files_list = [files_1015_s1, files_1015_s2, files_95_s1, files_95_s2]\n", - "\n", - "for i in range(num_times):\n", - " #all_times_all_values[i] = all_pixel_values(frame_key, i)\n", - " WTkA_pixel_val[i] = all_pixel_values(0, i)\n", - " #WTnokA_pixel_val[i] = all_pixel_values(1, i)\n", - " EA_pixel_val[i] = all_pixel_values(2, i)\n", - " AE_pixel_val[i] = all_pixel_values(3, i)\n", - " #WTkA_all_probs[i], WTkA_all_bins[i] = np.histogram(all_pixel_values(0, i), bins=bins_num, density = True)\n", - " #WTnokA_all_probs[i], WTnokA_all_bins[i] = np.histogram(all_pixel_values(1, i), bins=bins_num, density = True)\n", - " #EA_all_probs[i], EA_all_bins[i] = np.histogram(all_pixel_values(2, i), bins=bins_num, density = True)\n", - " #AE_all_probs[i], AE_all_bins[i] = np.histogram(all_pixel_values(3, i), bins=bins_num, density = True)\n", - " \n", - " \n", - "print(len(AE_all_bins[0]))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "585fc3a0", - "metadata": {}, - "outputs": [], - "source": [ - "def show_histograms(i, ax, array):\n", - " #print(files[i+index_add])\n", - " if time_array[i] == 0:\n", - " empty_im = np.zeros((1440,1920))\n", - " ax.imshow(empty_im, cmap = 'gray')\n", - " ax.set_title('[no image]', fontsize=10)\n", - " else:\n", - " ax.hist(array[i], density=True, bins=bins_num)\n", - " titles = condition + \", t= \" + str(time_array[i]) + \" hrs, bins= \"+str(bins_num)+\")\"\n", - " ax.set_title(titles, fontsize=font_size-1)\n", - " ax.set( ylabel='probability')\n", - " ax.set( xlabel='pixel intensity')\n", - " ax.set_xlim(0, 2500)\n", - " ax.set_ylim(0, 0.0095)\n", - " ax.tick_params(axis='both', which='major', labelsize=(font_size-3))\n", - " ax.xaxis.get_label().set_fontsize(font_size-2)\n", - " ax.yaxis.get_label().set_fontsize(font_size-2)\n", - " plt.tight_layout(pad=.25)\n", - "\n", - "cmap_num = (num_times*2) - 3\n", - "def stack_histograms(i, ax, array):\n", - " #print(files[i+index_add])\n", - " ax.hist(array[i], density=True, bins=bins_num, color=cmap(0.9-(i/cmap_num)))\n", - " \n", - "def FWHM(X,Y):\n", - " frac = 2 #For FWHM frac = 2, FWtenthM, frac = 10, etc\n", - " half_max = max(Y) / 2.\n", - " #find when function crosses line half_max (when sign of diff flips)\n", - " d = Y - (max(Y) / frac)\n", - " #plot(X[0:len(d)],d) #if you are interested\n", - " #find the left and right most indexes\n", - " indexes = np.where(d > 0)[0]\n", - " return abs(X[indexes[-1]] - X[indexes[0]]) #return the difference (full width)\n", - "\n", - "def select_data(frame_key):\n", - " if frame_key == 0:\n", - " print(\"WT+kaiA histograms\")\n", - " print((WTkA_all_bins[0][0:10]))\n", - " return WTkA_pixel_val, matplotlib.cm.get_cmap('Reds'), \"1:3 :: KaiA:WT KaiC, \"+str(time)+\" hrs\"\n", - " elif frame_key == 1:\n", - " print(\"WT w/o kaiA histograms\")\n", - " return WTnokA_pixel_val, matplotlib.cm.get_cmap('Blues'), \"WT KaiC (no KaiA), \"+str(time)+\" hrs\"\n", - " elif frame_key == 2:\n", - " print(\"EA histograms\")\n", - " return EA_pixel_val, matplotlib.cm.get_cmap('Greens'), \"EA KaiC (fixed binding), \"+str(time)+\" hrs\"\n", - " elif frame_key == 3:\n", - " print(\"AE histograms\")\n", - " return AE_pixel_val, matplotlib.cm.get_cmap('Greys'), \"AE KaiC (non-binding), \"+str(time)+\" hrs\"\n", - "\n", - "# My axis should display 10⁻¹ but you can switch to e-notation 1.00e+01\n", - "def log_tick_formatter(val, pos=None):\n", - " print(val)\n", - " return f\"$10^{{{int(val)}}}$\" # remove int() if you don't use MaxNLocator\n", - " # return f\"{10**val:.2e}\" # e-Notation" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "741a3942", "metadata": { - "scrolled": false + "scrolled": true }, "outputs": [ { @@ -1427,7 +1303,7 @@ { "data": { "text/html": [ - "" + "" ], "text/plain": [ "" @@ -1437,71 +1313,162 @@ "output_type": "display_data" }, { - "name": "stdout", - "output_type": "stream", - "text": [ - "AE histograms\n", - "49766400\n", - "WT+kaiA histograms\n", - "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", - "EA histograms\n" + "ename": "NameError", + "evalue": "name 'bins' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mfont_size\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m16\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[0mfig\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0max\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msubplots\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfigsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m9\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m6\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mplt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mplot\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mbins\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mcounts\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'-o'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mc\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mcmap\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0.65\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5\u001b[0m \u001b[0mplt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mylabel\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"FWHM\"\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mfontsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mfont_size\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[0mplt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mxlabel\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"time (hours)\"\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mfontsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mfont_size\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mNameError\u001b[0m: name 'bins' is not defined" ] } ], "source": [ - "\n", "%matplotlib notebook\n", "font_size = 16\n", "fig, ax = plt.subplots(figsize=(9,6))\n", - "ax.tick_params(axis='both', which='major', labelsize=font_size-2)\n", + "plt.plot(bins[:-1], counts, '-o', c=cmap(0.65))\n", + "plt.ylabel(\"FWHM\",fontsize=font_size)\n", + "plt.xlabel(\"time (hours)\",fontsize=font_size) \n", + "ax.tick_params(direction='in', which='both', labelsize=font_size-2)\n", + "plt.title(title, fontsize=font_size)\n", + "#plt.ylim(100, 500)\n", + "plt.show()\n", + "#fig.savefig(data_saveto+\"FWHM- \"+title+\".jpg\", dpi=600)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "0a7bf682", + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'files_list' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnum_times\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mall_times_all_values\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mall_pixel_values\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mi\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[1;31m#means[frame_key][i] = sum(all_times_all_values[i]) / len(all_times_all_values[i])\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;31m#medians[frame_key][i] = median(all_times_all_values[i])\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;31m#modes[frame_key][i] = mode(all_times_all_values[i])\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;32m\u001b[0m in \u001b[0;36mall_pixel_values\u001b[1;34m(frame_key, i)\u001b[0m\n\u001b[0;32m 28\u001b[0m \u001b[0mall_vals_list\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 29\u001b[0m \u001b[0mtime_index\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mi\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 30\u001b[1;33m \u001b[1;32mfor\u001b[0m \u001b[0ml\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiles_list\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 31\u001b[0m \u001b[0mlist_to_add\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfiles_list\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0ml\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 32\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0ml\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mNameError\u001b[0m: name 'files_list' is not defined" + ] + } + ], + "source": [ + "for i in range(num_times):\n", + " all_times_all_values[i] = all_pixel_values(0, i)\n", + " #means[frame_key][i] = sum(all_times_all_values[i]) / len(all_times_all_values[i])\n", + " #medians[frame_key][i] = median(all_times_all_values[i])\n", + " #modes[frame_key][i] = mode(all_times_all_values[i])\n", + " #std_devs[frame_key][i] = np.std(all_times_all_values[i])\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "2ae8bc57", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5001\n" + ] + } + ], + "source": [ + "files_list = [files_1015_s1, files_1015_s2, files_95_s1, files_95_s2]\n", "\n", - "time_key = 0\n", - "time = time_array[time_key]\n", - "title = \"time = \"+str(time) +\" hrs, (bins= \"+str(bins_num)+\")\"\n", + "for i in range(num_times):\n", + " #all_times_all_values[i] = all_pixel_values(frame_key, i)\n", + " WTkA_pixel_val[i] = all_pixel_values(0, i)\n", + " #WTnokA_pixel_val[i] = all_pixel_values(1, i)\n", + " EA_pixel_val[i] = all_pixel_values(2, i)\n", + " AE_pixel_val[i] = all_pixel_values(3, i)\n", + " #WTkA_all_probs[i], WTkA_all_bins[i] = np.histogram(all_pixel_values(0, i), bins=bins_num, density = True)\n", + " #WTnokA_all_probs[i], WTnokA_all_bins[i] = np.histogram(all_pixel_values(1, i), bins=bins_num, density = True)\n", + " #EA_all_probs[i], EA_all_bins[i] = np.histogram(all_pixel_values(2, i), bins=bins_num, density = True)\n", + " #AE_all_probs[i], AE_all_bins[i] = np.histogram(all_pixel_values(3, i), bins=bins_num, density = True)\n", + " \n", + " \n", + "print(len(AE_all_bins[0]))" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "585fc3a0", + "metadata": {}, + "outputs": [], + "source": [ + "def show_histograms(i, ax, array):\n", + " #print(files[i+index_add])\n", + " if time_array[i] == 0:\n", + " empty_im = np.zeros((1440,1920))\n", + " ax.imshow(empty_im, cmap = 'gray')\n", + " ax.set_title('[no image]', fontsize=10)\n", + " else:\n", + " ax.hist(array[i], density=True, bins=bins_num)\n", + " titles = condition + \", t= \" + str(time_array[i]) + \" hrs, bins= \"+str(bins_num)+\")\"\n", + " ax.set_title(titles, fontsize=font_size-1)\n", + " ax.set( ylabel='probability')\n", + " ax.set( xlabel='pixel intensity')\n", + " ax.set_xlim(0, 2500)\n", + " ax.set_ylim(0, 0.0095)\n", + " ax.tick_params(axis='both', which='major', labelsize=(font_size-3))\n", + " ax.xaxis.get_label().set_fontsize(font_size-2)\n", + " ax.yaxis.get_label().set_fontsize(font_size-2)\n", + " plt.tight_layout(pad=.25)\n", "\n", - "add = 0\n", - "alpha_num = 0.02*time_key + add/10\n", + "cmap_num = (num_times*2) - 3\n", + "def stack_histograms(i, ax, array):\n", + " #print(files[i+index_add])\n", + " ax.hist(array[i], density=True, bins=bins_num, color=cmap(0.9-(i/cmap_num)))\n", + " \n", + "def FWHM(X,Y):\n", + " frac = 2 #For FWHM frac = 2, FWtenthM, frac = 10, etc\n", + " half_max = max(Y) / 2.\n", + " #find when function crosses line half_max (when sign of diff flips)\n", + " d = Y - (max(Y) / frac)\n", + " #plot(X[0:len(d)],d) #if you are interested\n", + " #find the left and right most indexes\n", + " indexes = np.where(d > 0)[0]\n", + " return abs(X[indexes[-1]] - X[indexes[0]]) #return the difference (full width)\n", "\n", - "#ax.set_yscale(\"log\")\n", - "pixel_vals, cmap, data_label = select_data(3)\n", - "print(len(pixel_vals[time_key]))\n", - "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", - " alpha=0.6 + 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", - "pixel_vals, cmap, data_label = select_data(0)\n", - "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", - " alpha=0.5+ 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", - "pixel_vals, cmap, data_label = select_data(2)\n", - "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", - " alpha=0.45+ 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", + "def select_data(frame_key):\n", + " if frame_key == 0:\n", + " print(\"WT+kaiA histograms\")\n", + " print((WTkA_all_bins[0][0:10]))\n", + " return WTkA_pixel_val, matplotlib.cm.get_cmap('Reds'), \"1:3 :: KaiA:WT KaiC, \"+str(time)+\" hrs\"\n", + " elif frame_key == 1:\n", + " print(\"WT w/o kaiA histograms\")\n", + " return WTnokA_pixel_val, matplotlib.cm.get_cmap('Blues'), \"WT KaiC (no KaiA), \"+str(time)+\" hrs\"\n", + " elif frame_key == 2:\n", + " print(\"EA histograms\")\n", + " return EA_pixel_val, matplotlib.cm.get_cmap('Greens'), \"EA KaiC (fixed binding), \"+str(time)+\" hrs\"\n", + " elif frame_key == 3:\n", + " print(\"AE histograms\")\n", + " return AE_pixel_val, matplotlib.cm.get_cmap('Greys'), \"AE KaiC (non-binding), \"+str(time)+\" hrs\"\n", "\n", - "#counts, bins = np.histogram(pixel_vals[time_key], bins=bins_num, density = True)\n", - "#ax.bar(bins[:-1], counts, color=cmap(0.99-((time_key-add)*0.1)), \n", - " #alpha=0.6+alpha_num, label=data_label)\n", - "#pixel_vals, cmap, data_label = select_data(0)\n", - "#ax.bar(probabilities[time_key], bins[time_key][:-1], color=cmap(0.99-((time_key-add)*0.1)), alpha=0.5+alpha_num, label=data_label)\n", - "#pixel_vals, cmap, data_label = select_data(2)\n", - "#ax.bar(probabilities[time_key], bins[time_key][:-1], color=cmap(0.99-((time_key-add)*0.1)), alpha=0.45+alpha_num, label=data_label)\n", - " #print(all_FWHM[i])\n", - " #counts, bins, bars =ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num)\n", - " #print(counts.shape, bins.shape, bars)\n", - " \n", - "plt.ylabel('probability', fontsize=font_size)\n", - "plt.xlabel('pixel intensities', fontsize=font_size)\n", - "#plt.ylim(0.00001, 0.012)\n", - "#plt.ylim(0, 0.012)\n", - "#plt.xlim(0, 1500)\n", - "plt.xlim(0, 2500)\n", - "plt.title(title, fontsize=font_size)\n", - "plt.legend()\n", - "plt.show()\n", - "#fig.savefig(data_saveto+\"logy EA, AE, WT histograms- \"+title+\".jpg\", dpi=1000)" + "# My axis should display 10⁻¹ but you can switch to e-notation 1.00e+01\n", + "def log_tick_formatter(val, pos=None):\n", + " print(val)\n", + " return f\"$10^{{{int(val)}}}$\" # remove int() if you don't use MaxNLocator\n", + " # return f\"{10**val:.2e}\" # e-Notation" ] }, { "cell_type": "code", - "execution_count": 20, - "id": "df2f1fdf", - "metadata": {}, + "execution_count": 15, + "id": "741a3942", + "metadata": { + "scrolled": false + }, "outputs": [ { "data": { @@ -2464,7 +2431,7 @@ { "data": { "text/html": [ - "" + "" ], "text/plain": [ "" @@ -2477,10 +2444,69 @@ "name": "stdout", "output_type": "stream", "text": [ - "AE histograms\n" + "AE histograms\n", + "49766400\n", + "WT+kaiA histograms\n", + "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + "EA histograms\n" ] } ], + "source": [ + "\n", + "%matplotlib notebook\n", + "font_size = 16\n", + "fig, ax = plt.subplots(figsize=(9,6))\n", + "ax.tick_params(axis='both', which='major', labelsize=font_size-2)\n", + "\n", + "time_key = 0\n", + "time = time_array[time_key]\n", + "title = \"time = \"+str(time) +\" hrs, (bins= \"+str(bins_num)+\")\"\n", + "\n", + "add = 0\n", + "alpha_num = 0.02*time_key + add/10\n", + "\n", + "#ax.set_yscale(\"log\")\n", + "pixel_vals, cmap, data_label = select_data(3)\n", + "print(len(pixel_vals[time_key]))\n", + "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=0.6 + 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", + "pixel_vals, cmap, data_label = select_data(0)\n", + "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=0.5+ 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", + "pixel_vals, cmap, data_label = select_data(2)\n", + "counts, bins, bars = ax.hist(pixel_vals[time_key], histtype=\"stepfilled\", density=True, bins=bins_num, stacked=True, \n", + " alpha=0.45+ 0.02*time_key + add/10, color=cmap(0.99-((time_key-add)*0.11)), label= data_label)\n", + "\n", + "#counts, bins = np.histogram(pixel_vals[time_key], bins=bins_num, density = True)\n", + "#ax.bar(bins[:-1], counts, color=cmap(0.99-((time_key-add)*0.1)), \n", + " #alpha=0.6+alpha_num, label=data_label)\n", + "#pixel_vals, cmap, data_label = select_data(0)\n", + "#ax.bar(probabilities[time_key], bins[time_key][:-1], color=cmap(0.99-((time_key-add)*0.1)), alpha=0.5+alpha_num, label=data_label)\n", + "#pixel_vals, cmap, data_label = select_data(2)\n", + "#ax.bar(probabilities[time_key], bins[time_key][:-1], color=cmap(0.99-((time_key-add)*0.1)), alpha=0.45+alpha_num, label=data_label)\n", + " #print(all_FWHM[i])\n", + " #counts, bins, bars =ax.hist(all_times_all_values[i], histtype=\"stepfilled\", density=True, bins=bins_num)\n", + " #print(counts.shape, bins.shape, bars)\n", + " \n", + "plt.ylabel('probability', fontsize=font_size)\n", + "plt.xlabel('pixel intensities', fontsize=font_size)\n", + "#plt.ylim(0.00001, 0.012)\n", + "#plt.ylim(0, 0.012)\n", + "#plt.xlim(0, 1500)\n", + "plt.xlim(0, 2500)\n", + "plt.title(title, fontsize=font_size)\n", + "plt.legend()\n", + "plt.show()\n", + "#fig.savefig(data_saveto+\"logy EA, AE, WT histograms- \"+title+\".jpg\", dpi=1000)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df2f1fdf", + "metadata": {}, + "outputs": [], "source": [ "\n", "fig = plt.figure(figsize=(9,6))\n", @@ -2690,7 +2716,9 @@ "cell_type": "code", "execution_count": null, "id": "af3f7c44", - "metadata": {}, + "metadata": { + "scrolled": true + }, "outputs": [], "source": [ "%matplotlib notebook\n", diff --git a/simplified image histograms (2-10-23).ipynb b/simplified image histograms (2-10-23).ipynb index 4528d8e..c999067 100644 --- a/simplified image histograms (2-10-23).ipynb +++ b/simplified image histograms (2-10-23).ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "code", - "execution_count": 4, + "execution_count": 5, "id": "f7f0d53e", "metadata": {}, "outputs": [], @@ -49,7 +49,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 23, "id": "f41c7dfa", "metadata": {}, "outputs": [], @@ -69,7 +69,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 28, "id": "617edfe1", "metadata": {}, "outputs": [ @@ -77,26 +77,22 @@ "name": "stdout", "output_type": "stream", "text": [ - "found 9 files\n", - " 0 \t row1_t01.tif\n", - " 1 \t row1_t02.tif\n", - " 2 \t row1_t03.tif\n", - " 3 \t row1_t04.tif\n", - " 4 \t row1_t05.tif\n", - " 5 \t row1_t06.tif\n", - " 6 \t row1_t07.tif\n", - " 7 \t row1_t08.tif\n", - " 8 \t row1_t09.tif\n" + "found 3 files\n", + " 0 \t top_s1_40x_t1_MMStack_Pos0.ome.tif\n", + " 1 \t top_s1_40x_t2_MMStack_Pos0.ome.tif\n", + " 2 \t top_s1_40x_t3_MMStack_Pos0.ome.tif\n" ] } ], "source": [ - "exp = \"single tiffs (demo)\"\n", - "### \"data_dir\" is the pathway to the folder holding the tiff files to be analyzed \n", - "#C:\\Users\\gleech\\Documents\\GitHub\\kai codes\\user-friendly-SIA\\user-friendy-SIA\\single tiffs (demo)\n", - "data_dir = \"C:\\\\Users\\\\gleech\\\\Documents\\\\GitHub\\\\kai codes\\\\user-friendly-SIA\\\\\"+exp +\"\\\\\" \n", + "date = \"9-7-22\"\n", + "exp = \"top\"\n", + "\n", + "### \"data_dir\" is the pathway to the folder holding the tiff files to be analyzed --> change to your folder location\n", + "data_dir = \"Z:\\\\Maya N\\\\data\\\\\"+date+\"\\\\\"+exp +\"\\\\\"\n", + "data_save = \"Z:\\\\Maya N\\\\analysis\\\\\"+date+\"\\\\\"\n", "### \"plot_saveto\" is the pathway to the folder where plots and results will be saved\n", - "plot_saveto = data_dir\n", + "plot_saveto = data_save\n", "\n", "files = glob.glob(data_dir+\"*tif\") ### this should generate an ordered list of files in \"data_dir\" which have \"_t\" in their name\n", "print(\"found %i files\" % len(files))\n", @@ -105,7 +101,7 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 29, "id": "1213e586", "metadata": {}, "outputs": [ @@ -1070,7 +1066,7 @@ { "data": { "text/html": [ - "" + "" ], "text/plain": [ "" @@ -2040,7 +2036,7 @@ { "data": { "text/html": [ - "" + "" ], "text/plain": [ "" @@ -3010,7 +3006,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -3980,7 +3976,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -3991,9 +3987,9 @@ } ], "source": [ - "chosen_tiff = files[0]\n", + "chosen_tiff = files[2]\n", "\n", - "chosen_image = tiff_file.imread(chosen_tiff,key=[0]) #key=[ ] selects which frame of the tiff file will be read\n", + "chosen_image = tiff_file.imread(chosen_tiff,key=[2]) #key=[ ] selects which frame of the tiff file will be read\n", "\n", "%matplotlib notebook\n", "fig, ax = plt.subplots(figsize=(6,4)) #set up 'figure 1'\n", diff --git a/simplified image histograms - maya.ipynb b/simplified image histograms - maya.ipynb new file mode 100644 index 0000000..8bbe372 --- /dev/null +++ b/simplified image histograms - maya.ipynb @@ -0,0 +1,1819 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "f7f0d53e", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodepackbits\n", + " warnings.warn(\"failed to import %s\" % module_function)\n", + "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodelzw\n", + " warnings.warn(\"failed to import %s\" % module_function)\n", + "C:\\Users\\svc-scst291lab\\Documents\\GitHub\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.unpackints\n", + " warnings.warn(\"failed to import %s\" % module_function)\n" + ] + } + ], + "source": [ + "%matplotlib notebook\n", + "import numpy as np\n", + "from numpy.fft import fft2, ifft2, fftshift\n", + "import matplotlib\n", + "from matplotlib import pyplot as plt\n", + "from matplotlib import cm\n", + "import scipy\n", + "from scipy import stats\n", + "from statistics import mode\n", + "from scipy.optimize import curve_fit\n", + "from scipy.ndimage import gaussian_filter1d as gf1d\n", + "from scipy.ndimage import gaussian_filter as gf\n", + "from scipy.ndimage import uniform_filter as uf\n", + "\n", + "from skimage.transform import downscale_local_mean #For binning\n", + "from skimage.filters import threshold_otsu, threshold_local\n", + "\n", + "import xarray as xr #package for labeling and adding metadata to multi-dimensional arrays\n", + "from statistics import median\n", + "from statistics import mode\n", + "\n", + "import sys\n", + "#sys.path.append(\"../kai_colloids/PyDDM\") #must point to the PyDDM folder\n", + "#import ddm_analysis_and_fitting as ddm \n", + "\n", + "import tiff_file \n", + "\n", + "import io \n", + "import sys\n", + "import csv\n", + "\n", + "from PIL import Image\n", + "\n", + "import os\n", + "import glob #glob is helpful for searching for filenames or directories\n", + "import pickle #for saving data\n", + "### usually this block prints out \"nd2reader module not found. Reading of .nd2 files disabled.\" on the first run\n", + "### this is fine (unless you need to read .nd2 files), just re-run this block to make the error go away" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "f41c7dfa", + "metadata": {}, + "outputs": [], + "source": [ + "def subtract_mean_and_shift(image):\n", + " image = (image*1.0) - (np.mean(image)) \n", + " flat_im = image.ravel()\n", + " shifted_im = flat_im + np.abs(flat_im.min())\n", + " return shifted_im\n", + "\n", + "def filter_and_shift(image, filtersize):\n", + " image = (image*1.0) - ((uf(image,filtersize))*1) #(image) - unifrom-filtered(image) subtracts background\n", + " flat_im = image.ravel()\n", + " shifted_im = flat_im + np.abs(flat_im.min())\n", + " return shifted_im" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "7d00cb42", + "metadata": {}, + "outputs": [], + "source": [ + "def subtract_mean_and_shift_list(pixel_list):\n", + " pixel_list = (pixel_list*1) - (np.mean(pixel_list)) \n", + " flat_im = pixel_list.ravel()\n", + " shifted_im_list = flat_im + np.abs(flat_im.min())\n", + " return shifted_im_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "617edfe1", + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "found 19 files\n", + " 0 \t row1_t2_MMStack_Pos0.ome.tif\n", + " 1 \t row1_t3_MMStack_Pos0.ome.tif\n", + " 2 \t row1_t4_MMStack_Pos0.ome.tif\n", + " 3 \t row2_t1_MMStack_Pos0.ome.tif\n", + " 4 \t row2_t2_MMStack_Pos0.ome.tif\n", + " 5 \t row2_t3_MMStack_Pos0.ome.tif\n", + " 6 \t row2_t4_MMStack_Pos0.ome.tif\n", + " 7 \t row3_t1_MMStack_Pos0.ome.tif\n", + " 8 \t row3_t2_MMStack_Pos0.ome.tif\n", + " 9 \t row3_t3_MMStack_Pos0.ome.tif\n", + " 10 \t row3_t4_MMStack_Pos0.ome.tif\n", + " 11 \t row4_t1_MMStack_Pos0.ome.tif\n", + " 12 \t row4_t2_MMStack_Pos0.ome.tif\n", + " 13 \t row4_t3_MMStack_Pos0.ome.tif\n", + " 14 \t row4_t4_MMStack_Pos0.ome.tif\n", + " 15 \t row5_t1_MMStack_Pos0.ome.tif\n", + " 16 \t row5_t2_MMStack_Pos0.ome.tif\n", + " 17 \t row5_t3_MMStack_Pos0.ome.tif\n", + " 18 \t row5_t4_MMStack_Pos0.ome.tif\n" + ] + } + ], + "source": [ + "date = \"04-03-23\"\n", + "exp0 = \"AE-3.31µM\"\n", + "exp1 = \"AE-6.62µM\"\n", + "exp2 = \"WT-3.31µM\"\n", + "exp3 = \"WT-6.62µM\"\n", + "\n", + "time_array = [1, 7, 15, 25] #time corresponding with each tiff file\n", + "\n", + "### \"data_dir\" is the pathway to the folder holding the tiff files to be analyzed --> change to your folder location\n", + "data_dir = \"Z:\\\\Maya N\\\\data\\\\\"+date+\"\\\\all tiff files\\\\\"\n", + "data_save = \"Z:\\\\Maya N\\\\analysis\\\\\"+date+\"\\\\\"\n", + "### \"plot_saveto\" is the pathway to the folder where plots and results will be saved\n", + "plot_saveto = data_save\n", + "\n", + "files = glob.glob(data_dir+\"*tif\") ### this should generate an ordered list of files in \"data_dir\" which have \"_t\" in their name\n", + "print(\"found %i files\" % len(files))\n", + "for i,f in enumerate(files): print (' %i \\t %s' % (i, f.split('\\\\')[-1]))" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "6e67b266", + "metadata": {}, + "outputs": [], + "source": [ + "#time_array = [1, 7, 15, 25] #time corresponding with each tiff file\n", + "#time_key = 0\n", + "#time = time_array[time_key]\n", + "#image_time = \"time 3\"" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "a5007731", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "next time\n", + "0 row1_t2_MMStack_Pos0.ome.tif\n", + "4 row2_t2_MMStack_Pos0.ome.tif\n", + "8 row3_t2_MMStack_Pos0.ome.tif\n", + "12 row4_t2_MMStack_Pos0.ome.tif\n", + "16 row5_t2_MMStack_Pos0.ome.tif\n", + "next time\n", + "1 row1_t3_MMStack_Pos0.ome.tif\n", + "5 row2_t3_MMStack_Pos0.ome.tif\n", + "9 row3_t3_MMStack_Pos0.ome.tif\n", + "13 row4_t3_MMStack_Pos0.ome.tif\n", + "17 row5_t3_MMStack_Pos0.ome.tif\n", + "next time\n", + "2 row1_t4_MMStack_Pos0.ome.tif\n", + "6 row2_t4_MMStack_Pos0.ome.tif\n", + "10 row3_t4_MMStack_Pos0.ome.tif\n", + "14 row4_t4_MMStack_Pos0.ome.tif\n", + "18 row5_t4_MMStack_Pos0.ome.tif\n", + "next time\n", + "3 row2_t1_MMStack_Pos0.ome.tif\n", + "7 row3_t1_MMStack_Pos0.ome.tif\n", + "11 row4_t1_MMStack_Pos0.ome.tif\n", + "15 row5_t1_MMStack_Pos0.ome.tif\n" + ] + } + ], + "source": [ + "## pixel value lists for first condition \n", + "\n", + "t1_pixel_list_0 = []\n", + "t2_pixel_list_0 = []\n", + "t3_pixel_list_0 = []\n", + "t4_pixel_list_0 = []\n", + "all_times_list_0 = [t1_pixel_list_0, t2_pixel_list_0, t3_pixel_list_0, t4_pixel_list_0]\n", + "\n", + "for i in range(4):\n", + " print(\"next time\")\n", + " list_to_add_to0 = all_times_list_0[i]\n", + " for j in range(i, 19, 4):\n", + " print(str(j) + \" \" + files[j].split('\\\\')[-1])\n", + " chosen_image0 = tiff_file.imread(files[j], key=[0])\n", + " shifted_chosen_image0 = subtract_mean_and_shift(chosen_image0)\n", + " raveled_im0 = shifted_chosen_image0.ravel()\n", + " list_to_add_to0.extend(raveled_im0)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "1452f4ff", + "metadata": {}, + "outputs": [], + "source": [ + "## pixel value lists for second condition \n", + "\n", + "t1_pixel_list_1 = []\n", + "t2_pixel_list_1 = []\n", + "t3_pixel_list_1 = []\n", + "t4_pixel_list_1 = []\n", + "all_times_list_1 = [t1_pixel_list_1, t2_pixel_list_1, t3_pixel_list_1, t4_pixel_list_1]\n", + "\n", + "for i in range(4):\n", + " #print(\"next time\")\n", + " list_to_add_to1 = all_times_list_1[i]\n", + " for j in range(i, 19, 4):\n", + " #print(str(j) + \" \" + files[j].split('\\\\')[-1])\n", + " chosen_image1 = tiff_file.imread(files[j], key=[1])\n", + " shifted_chosen_image1 = subtract_mean_and_shift(chosen_image1)\n", + " raveled_im1 = shifted_chosen_image1.ravel()\n", + " list_to_add_to1.extend(raveled_im1)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "df252a5a", + "metadata": {}, + "outputs": [], + "source": [ + "## pixel value lists for third condition \n", + "\n", + "t1_pixel_list_2 = []\n", + "t2_pixel_list_2 = []\n", + "t3_pixel_list_2 = []\n", + "t4_pixel_list_2 = []\n", + "all_times_list_2 = [t1_pixel_list_2, t2_pixel_list_2, t3_pixel_list_2, t4_pixel_list_2]\n", + "\n", + "for i in range(4):\n", + " #print(\"next time\")\n", + " list_to_add_to2 = all_times_list_2[i]\n", + " for j in range(i, 19, 4):\n", + " #print(str(j) + \" \" + files[j].split('\\\\')[-1])\n", + " chosen_image2 = tiff_file.imread(files[j], key=[2])\n", + " shifted_chosen_image2 = subtract_mean_and_shift(chosen_image2)\n", + " raveled_im2 = shifted_chosen_image2.ravel()\n", + " list_to_add_to2.extend(raveled_im2)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "e44a053c", + "metadata": {}, + "outputs": [], + "source": [ + "## pixel value lists for fourth condition \n", + "\n", + "t1_pixel_list_3 = []\n", + "t2_pixel_list_3 = []\n", + "t3_pixel_list_3 = []\n", + "t4_pixel_list_3 = []\n", + "all_times_list_3 = [t1_pixel_list_3, t2_pixel_list_3, t3_pixel_list_3, t4_pixel_list_3]\n", + "\n", + "for i in range(4):\n", + " #print(\"next time\")\n", + " list_to_add_to3 = all_times_list_3[i]\n", + " for j in range(i, 19, 4):\n", + " #print(str(j) + \" \" + files[j].split('\\\\')[-1])\n", + " shifted_chosen_image3 = tiff_file.imread(files[j], key=[3])\n", + " shifted_chosen_image3 = subtract_mean_and_shift(chosen_image3)\n", + " raveled_im3 = shifted_chosen_image3.ravel()\n", + " list_to_add_to3.extend(raveled_im3)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "9450287f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "13824000\n", + "[179.0, 165.0, 139.0, 142.0]\n", + "[180.0, 180.0, 178.0, 202.0]\n", + "[491.0, 480.0, 460.0, 440.0]\n", + "[150.0, 163.0, 153.0, 189.0]\n", + "13824000\n", + "[217.0, 231.0, 239.0, 240.0]\n", + "[312.0, 282.0, 283.0, 330.0]\n", + "[322.0, 331.0, 297.0, 349.0]\n", + "[173.0, 146.0, 171.0, 163.0]\n", + "13824000\n", + "[340.0, 327.0, 333.0, 321.0]\n", + "[686.0, 715.0, 663.0, 679.0]\n", + "[379.0, 362.0, 379.0, 442.0]\n", + "[643.0, 635.0, 646.0, 594.0]\n", + "13824000\n", + "[759.0, 773.0, 774.0, 773.0]\n", + "[759.0, 773.0, 774.0, 773.0]\n", + "[759.0, 773.0, 774.0, 773.0]\n", + "[759.0, 773.0, 774.0, 773.0]\n" + ] + } + ], + "source": [ + "## checkpoint to make sure data is not overwritten\n", + "\n", + "print(len(t1_pixel_list_0))\n", + "print(t1_pixel_list_0[0:4])\n", + "print(t2_pixel_list_0[0:4])\n", + "print(t3_pixel_list_0[0:4])\n", + "print(t4_pixel_list_0[0:4])\n", + "\n", + "print(len(t1_pixel_list_1))\n", + "print(t1_pixel_list_1[0:4])\n", + "print(t2_pixel_list_1[0:4])\n", + "print(t3_pixel_list_1[0:4])\n", + "print(t4_pixel_list_1[0:4])\n", + "\n", + "print(len(t1_pixel_list_2))\n", + "print(t1_pixel_list_2[0:4])\n", + "print(t2_pixel_list_2[0:4])\n", + "print(t3_pixel_list_2[0:4])\n", + "print(t4_pixel_list_2[0:4])\n", + "\n", + "print(len(t1_pixel_list_3))\n", + "print(t1_pixel_list_3[0:4])\n", + "print(t2_pixel_list_3[0:4])\n", + "print(t3_pixel_list_3[0:4])\n", + "print(t4_pixel_list_3[0:4])" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "63fa82fa", + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'chosen_tiff5 = files[16]\\nchosen_image5 = tiff_file.imread(chosen_tiff5, key=[image_key])'" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "image_key = 3\n", + "##experimental condition [1/2xAE, 1xAE, 1/2xWT, 1xWT]\n", + "\n", + "chosen_tiff1 = files[3]\n", + "chosen_image1 = tiff_file.imread(chosen_tiff1, key=[image_key])\n", + "chosen_tiff2 = files[7]\n", + "chosen_image2 = tiff_file.imread(chosen_tiff2, key=[image_key])\n", + "chosen_tiff3 = files[11]\n", + "chosen_image3 = tiff_file.imread(chosen_tiff3, key=[image_key])\n", + "chosen_tiff4 = files[15]\n", + "chosen_image4 = tiff_file.imread(chosen_tiff4, key=[image_key])\n", + "'''chosen_tiff5 = files[16]\n", + "chosen_image5 = tiff_file.imread(chosen_tiff5, key=[image_key])'''" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "364de232", + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (fig.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " this.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " // Apply a ponyfill if ResizeObserver is not implemented by browser.\n", + " if (this.ResizeObserver === undefined) {\n", + " if (window.ResizeObserver !== undefined) {\n", + " this.ResizeObserver = window.ResizeObserver;\n", + " } else {\n", + " var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n", + " this.ResizeObserver = obs.ResizeObserver;\n", + " }\n", + " }\n", + "\n", + " this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " if (entry.contentBoxSize instanceof Array) {\n", + " // Chrome 84 implements new version of spec.\n", + " width = entry.contentBoxSize[0].inlineSize;\n", + " height = entry.contentBoxSize[0].blockSize;\n", + " } else {\n", + " // Firefox implements old version of spec.\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " }\n", + " } else {\n", + " // Chrome <84 implements even older version of spec.\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " if (entry.devicePixelContentBoxSize) {\n", + " // Chrome 84 implements new version of spec.\n", + " canvas.setAttribute(\n", + " 'width',\n", + " entry.devicePixelContentBoxSize[0].inlineSize\n", + " );\n", + " canvas.setAttribute(\n", + " 'height',\n", + " entry.devicePixelContentBoxSize[0].blockSize\n", + " );\n", + " } else {\n", + " canvas.setAttribute('width', width * fig.ratio);\n", + " canvas.setAttribute('height', height * fig.ratio);\n", + " }\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " this.resizeObserverInstance.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " event.preventDefault();\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / fig.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n", + " var x1 = msg['x1'] / fig.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / fig.ratio,\n", + " fig.canvas.height / fig.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * this.ratio;\n", + " var y = canvas_pos.y * this.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "\n", + "///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n", + "// prettier-ignore\n", + "var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + " fig.cell_info[0].output_area.element.on(\n", + " 'cleared',\n", + " { fig: fig },\n", + " fig._remove_fig_handler\n", + " );\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / fig.ratio;\n", + " fig.cell_info[0].output_area.element.off(\n", + " 'cleared',\n", + " fig._remove_fig_handler\n", + " );\n", + " fig.resizeObserverInstance.unobserve(fig.canvas_div);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / this.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function (event) {\n", + " var fig = event.data.fig;\n", + " if (event.target !== this) {\n", + " // Ignore bubbled events from children.\n", + " return;\n", + " }\n", + " fig.close_ws(fig, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%matplotlib notebook\n", + "\n", + " #AE = yellow, EA = blue, WT = magenta\n", + "c1 = \"magenta\" #AE: 1/4x = darkgolenrod, 1/2x = gold, 1x = khaki\n", + "c2 = \"violet\" #EA: 1/4x = darkblue, 1/2x = blue, 1x = dodgerblue\n", + "c3 = \"darkmagenta\" #WT: 1/4x = darkmagenta, 1/2x = magenta, 1x = violet\n", + "c4 = \"violet\"\n", + "\n", + "bin_num = 100 # number of histogram bins, changing this effects the histogram (can be set to \"auto\")\n", + "\n", + "fig, ax = plt.subplots(figsize=(6,4)) #set up 'figure 1' - mean subtraction\n", + "all_intensities_list0 = t3_pixel_list_3\n", + "all_intensities_list1 = subtract_mean_and_shift(chosen_image1)\n", + "all_intensities_list2 = subtract_mean_and_shift(chosen_image2)\n", + "all_intensities_list3 = subtract_mean_and_shift(chosen_image3)\n", + "all_intensities_list4 = subtract_mean_and_shift(chosen_image4)\n", + "'''all_intensities_list5 = subtract_mean_and_shift(chosen_image5)\n", + "'''\n", + "probabilities0, bins0 = np.histogram(all_intensities_list0, bins=bin_num, density = True)\n", + "ax.plot(bins0[:-1], probabilities0, 'o-', linewidth=2, markersize=0, color = c3, alpha = 1, label = \"all images\")\n", + "counts0, bins0, bars0 = ax.hist(all_intensities_list0, bins=bin_num, density = True, \n", + " color = c4, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities1, bins1 = np.histogram(all_intensities_list1, bins=bin_num, density = True)\n", + "ax.plot(bins1[:-1], probabilities1, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts1, bins1, bars1 = ax.hist(all_intensities_list1, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities2, bins2 = np.histogram(all_intensities_list2, bins=bin_num, density = True)\n", + "ax.plot(bins2[:-1], probabilities2, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts2, bins2, bars2 = ax.hist(all_intensities_list2, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities3, bins3 = np.histogram(all_intensities_list3, bins=bin_num, density = True)\n", + "ax.plot(bins3[:-1], probabilities3, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts3, bins3, bars3 = ax.hist(all_intensities_list3, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "probabilities4, bins4 = np.histogram(all_intensities_list4, bins=bin_num, density = True)\n", + "ax.plot(bins4[:-1], probabilities4, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts4, bins4, bars4 = ax.hist(all_intensities_list4, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "'''probabilities5, bins5 = np.histogram(all_intensities_list5, bins=bin_num, density = True)\n", + "ax.plot(bins5[:-1], probabilities5, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, linestyle='dashed')\n", + "counts5, bins5, bars5 = ax.hist(all_intensities_list5, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")'''\n", + "\n", + "\n", + "ax.set_xlim(0,3000)\n", + "ax.set_ylim(10E-6, 10E-3)\n", + "ax.tick_params(axis='both', labelsize=20)\n", + "ax.set_yscale('log')\n", + "#ax.set_xlabel(\"Pixel Intensity\")\n", + "#ax.set_ylabel(\"Probability\")\n", + "ax.legend(loc = \"upper right\", fontsize=18)\n", + "#ax.set_title(\"Probability Distribution at \" + str(time) + \" hr\", fontsize=12)\n", + "#fig.savefig(plot_saveto + \"probability histogram for \" + exp3 + \".jpg\", dpi=800, bbox_inches = 'tight', transparent=True) \n", + "fig.savefig(plot_saveto + \"single image histogram\" + exp3 + \"1hr.jpg\", dpi=800, bbox_inches = 'tight', transparent=True)\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "504f3c42", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fa5b8a39", + "metadata": {}, + "outputs": [], + "source": [ + "#histogram tests\n", + "\n", + "fig, ax2 = plt.subplots(figsize=(6,4)) #set up 'figure 1' - raw intensity values\n", + "probabilities, bins = np.histogram(chosen_image1.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins[:-1], probabilities, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"1\")\n", + "counts, bins, bars = ax2.hist(chosen_image1.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities2, bins2 = np.histogram(chosen_image2.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins2[:-1], probabilities2, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"2\", linestyle='dashed')\n", + "counts2, bins2, bars2 = ax2.hist(chosen_image2.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "\n", + "\n", + "probabilities3, bins3 = np.histogram(chosen_image3.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins3[:-1], probabilities3, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"3\", linestyle='dotted')\n", + "counts3, bins3, bars3 = ax2.hist(chosen_image3.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "probabilities4, bins4 = np.histogram(chosen_image4.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins4[:-1], probabilities4, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"4\", linestyle='dotted')\n", + "counts4, bins4, bars4 = ax2.hist(chosen_image4.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "probabilities5, bins5 = np.histogram(chosen_image5.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins5[:-1], probabilities5, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = \"5\", linestyle='dotted')\n", + "counts5, bins5, bars5 = ax2.hist(chosen_image5.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + " #plots a histogram for a given list; \n", + " #___.ravel() converts a 2D image array to a 1D list of pixel intensities\n", + "ax2.set_xlim(0,3500)\n", + "ax2.set_ylim(10E-6, 10E-3) \n", + "ax2.tick_params(axis='both', labelsize=20)\n", + "ax2.set_yscale('log')\n", + "#ax2.set_xlabel(\"Pixel Intensity\")\n", + "#ax2.set_ylabel(\"Probability\")\n", + "#ax2.legend(loc = \"upper right\", fontsize=18)\n", + "#ax2.set_title(\"Probability Distribution at \" + str(time) + \" hr\", fontsize=12)\n", + "#fig.savefig(plot_saveto + \"histogram for AE \" + image_time + \".jpg\", dpi=800, bbox_inches = 'tight', transparent=True) \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "405fea85", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(figsize=(6,4)) #set up 'figure 1' - mean subtraction\n", + "all_intensities_list0 = subtract_mean_and_shift(chosen_image1) #subtract_mean_and_shift\n", + "all_intensities_list1 = subtract_mean_and_shift(chosen_image2)\n", + "all_intensities_list2 = subtract_mean_and_shift(chosen_image3)\n", + "all_intensities_list3 = subtract_mean_and_shift(chosen_image4)\n", + "all_intensities_list4 = subtract_mean_and_shift(chosen_image5)\n", + "\n", + "probabilities0, bins0 = np.histogram(all_intensities_list0, bins=bin_num, density = True)\n", + "ax.plot(bins0[:-1], probabilities0, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[0])\n", + "counts0, bins0, bars0 = ax.hist(all_intensities_list0, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities1, bins1 = np.histogram(all_intensities_list1, bins=bin_num, density = True)\n", + "ax.plot(bins1[:-1], probabilities1, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[1], \n", + " linestyle='dashed')\n", + "counts1, bins1, bars1 = ax.hist(all_intensities_list1, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities2, bins2 = np.histogram(all_intensities_list2, bins=bin_num, density = True)\n", + "ax.plot(bins2[:-1], probabilities2, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[2], \n", + " linestyle='dotted')\n", + "counts2, bins2, bars2 = ax.hist(all_intensities_list2, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities3, bins3 = np.histogram(all_intensities_list3, bins=bin_num, density = True)\n", + "ax.plot(bins3[:-1], probabilities3, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[3], \n", + " linestyle='dashdot')\n", + "counts3, bins3, bars3 = ax.hist(all_intensities_list3, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities4, bins4 = np.histogram(all_intensities_list4, bins=bin_num, density = True)\n", + "ax.plot(bins4[:-1], probabilities4, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = time_array[3], \n", + " linestyle='dashdot')\n", + "counts4, bins4, bars4 = ax.hist(all_intensities_list4, bins=bin_num, density = True, \n", + " color = c2, alpha = 0.2, histtype = \"stepfilled\")\n", + "\n", + "\n", + "ax.set_xlim(0,3000)\n", + "ax.set_ylim(10E-6, 10E-3)\n", + "ax.tick_params(axis='both', labelsize=20)\n", + "ax.set_yscale('log')\n", + "#ax.set_xlabel(\"Pixel Intensity\")\n", + "#ax.set_ylabel(\"Probability\")\n", + "#ax.legend(loc = \"upper right\", title=\"Time (hrs)\", fontsize=18)\n", + "#ax.set_title(\"Probability Distribution at \" + str(time) + \" hr\", fontsize=12)\n", + "#fig.savefig(plot_saveto + \"probability histogram for \" + exp1 + \".jpg\", dpi=800, bbox_inches = 'tight', transparent=True) \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a7baceb0", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3bbd28c2", + "metadata": {}, + "outputs": [], + "source": [ + "histogram_dict = {} #makes dictionary\n", + "\n", + "histogram_dict[\"AE\"] = {} #makes subdictionary for AE files\n", + "histogram_dict[\"AE\"][probabilities] = probabilities\n", + "histogram_dict[\"AE\"][probabilities] = probabilities_subtract_mean\n", + "histogram_dict[\"AE\"][bins] = bins\n", + "histogram_dict[\"AE\"][bins]= bins_subtract_mean\n", + "\n", + "histogram_dict[\"EA\"] = {} #makes subdictionary for EA files\n", + "histogram_dict[\"EA\"][probabilities] = probabilities2\n", + "histogram_dict[\"EA\"][probabilities] = probabilities_subtract_mean2\n", + "histogram_dict[\"EA\"][bins] = bins2\n", + "histogram_dict[\"EA\"][bins]= bins_subtract_mean2\n", + "\n", + "histogram_dict[\"WT\"] = {} #makes subdictionary for WT files\n", + "histogram_dict[\"WT\"][probabilities] = probabilities3\n", + "histogram_dict[\"WT\"][probabilities] = probabilities_subtract_mean3\n", + "histogram_dict[\"WT\"][bins] = bins3\n", + "histogram_dict[\"WT\"][bins]= bins_subtract_mean3\n", + "\n", + "with open(\"1x WT bead\" + date + \".pkl\", 'wb') as f: #saves intensity data\n", + " pickle.dump(histogram_dict, f)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1c3a6677", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d5bca1c6", + "metadata": {}, + "outputs": [], + "source": [ + "## plots raw histogram (not updated)\n", + "\n", + "fig, ax2 = plt.subplots(figsize=(6,4)) #set up 'figure 1' - raw intensity values\n", + "probabilities, bins = np.histogram(chosen_image1.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins[:-1], probabilities, 'o-', linewidth=2, markersize=0, color = c1, alpha = 1, label = exp1)\n", + "counts, bins, bars = ax2.hist(chosen_image1.ravel(), bins=bin_num, density = True, color = c1, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "\n", + "probabilities2, bins2 = np.histogram(chosen_image2.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins2[:-1], probabilities2, 'o-', linewidth=2, markersize=0, color = c2, alpha = 1, label = exp2, linestyle='dashed')\n", + "counts2, bins2, bars2 = ax2.hist(chosen_image2.ravel(), bins=bin_num, density = True, color = c2, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + "\n", + "\n", + "probabilities3, bins3 = np.histogram(chosen_image3.ravel(), bins=bin_num, density = True)\n", + "ax2.plot(bins3[:-1], probabilities3, 'o-', linewidth=2, markersize=0, color = c3, alpha = 1, label = exp3, linestyle='dotted')\n", + "counts3, bins3, bars3 = ax2.hist(chosen_image3.ravel(), bins=bin_num, density = True, color = c3, alpha = 0.2, \n", + " histtype = \"stepfilled\")\n", + "\n", + " #plots a histogram for a given list; \n", + " #___.ravel() converts a 2D image array to a 1D list of pixel intensities\n", + "ax2.set_xlim(1000,3500)\n", + "ax2.set_ylim(10E-6, 10E-3) \n", + "ax2.tick_params(axis='both', labelsize=20)\n", + "ax2.set_yscale('log')\n", + "#ax2.set_xlabel(\"Pixel Intensity\")\n", + "#ax2.set_ylabel(\"Probability\")\n", + "ax2.legend(loc = \"upper right\", fontsize=18)\n", + "#ax2.set_title(\"Probability Distribution at \" + str(time) + \" hr\", fontsize=12)\n", + "fig.savefig(plot_saveto + \"probability histogram for AE \" + image_time + \".jpg\", dpi=800, bbox_inches = 'tight', transparent=True) \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "51527778", + "metadata": {}, + "outputs": [], + "source": [ + "## plots shifted histogram (not updated)\n", + "\n", + "fig, ax3 = plt.subplots(figsize=(6,4)) #set up 'figure 3' - background subtraction\n", + "all_intensities_list = filter_and_shift(chosen_image, 1000) \n", + "ax3.hist(all_intensities_list, bins=bin_num, density = True, color = c)\n", + "ax3.set_xlim(0,1500)\n", + "ax3.set_ylim(10E-6, 10E-3)\n", + "ax3.set_yscale('log')\n", + "ax3.set_xlabel(\"pixel intensity\")\n", + "ax3.set_ylabel(\"probability\")\n", + "fig.savefig(plot_saveto + \"filtered histogram for \" + title + \".jpg\") \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "95b732fb", + "metadata": {}, + "outputs": [], + "source": [ + "## attempt to only include certain files\n", + "\n", + "print(files[0])\n", + "print(files[0].split('\\\\'))\n", + "print(files[0].split('\\\\')[-1])\n", + "print((files[0].split('\\\\')[-1])[0:4])\n", + "obj_mag = (files[0].split('\\\\')[-1])[0:3]\n", + "\n", + "new_files_list = []\n", + "\n", + "for i in range(len(files)):\n", + " current_file = files[i]\n", + " obj_mag = (current_file.split('\\\\')[-1])[0:3]\n", + " if obj_mag != \"20x\":\n", + " new_files_list.extend(current_file)\n", + " #new_files_list[i] = current_file\n", + " \n", + "print(\"found %i files\" % len(new_files_list))\n", + "for i,f in enumerate(new_files_list): print (' %i \\t %s' % (i, f.split('\\\\')[-1]))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "88e12437", + "metadata": {}, + "outputs": [], + "source": [ + "#image_key[1/2x AE, 1x AE, 1/2x WT, 1x WT]\n", + "image_key = 0\n", + "number_of_images = 5\n", + "\n", + "#file number\n", + "a=0\n", + "b=4\n", + "c=8\n", + "d=12\n", + "e=16\n", + "\n", + "chosen_tiff1 = files[a]\n", + "chosen_image1 = tiff_file.imread(chosen_tiff1, key=[image_key]) #key=[ ] selects which frame of the tiff file will be read\n", + "chosen_tiff2 = files[b]\n", + "chosen_image2 = tiff_file.imread(chosen_tiff2, key=[image_key])\n", + "chosen_tiff3 = files[c]\n", + "chosen_image3 = tiff_file.imread(chosen_tiff3, key=[image_key])\n", + "chosen_tiff4 = files[d]\n", + "chosen_image4 = tiff_file.imread(chosen_tiff4, key=[image_key])\n", + "chosen_tiff5 = files[e]\n", + "chosen_image5 = tiff_file.imread(chosen_tiff5, key=[image_key])\n", + "\n", + "\n", + "all_pixel_values = []\n", + "for i in range(number_of_images):\n", + " image_array_2D = tiff_file.imread(chosen_tiff[i], key=[image_key])\n", + " raveled_im = image_array_2D.ravel()\n", + " all_pixel_values.extend(raveled_im)\n", + "#print('List 1 before extend():', chosen_image1)\n", + "\n", + "\n", + "#might say \"list index out of range\" - if so, just change first key from i→1, run then change back to i and rerun\n", + "\n", + " # image_array_2D2 = tiff_file.imread(chosen_tiff2, key=[image_key])\n", + " # pixel_values_list2 = image_array_2D2.ravel()\n", + " # image_array_2D3 = tiff_file.imread(chosen_tiff3, key=[image_key])\n", + " # pixel_values_list3 = image_array_2D3.ravel() \n", + " # image_array_2D4 = tiff_file.imread(chosen_tiff4, key=[image_key])\n", + " # pixel_values_list4 = image_array_2D4.ravel() \n", + " # image_array_2D5 = tiff_file.imread(chosen_tiff5, key=[image_key])\n", + " # pixel_values_list5 = image_array_2D5.ravel()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3a961b57", + "metadata": {}, + "outputs": [], + "source": [ + "##prints images (not updated)\n", + "\n", + "fig, ax4 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff1.split('\\\\')[-1])[:-21]) #splits the full file name into only the relevent info\n", + "ax4.set_title(title, fontsize=10)\n", + "ax4.imshow(chosen_image1, cmap='gray') #'cmap' is the color map used to display the image, 'gray' is short for greyscale\n", + "ax4.axis('off')\n", + "\n", + "'''fig, ax9 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff1.split('\\\\')[-1])[:-21]) #splits the full file name into only the relevent info\n", + "ax9.set_title(title, fontsize=10)\n", + "ax9.imshow(subtract_mean_and_shift(chosen_image1), cmap='gray') #'cmap' is the color map used to display the image, 'gray' is short for greyscale\n", + "ax9.axis('off')'''\n", + "\n", + "fig, ax5 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff2.split('\\\\')[-1])[:-21]) \n", + "ax5.set_title(title, fontsize=10)\n", + "ax5.imshow(chosen_image2, cmap='gray') \n", + "ax5.axis('off')\n", + "\n", + "fig, ax6 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff3.split('\\\\')[-1])[:-21]) \n", + "ax6.set_title(title, fontsize=10)\n", + "ax6.imshow(chosen_image3, cmap='gray')\n", + "ax6.axis('off')\n", + "\n", + "fig, ax7 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff4.split('\\\\')[-1])[:-21]) \n", + "ax7.set_title(title, fontsize=10)\n", + "ax7.imshow(chosen_image4, cmap='gray')\n", + "ax7.axis('off')\n", + "\n", + "fig, ax8 = plt.subplots(figsize=(6,4)) \n", + "title = str((chosen_tiff5.split('\\\\')[-1])[:-21]) \n", + "ax8.set_title(title, fontsize=10)\n", + "ax8.imshow(chosen_image5, cmap='gray')\n", + "ax8.axis('off')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "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.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/single image SIA (user friendly).ipynb b/single image SIA (user friendly).ipynb index 35801f9..28170ff 100644 --- a/single image SIA (user friendly).ipynb +++ b/single image SIA (user friendly).ipynb @@ -2,9 +2,22 @@ "cells": [ { "cell_type": "code", - "execution_count": 19, + "execution_count": 1, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\svc-scst291lab\\documents\\Github\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodepackbits\n", + " warnings.warn(\"failed to import %s\" % module_function)\n", + "C:\\Users\\svc-scst291lab\\documents\\Github\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.decodelzw\n", + " warnings.warn(\"failed to import %s\" % module_function)\n", + "C:\\Users\\svc-scst291lab\\documents\\Github\\user-friendly-SIA\\tiff_file.py:1995: UserWarning: failed to import _tifffile.unpackints\n", + " warnings.warn(\"failed to import %s\" % module_function)\n" + ] + } + ], "source": [ "%matplotlib notebook\n", "import numpy as np\n", @@ -42,7 +55,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 2, "metadata": {}, "outputs": [], "source": [ @@ -173,7 +186,7 @@ }, { "cell_type": "code", - "execution_count": 31, + "execution_count": 3, "metadata": { "scrolled": false }, @@ -182,6 +195,7 @@ "name": "stdout", "output_type": "stream", "text": [ + "Z:\\Maya N\\data\\9-7-22\\top\\\n", "found 3 files\n", " 0 \t top_s1_40x_t1_MMStack_Pos0.ome.tif\n", " 1 \t top_s1_40x_t2_MMStack_Pos0.ome.tif\n", @@ -199,6 +213,8 @@ "### \"plot_saveto\" is the pathway to the folder where plots and results will be saved\n", "plot_saveto = data_save\n", "\n", + "print(data_dir)\n", + "\n", "files = glob.glob(data_dir+\"*tif\") ### this should generate an ordered list of files in \"data_dir\" which have \"_t\" in their name\n", "print(\"found %i files\" % len(files))\n", "for i,f in enumerate(files): print (' %i \\t %s' % (i, f.split('\\\\')[-1]))" @@ -213,9 +229,17 @@ }, { "cell_type": "code", - "execution_count": 33, + "execution_count": 4, "metadata": {}, "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\svc-scst291lab\\documents\\Github\\user-friendly-SIA\\tiff_file.py:724: FutureWarning: arrays to stack must be passed as a \"sequence\" type such as list or tuple. Support for non-sequence iterables such as generators is deprecated as of NumPy 1.16 and will raise an error in the future.\n", + " result = numpy.vstack((p.asarray() if p else nopage)\n" + ] + }, { "name": "stdout", "output_type": "stream", @@ -258,7 +282,7 @@ }, { "cell_type": "code", - "execution_count": 34, + "execution_count": 5, "metadata": {}, "outputs": [], "source": [ @@ -290,7 +314,7 @@ }, { "cell_type": "code", - "execution_count": 40, + "execution_count": 6, "metadata": { "scrolled": false }, @@ -1263,7 +1287,7 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ "" @@ -1279,8 +1303,8 @@ "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mIndexError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 30\u001b[0m \u001b[0mdetails\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mexp\u001b[0m\u001b[1;33m+\u001b[0m \u001b[1;34m\", %3.1f files (block_size= %3i, offset= %3i)\"\u001b[0m \u001b[1;33m%\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mblock_size\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0moffset_val\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 31\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 32\u001b[1;33m \u001b[0mshow_raw_images\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0max\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mi\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mframe_key\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 33\u001b[0m \u001b[0mi\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mi\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 34\u001b[0m \u001b[0mdetails\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mexp\u001b[0m\u001b[1;33m+\u001b[0m \u001b[1;34m\", %i files (raw images)\"\u001b[0m \u001b[1;33m%\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", - "\u001b[1;32m\u001b[0m in \u001b[0;36mshow_raw_images\u001b[1;34m(ax, i, frame_key)\u001b[0m\n\u001b[0;32m 89\u001b[0m \u001b[0max\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'[no image]'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfontsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 90\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 91\u001b[1;33m \u001b[0mtest_image\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mtiff_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mimread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiles\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mframe_key\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 92\u001b[0m \u001b[0mtitle\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiles\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msplit\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'\\\\'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m#OPTION: frame_array[i]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 93\u001b[0m \u001b[0max\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtitle\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfontsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 30\u001b[0m \u001b[0mdetails\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mexp\u001b[0m\u001b[1;33m+\u001b[0m \u001b[1;34m\", %3.1f files (block_size= %3i, offset= %3i)\"\u001b[0m \u001b[1;33m%\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mblock_size\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0moffset_val\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 31\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 32\u001b[1;33m \u001b[0mshow_raw_images\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0max\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mi\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mframe_key\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 33\u001b[0m \u001b[0mi\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mi\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 34\u001b[0m \u001b[0mdetails\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mexp\u001b[0m\u001b[1;33m+\u001b[0m \u001b[1;34m\", %i files (raw images)\"\u001b[0m \u001b[1;33m%\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m+\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;32m\u001b[0m in \u001b[0;36mshow_raw_images\u001b[1;34m(ax, i, frame_key)\u001b[0m\n\u001b[0;32m 89\u001b[0m \u001b[0max\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'[no image]'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfontsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 90\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 91\u001b[1;33m \u001b[0mtest_image\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mtiff_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mimread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiles\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mframe_key\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 92\u001b[0m \u001b[0mtitle\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiles\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msplit\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'\\\\'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m#OPTION: frame_array[i]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 93\u001b[0m \u001b[0max\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtitle\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfontsize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mIndexError\u001b[0m: list index out of range" ] }