{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# This cell is added by sphinx-gallery\n\n%matplotlib inline\n\nimport mrsimulator\nprint(f'You are using mrsimulator v{mrsimulator.__version__}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# 13C 2D PASS NMR of LHistidine\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Coesite is a high-pressure (2-3 GPa) and high-temperature (700\u00b0C) polymorph of silicon\ndioxide $\\text{SiO}_2$. Coesite has five crystallographic $^{17}\\text{O}$\nsites. The experimental dataset used in this example is published in\nGrandinetti `et. al.` [#f1]_\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport csdmpy as cp\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport mrsimulator.signal_processing as sp\nimport mrsimulator.signal_processing.apodization as apo\nfrom mrsimulator import Simulator\nfrom mrsimulator.methods import SSB2D\nfrom mrsimulator.utils import get_spectral_dimensions\nfrom mrsimulator.utils.spectral_fitting import LMFIT_min_function, make_LMFIT_params\nfrom lmfit import Minimizer, report_fit\nfrom mrsimulator.utils.collection import single_site_system_generator\n\n# global plot configuration\nmpl.rcParams[\"figure.figsize\"] = [4.5, 3.0]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Import the dataset\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "filename = \"https://sandbox.zenodo.org/record/687656/files/1H13C_CPPASS_LHistidine.csdf\"\npass_data = cp.load(filename)\n\n# For the spectral fitting, we only focus on the real part of the complex dataset.\n# The script assumes that the dimension at index 0 is the isotropic dimension.\n# Transpose the dataset as required.\npass_data = pass_data.real.T\n\n# Convert the coordinates along each dimension from Hz to ppm.\n_ = [item.to(\"ppm\", \"nmr_frequency_ratio\") for item in pass_data.dimensions]\n\n# Normalize the spectrum\npass_data /= pass_data.max()\n\n# plot of the dataset.\nlevels = (np.arange(10) + 0.3) / 15  # contours are drawn at these levels.\nax = plt.subplot(projection=\"csdm\")\ncb = ax.contour(pass_data, colors=\"k\", levels=levels, alpha=0.5, linewidths=0.5)\nplt.colorbar(cb)\nax.set_xlim(200, 10)\nax.invert_yaxis()\nplt.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Create a fitting model\nThe fitting model includes the Simulator and the SignalProcessor objects. First\ncreate the Simulator object.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Create the guess sites and spin systems.\n# default unit of isotropic_chemical_shift is ppm and Cq is Hz.\nshifts = [120, 128, 135, 175, 55, 25]  # in ppm\nzeta = [-70, -65, -60, -60, -10, -10]  # in  Hz\neta = [0.8, 0.4, 0.9, 0.3, 0.0, 0.0]\n\nspin_systems = single_site_system_generator(\n    isotopes=\"13C\",\n    isotropic_chemical_shifts=shifts,\n    shielding_symmetric={\"zeta\": zeta, \"eta\": eta},\n    abundance=100 / 6,\n)\n\n# Create the DAS method.\n# Get the spectral dimension paramters from the experiment.\nspectral_dims = get_spectral_dimensions(pass_data)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ssb = SSB2D(\n    channels=[\"13C\"],\n    magnetic_flux_density=9.4,  # in T\n    rotor_frequency=1500,  # in Hz\n    spectral_dimensions=spectral_dims,\n    experiment=pass_data,  # also add the measurement to the method.\n)\n\n# Optimize the script by pre-setting the transition pathways for each spin system from\n# the das method.\nfor sys in spin_systems:\n    sys.transition_pathways = ssb.get_transition_pathways(sys)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Create the Simulator object and add the method and spin system objects.\nsim = Simulator()\nsim.spin_systems = spin_systems  # add the spin systems\nsim.methods = [ssb]  # add the method\nsim.run()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Add Post simulation processing\nprocessor = sp.SignalProcessor(\n    operations=[\n        # Gaussian convolution along the isotropic dimensions.\n        sp.FFT(axis=0),\n        apo.Exponential(FWHM=\"20 Hz\"),\n        sp.IFFT(axis=0),\n        sp.Scale(factor=0.6),\n    ]\n)\n# Apply post simulation operations\nprocessed_data = processor.apply_operations(data=sim.methods[0].simulation).real"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# The plot of the simulation after signal processing.\nax = plt.subplot(projection=\"csdm\")\nax.contour(processed_data, colors=\"r\", levels=levels, alpha=0.5, linewidths=0.5)\ncb = ax.contour(pass_data, colors=\"k\", levels=levels, alpha=0.5, linewidths=0.5)\nplt.colorbar(cb)\nax.set_xlim(200, 10)\nplt.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Least-squares minimization with LMFIT\nFirst create the fitting parameters.\nUse the :func:`~mrsimulator.utils.spectral_fitting.make_LMFIT_params` for a quick\nsetup.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "params = make_LMFIT_params(sim, processor)\nprint(params.pretty_print())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Run the minimization using LMFIT\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "minner = Minimizer(LMFIT_min_function, params, fcn_args=(sim, processor))\nresult = minner.minimize()\nreport_fit(result)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Simulate the spectrum corresponding to the optimum parameters\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "sim.run()\nprocessed_data = processor.apply_operations(data=sim.methods[0].simulation).real"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot the spectrum\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ax = plt.subplot(projection=\"csdm\")\nax.contour(processed_data, colors=\"r\", levels=levels, alpha=0.5, linewidths=0.5)\ncb = ax.contour(pass_data, colors=\"k\", levels=levels, alpha=0.5, linewidths=0.5)\nplt.colorbar(cb)\nax.set_xlim(200, 10)\nplt.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. [#f1] Grandinetti, P. J., Baltisberger, J. H., Farnan, I., Stebbins, J. F.,\n      Werner, U. and Pines, A.\n      Solid-State $^{17}\\text{O}$ Magic-Angle and Dynamic-Angle Spinning NMR\n      Study of the $\\text{SiO}_2$ Polymorph Coesite, J. Phys. Chem. 1995,\n      **99**, *32*, 12341-12348.\n      `DOI: 10.1021/j100032a045 <https://doi.org/10.1021/j100032a045>`_\n\n"
      ]
    }
  ],
  "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.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}