{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Force Spectroscopy Processing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Import packages and find all the *.nid files."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C:\\Users\\applab\\Downloads\\Jupyter Notebooks\\ForceSpetroscopy with 1  *.nid force files:\n",
      "['spectroscopy_0001.nid']\n"
     ]
    }
   ],
   "source": [
    "from NSFopen.read import read as afmreader\n",
    "\n",
    "import os\n",
    "from os import listdir\n",
    "from os.path import isfile, join\n",
    "\n",
    "import numpy as np\n",
    "import math\n",
    "import pprint\n",
    "import collections\n",
    "from pprint import pprint\n",
    "\n",
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "dirpath = os.getcwd()\n",
    "\n",
    "# list all *.nid files\n",
    "onlyfiles = [f for f in listdir(dirpath) if isfile(join(dirpath, f)) and f.split(\".\")[-1] == \"nid\"]\n",
    "\n",
    "# list only files where there is \"spectroscopy_\" in the filename\n",
    "force_files = [f for f in onlyfiles if \"spectroscopy\" in f.split(\"_\")]\n",
    "\n",
    "print(dirpath, \"with\", len(force_files),\" *.nid force files:\")\n",
    "pprint(force_files)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Read data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "filename = 'spectroscopy_0001.nid'\n",
    "alldata = afmreader(filename, verbose=False).data\n",
    "params = afmreader(filename, verbose=False).param"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Study the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Image  Forward   Z-Axis           [[-2.0353380013257264e-06, -2.0353067460469904...\n",
       "                 Amplitude        [[0.19510995596647263, 0.19624395295977592, 0....\n",
       "                 Phase            [[-0.3227592632174492, -0.570032112300396, 1.4...\n",
       "                 Z-Axis Sensor    [[1.3012584000825895e-06, 1.3011265546083438e-...\n",
       "                 Deflection                                                     NaN\n",
       "       Backward  Z-Axis           [[-2.0308267816901207e-06, -2.0314367319457234...\n",
       "                 Amplitude        [[0.19098110496997833, 0.19194109365344048, 0....\n",
       "                 Phase            [[-0.9834825620055199, -1.571555882692337, 0.6...\n",
       "                 Z-Axis Sensor    [[1.301939662545919e-06, 1.301317282021045e-06...\n",
       "                 Deflection                                                     NaN\n",
       "Spec   Forward   Z-Axis                                                         NaN\n",
       "                 Amplitude                                                      NaN\n",
       "                 Phase                                                          NaN\n",
       "                 Z-Axis Sensor    [[-2.4028351604938504e-06, -2.4016023427248004...\n",
       "                 Deflection       [[-5.270044375212667e-10, -5.464680488219607e-...\n",
       "       Backward  Z-Axis                                                         NaN\n",
       "                 Amplitude                                                      NaN\n",
       "                 Phase                                                          NaN\n",
       "                 Z-Axis Sensor    [[-2.1268137395381934e-06, -2.1259107962250702...\n",
       "                 Deflection       [[-8.34981137885745e-11, -1.0336219565944979e-...\n",
       "dtype: object"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alldata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tip          Manufacturer                                                                                 BudgetSensors\n",
       "             Name                                                                                            Tap150Al-G\n",
       "             Prop0                                                                    {'Value': 2.72436, 'Unit': 'N/m'}\n",
       "             Prop1                                                                    {'Value': 150000.0, 'Unit': 'Hz'}\n",
       "             Prop2                                                                     {'Value': 0.000125, 'Unit': 'm'}\n",
       "                                                                                            ...                        \n",
       "Header Dump  ProcessorSet-{138707ED-FD93-4E28-B2B0-C5DA628CB815}:0    {'Name': 'Indentation', 'GUID': '{138707ED-FD9...\n",
       "             ProcessorSet-{AB0B4062-81AF-464B-A7F7-75B11891ACF8}:0    {'Name': 'Slope', 'GUID': '{AB0B4062-81AF-464B...\n",
       "             ProcessorSet-{AB0B4062-81AF-464B-A7F7-75B11891ACF8}:1    {'Name': 'Slope', 'GUID': '{AB0B4062-81AF-464B...\n",
       "             ProcessorSet-{1220F4A8-053A-494D-B28C-3635059D1530}:0    {'Name': 'MaxAdhesion', 'GUID': '{1220F4A8-053...\n",
       "             ProcessorSet-{1220F4A8-053A-494D-B28C-3635059D1530}:1    {'Name': 'MaxAdhesion', 'GUID': '{1220F4A8-053...\n",
       "Length: 88, dtype: object"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "params"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Load the spectroscopy data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "adhesion_data = alldata['Spec']['Backward']['Deflection']\n",
    "zaxis = alldata['Spec']['Backward']['Z-Axis Sensor']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Plot spectorscopy data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 379052 characters]\n",
      "text/plain": [
       "<Figure size 792x720 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "font = {'size': 16}\n",
    "matplotlib.rc('font', **font)\n",
    "\n",
    "adhesion_force = []\n",
    "\n",
    "for i in range(len(adhesion_data)):\n",
    "    plt.plot(zaxis[i]*1e9+1250, adhesion_data[i]*1e9)\n",
    "    adhesion_force.append(np.min(adhesion_data[i]*1e9))\n",
    "\n",
    "plt.xlim([-100, 100])\n",
    "plt.ylim([-15, 5])\n",
    "plt.xticks(np.arange(-50, 150, step=50))\n",
    "\n",
    "plt.xlabel('Z (nm)')\n",
    "plt.ylabel('Force (nN)')\n",
    "\n",
    "fig = matplotlib.pyplot.gcf()\n",
    "fig.set_size_inches(11, 10)\n",
    "fig.savefig('adhesion.png', dpi=300)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Plot histogram"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 19320 characters]\n",
      "text/plain": [
       "<Figure size 792x720 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "med = np.median(adhesion_force)\n",
    "stdev = np.std(adhesion_force)\n",
    "n, bins, patches = plt.hist(adhesion_force, 100, density=True, facecolor='g', alpha=0.75)\n",
    "plt.title('\\u00B5 = {:.1f} nN, \\u03C3 = {:.2f} nN'.format(med, stdev))\n",
    "plt.xlabel('Force (nN)')\n",
    "plt.ylabel('Occurence')\n",
    "fig = matplotlib.pyplot.gcf()\n",
    "fig.set_size_inches(11, 10)\n",
    "fig.savefig('adhesion_dist.png', dpi=300)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "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.7.0"
  },
  "metadata": {
   "interpreter": {
    "hash": "6a59ef28384e64e06d3c3cdd32c8846c98b2b5aa94c86f7aef6fbc7e75733461"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
