keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
mpes-kit/fuller
figures/extra/E03_Band_path.ipynb
.ipynb
4,605
155
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Slice the band mapping or band structure data along certain high-symmetry lines\n", "The following demo relates to the software package [mpes](https://github.com/mpes-kit/mpes/), which contains the functionality for making band path figures" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import warnings as wn\n", "wn.filterwarnings(\"ignore\")\n", "\n", "import numpy as np\n", "import fuller\n", "import matplotlib.pyplot as plt\n", "import matplotlib as mpl\n", "from mpes import analysis as aly, fprocessing as fp\n", "from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mpl.rcParams['font.family'] = 'sans-serif'\n", "mpl.rcParams['font.sans-serif'] = 'Arial'\n", "mpl.rcParams['axes.linewidth'] = 2\n", "mpl.rcParams['pdf.fonttype'] = 42\n", "mpl.rcParams['ps.fonttype'] = 42" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load photoemission data files\n", "fdir = r'../../data/pes'\n", "files = fuller.utils.findFiles(fdir, fstring='/*', ftype='h5')\n", "fdata = fp.readBinnedhdf5(files[1])\n", "mc = aly.MomentumCorrector(fdata['V'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc.selectSlice2D(selector=slice(30, 32), axis=2)\n", "mc.featureExtract(mc.slice, method='daofind', sigma=6, fwhm=20, symscores=False)\n", "\n", "# False detection filter, if needed\n", "try:\n", " mc.pouter_ord = mc.pouter_ord[[0,1,3,5,6,9],:]\n", "except:\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc.view(image=mc.slice, annotated=True, points=mc.features)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define high-symmetry points\n", "G = mc.pcent # Gamma point\n", "K = mc.pouter_ord[0,:] # K point\n", "K1 = mc.pouter_ord[1,:] # K' point\n", "M = (K + K1) / 2 # M point\n", "\n", "# Define cutting path\n", "pathPoints = np.asarray([G, M, K, G])\n", "nGM, nMK, nKG = 70, 39, 79\n", "segPoints = [nGM, nMK, nKG]\n", "rowInds, colInds, pathInds = aly.points2path(pathPoints[:,0], pathPoints[:,1], npoints=segPoints)\n", "nSegPoints = len(rowInds)\n", "\n", "# Normalize data\n", "imNorm = fdata['V'] / fdata['V'].max()\n", "\n", "# Sample the data along high-symmetry lines (k-path) connecting the corresponding high-symmetry points\n", "pathDiagram = aly.bandpath_map(imNorm, pathr=rowInds, pathc=colInds, eaxis=2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Evals = fdata['E']\n", "ehi, elo = Evals[0], Evals[469]\n", "\n", "f, ax = plt.subplots(figsize=(10, 6))\n", "plt.imshow(pathDiagram[:470, :], cmap='Blues', aspect=10.9, extent=[0, nSegPoints, elo, ehi], vmin=0, vmax=0.5)\n", "ax.set_xticks(pathInds)\n", "ax.set_xticklabels(['$\\overline{\\Gamma}$', '$\\overline{\\mathrm{M}}$',\n", " '$\\overline{\\mathrm{K}}$', '$\\overline{\\Gamma}$'], fontsize=15)\n", "for p in pathInds[:-1]:\n", " ax.axvline(x=p, c='r', ls='--', lw=2, dashes=[4, 2])\n", "# ax.axhline(y=0, ls='--', color='r', lw=2)\n", "ax.yaxis.set_major_locator(MultipleLocator(2))\n", "ax.yaxis.set_minor_locator(MultipleLocator(1))\n", "ax.yaxis.set_label_position(\"right\")\n", "ax.yaxis.tick_right()\n", "ax.set_ylabel('Energy (eV)', fontsize=15, rotation=-90, labelpad=20)\n", "ax.tick_params(axis='x', length=0, pad=6)\n", "ax.tick_params(which='both', axis='y', length=8, width=2, labelsize=15)" ] } ], "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.3" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
figures/extra/E02_Brillouin_zoning.ipynb
.ipynb
4,761
223
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Cutting band structure or band mapping data to the first Brillouin zone" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import warnings as wn\n", "wn.filterwarnings(\"ignore\")\n", "\n", "import numpy as np\n", "import fuller\n", "import scipy.io as sio\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1. Load data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bs_hse = sio.loadmat(r'../../data/theory/WSe2_HSE06_bands.mat')\n", "bshse = np.moveaxis(bs_hse['evb'][::2,...], 1, 2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "bs_hse['kxxsc'].shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2. Determine Brillouin zone boundary using landmarks" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn = fuller.generator.BrillouinZoner(bands=bshse, axis=0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.select_slice(selector=slice(0, 1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.findlandmarks(image=bzn.slice, method='daofind', sigma=25, fwhm=40, sigma_radius=4, image_ofs=[25,25,0,0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.visualize(bzn.slice, annotated=True, points=dict(pts=bzn.pouter_ord))\n", "# plt.scatter(bzn.pcent[1], bzn.pcent[0], s=100, c='r')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3. Calculate geometric parameters for creating data mask" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "imr, imc = bzn.slice.shape\n", "hexside = np.linalg.norm(bzn.pouter_ord[1,:] - bzn.pouter_ord[2,:])\n", "hexdiag = np.linalg.norm(bzn.pouter_ord[1,:] - bzn.pouter_ord[4,:])\n", "imside = min(bzn.slice.shape)\n", "ptop = (imr - hexdiag) / 2\n", "# Calculate the distance of twice of the apothem (apo diameter)\n", "apod = np.abs(np.sqrt(3)*hexside)\n", "pleft = (imc - hexdiag) / 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.maskgen(hexdiag=int(hexdiag), imside=imside, image=None, padded=True,\n", " pad_top=int(ptop), pad_left=int(pleft), ret='all')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.visualize(bzn.mask*bzn.slice, annotated=True, points=dict(pts=bzn.pouter_ord))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.bandcutter(selector=slice(0, None))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Energy band data sliced to the first Brillouin zone now bears the name `bandcuts`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.bandcuts.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4. Save sliced data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Summarize the content of the class (remove the semiconlon to see output)\n", "bzn.summary();" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# bzn.save_data(form='h5', save_addr=r'./wse2_hse_bandcuts.h5')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.imshow(bzn.bandcuts[0,...])" ] } ], "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.3" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
figures/extra/E01_Hexagonal_tiling.ipynb
.ipynb
2,209
106
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Construct large patches of the Brillouin zones (from DFT calculations) using symmetry operations" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import warnings as wn\n", "wn.filterwarnings(\"ignore\")\n", "\n", "import numpy as np\n", "import fuller\n", "from mpes import visualization as vis\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Download data \n", "pbedata = fuller.utils.load_calculation(r'../../data/theory/patch/band_all_paths_cart.out.pbe')\n", "pbedata.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.imshow(pbedata[..., 285])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Perform symmetry operations to fill a larger patch of Brillouin zones\n", "pbe_vb, pbe_cb = fuller.generator.bandstack(pbedata[:50,:,:], nvb=80, ncb=40, gap_id=286, cvd=103.9)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pbe_vb.shape, pbe_cb.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.imshow(pbe_vb[0,...])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "axs = vis.sliceview3d(pbe_cb, axis=0, ncol=8, colormap='Spectral_r');" ] } ], "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.3" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
figures/recon/R02_Example_reconstruction_synthetic_multiband_3D_data.ipynb
.ipynb
5,729
199
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Reconstruction of synthetic 3D multiband photoemission data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import warnings as wn\n", "wn.filterwarnings(\"ignore\")\n", "\n", "import os\n", "import numpy as np\n", "import fuller\n", "from fuller.mrfRec import MrfRec\n", "import matplotlib.pyplot as plt\n", "import matplotlib as mpl\n", "from tqdm import tqdm_notebook as tqdm\n", "%matplotlib inline\n", "\n", "mpl.rcParams['font.family'] = 'sans-serif'\n", "mpl.rcParams['font.sans-serif'] = 'Arial'\n", "mpl.rcParams['axes.linewidth'] = 2\n", "mpl.rcParams['pdf.fonttype'] = 42\n", "mpl.rcParams['ps.fonttype'] = 42" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import synthetic data and axes values\n", "fdir = r'../../data/synthetic'\n", "data = fuller.utils.loadHDF(fdir + r'/synth_data_WSe2_LDA_top8.h5', hierarchy='nested')\n", "E0 = data['params']['E']\n", "kx = data['params']['kx']\n", "ky = data['params']['ky']\n", "I = np.moveaxis(np.nan_to_num(data['data']['mpes_padded']), 0, -1)\n", "I.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import initial conditions\n", "datab = fuller.utils.loadHDF(r'../../data/theory/bands_padded/wse2_hse_bands_padded.h5')\n", "datab['bands_padded'].shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compare ground truth with coefficient-tuned band structure\n", "for i in range(6):\n", " if i < 5:\n", " plt.plot(ky, data['data']['bands_padded'][i, :, 150], c='k')\n", " plt.plot(ky, datab['bands_padded'][i, :, 128].T, ls='--', c='b')\n", " elif i == 5:\n", " plt.plot(ky, data['data']['bands_padded'][i, :, 150], c='k', label='ground truth (LDA)')\n", " plt.plot(ky, datab['bands_padded'][i, :, 128].T, ls='--', c='b', label='initialization (PBE)')\n", "\n", "plt.tick_params(axis='both', length=10, labelsize=15)\n", "plt.ylabel('Energy (eV)', fontsize=15)\n", "plt.legend(bbox_to_anchor=(1,0.2,0.2,0.3), fontsize=15, frameon=False);" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create MRF model\n", "mrf = MrfRec(E=E0, kx=kx, ky=ky, I=I, eta=.12)\n", "mrf.I_normalized = False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mrf.normalizeI(kernel_size=(20, 20, 20), clip_limit=0.01)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# These hyperparameters are already tuned\n", "etas = [0.08, 0.1, 0.08, 0.1, 0.1, 0.14, 0.08, 0.08]\n", "ofs = [0.3, 0.1, 0.26, 0.14, 0.3, 0.24, 0.34, 0.14]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Demonstration for reconstructing one band\n", "mrf.eta = etas[1]\n", "offset = ofs[1]\n", "mrf.initializeBand(kx, ky, datab['bands_padded'][1,...], offset=offset, kScale=1., flipKAxes=False)\n", "mrf.iter_para(100, use_gpu=True, disable_tqdm=False, graph_reset=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "# Illustration of outcome (black line = initialization, red line = reconstruction)\n", "mrf.plotBands()\n", "mrf.plotI(ky=0, plotBand=True, plotBandInit=True, plotSliceInBand=False, cmapName='coolwarm')\n", "mrf.plotI(ky=0.4, plotBand=True, plotBandInit=True, plotSliceInBand=False, cmapName='coolwarm')\n", "mrf.plotI(kx=0, plotBand=True, plotBandInit=True, plotSliceInBand=False, cmapName='coolwarm')\n", "mrf.plotI(kx=0.4, plotBand=True, plotBandInit=True, plotSliceInBand=False, cmapName='coolwarm')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reconstruct all bands and save the results" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if not os.path.exists(r'../../results/hse_lda'):\n", " os.mkdir(r'../../results/hse_lda')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Reconstruct band by band\n", "for idx, (eta, offset) in enumerate(zip(tqdm(etas), ofs)):\n", "\n", " mrf.eta = eta\n", " iband = idx + 1\n", " mrf.initializeBand(kx, ky, datab['bands_padded'][idx,...], offset=offset, kScale=1., flipKAxes=False)\n", " mrf.iter_para(100, use_gpu=True, disable_tqdm=True, graph_reset=True)\n", " mrf.saveBand(r'../../results/hse_lda/mrf_rec_band='+str(iband).zfill(2)+'_ofs='+str(offset)+'_eta='+str(eta)+'.h5',\n", " index=iband)" ] } ], "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.3" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
figures/recon/R01_Example_reconstruction_wse2_3D_data.ipynb
.ipynb
5,592
172
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Reconstruction of photoemission band structure using Markov Random Field model\n", "### Model setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import warnings as wn\n", "wn.filterwarnings(\"ignore\")\n", "\n", "import os\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import matplotlib as mpl\n", "import fuller\n", "from fuller.mrfRec import MrfRec\n", "from tqdm import tnrange\n", "\n", "%matplotlib inline\n", "mpl.rcParams['axes.linewidth'] = 2\n", "mpl.rcParams['pdf.fonttype'] = 42\n", "mpl.rcParams['ps.fonttype'] = 42" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load preprocessed data\n", "data_path = '../../data/pes/3_smooth.h5'\n", "data = fuller.utils.loadHDF(data_path)\n", "\n", "E = data['E'][:470]\n", "kx = data['kx']\n", "ky = data['ky']\n", "I = data['V'][...,:470]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create MRF model\n", "mrf = MrfRec(E=E, kx=kx, ky=ky, I=I, eta=.12)\n", "mrf.I_normalized = True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reconstruction" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Initialize parameters for loop\n", "path_dft = ['../../data/theory/WSe2_LDA_bands.mat',\n", " '../../data/theory/WSe2_PBE_bands.mat',\n", " '../../data/theory/WSe2_PBEsol_bands.mat',\n", " '../../data/theory/WSe2_HSE06_bands.mat']\n", "path_hyperparam = ['../../data/hyperparameter/LDA.csv',\n", " '../../data/hyperparameter/PBE.csv',\n", " '../../data/hyperparameter/PBEsol.csv',\n", " '../../data/hyperparameter/HSE06.csv']\n", "num_dft = 1 # Number of DFTs to consider, can be up to 4 here, but set to 1 to save computation\n", "recon = np.zeros((num_dft, 14, len(kx), len(ky)))\n", "\n", "for ind_dft in tnrange(num_dft, desc='Initialization'):\n", " # Load hyperparameter and DFT\n", " hyperparam = np.loadtxt(path_hyperparam[ind_dft], delimiter=',', skiprows=1)\n", " kx_dft, ky_dft, E_dft = mrf.loadBandsMat(path_dft[ind_dft])\n", " \n", " for ind_band in tnrange(14, desc='Band'):\n", " # Set eta and initialization\n", " mrf.eta = hyperparam[ind_band, 1]\n", " mrf.initializeBand(kx=kx_dft, ky=ky_dft, Eb=E_dft[2 * ind_band,...], kScale=hyperparam[ind_band, 3],\n", " offset=hyperparam[ind_band, 2] + 0.65, flipKAxes=True)\n", " \n", " # Perform optimization\n", " mrf.iter_para(150, disable_tqdm=True)\n", " \n", " # Store result\n", " recon[ind_dft, ind_band, ...] = mrf.getEb()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Results" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot slices ky slice\n", "dft_name = ['LDA', 'PBE', 'PBEsol', 'HSE06']\n", "\n", "# Mask to only plot Brillouin zone\n", "mask = np.load('../../data/processed/WSe2_Brillouin_Zone_Mask.npy')\n", "mrf.I = mrf.I * mask[:, :, None]\n", "ky_val = 0\n", "ind_ky = np.argmin(np.abs(mrf.ky - ky_val))\n", "\n", "# Loop over initializations and bands\n", "for ind_dft in range(num_dft):\n", " mrf.plotI(ky=ky_val, cmapName='coolwarm')\n", " plt.title(dft_name[ind_dft], fontsize=26)\n", " plt.xlim((-1.35, 1.3))\n", " kx_dft, ky_dft, E_dft = mrf.loadBandsMat(path_dft[ind_dft])\n", " for ind_band in range(14):\n", " #mrf.initializeBand(kx=kx_dft, ky=ky_dft, Eb=E_dft[2 * ind_band,...], kScale=1,\n", " # offset=0.65, flipKAxes=True)\n", " #E0 = mrf.E[mrf.indE0[:, ind_ky]]\n", " #plt.plot(mrf.kx, E0 * mask[:, ind_ky], 'k', linewidth=2.0, \n", " # label='DFT' if ind_band==0 else None, zorder=3)\n", " mrf.initializeBand(kx=kx_dft, ky=ky_dft, Eb=E_dft[2 * ind_band,...], kScale=hyperparam[ind_band, 3],\n", " offset=hyperparam[ind_band, 2] + 0.65, flipKAxes=True)\n", " E0 = mrf.E[mrf.indE0[:, ind_ky]]\n", " plt.plot(mrf.kx, E0 * mask[:, ind_ky], 'c--', linewidth=2.0, \n", " label='Initialization' if ind_band==0 else None, zorder=2)\n", " plt.plot(mrf.kx, recon[ind_dft, ind_band, :, ind_ky] * mask[:, ind_ky], 'r', linewidth=2.0,\n", " label='Reconstruction' if ind_band==0 else None, zorder=1)\n", " plt.legend(loc=4, prop={'size': 14}, framealpha=1)\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.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
examples/synthetic_mpes_data_generation_I (from calculation).ipynb
.ipynb
4,958
242
{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import fuller\n", "from fuller import generator\n", "import scipy.io as sio\n", "from mpes import analysis as aly\n", "from symmetrize import pointops as po\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from imp import reload\n", "reload(fuller)\n", "reload(fuller.utils)\n", "reload(fuller.generator)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fth = r'../theory'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bsth = sio.loadmat(fth + r'/WSe2_DFT_BandStructure.mat')\n", "bsth.keys()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.pcolormesh(bsth['kxx'], bsth['kyy'], bsth['evb'][0,...])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nr, nc = bsth['kxx'].shape\n", "kxvals = bsth['kxx'][:,0]\n", "kyvals = bsth['kyy'][0,:]\n", "xlen, ylen = 256, int(256/(nr/nc))\n", "ofs = (xlen - ylen) // 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bandaug, _, [kxx, kyy] = fuller.utils.interpolate2d(kxvals, kyvals, bsth['evb'][0,...], xlen, ylen, ret='all')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "plt.pcolormesh(kxx, kyy, bandaug)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Detect landmarks" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc = aly.MomentumCorrector(image=bandaug)\n", "mc.slice = mc.image\n", "mc.featureExtract(image=mc.image, direction='ccw', method='daofind', sigma=15, fwhm=30)\n", "mc.view(mc.image, points=mc.features, annotated=True, cmap='viridis')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc.pouter_ord[0,:] - mc.pouter_ord[3,:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Synthesize artificial MPES data within the first Brillouin zone" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hm, margins = fuller.generator.hexmask(hexside=170, imside=256, padded=True, pad_left=43, pad_top=43, ret='all')\n", "plt.imshow(hm[:,ofs:-ofs]*bandaug)\n", "plt.scatter(mc.pouter_ord[:,1], mc.pouter_ord[:,0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bandcut = cut_margins(bandaug, margins, offsetx=ofs)\n", "hmcut = cut_margins(hm, margins)\n", "bandhm = bandcut*hmcut\n", "plt.imshow(bandhm)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bandhm_dmean = np.nan_to_num(bandhm - np.nanmean(bandhm))\n", "bcf = fuller.generator.decomposition_hex2d(bandhm_dmean, nterms=400)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.plot(bcf)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dg = fuller.generator.MPESDataGenerator()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simulate DFT error in initial estimates" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
examples/05_synthetic_data_and_initial_conditions.ipynb
.ipynb
11,861
398
{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import fuller\n", "from mpes import analysis as aly\n", "import matplotlib.pyplot as plt\n", "from tqdm import tqdm_notebook as tqdm\n", "import tifffile as ti\n", "import matplotlib as mpl\n", "from scipy import interpolate" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from imp import reload\n", "reload(fuller)\n", "reload(fuller.utils)\n", "reload(fuller.generator)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ncfs = 400\n", "bases = fuller.generator.ppz.hexike_basis(nterms=ncfs, npix=208, vertical=True, outside=0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute the polynomial decomposition coefficients\n", "bandout = np.nan_to_num(fuller.utils.loadHDF(r'.\\wse2_lda_bandcuts.h5')['bands'])\n", "bcfs = []\n", "for i in tqdm(range(14)):\n", " bcfs.append(fuller.generator.decomposition_hex2d(bandout[i,...] + 0.86813, bases=bases, baxis=0, ret='coeffs'))\n", "bcfs = np.array(bcfs)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.imshow(bandout[0,...])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generate Brillouin zone mask\n", "bzmsk = fuller.generator.hexmask(hexdiag=208, imside=208, padded=False, margins=[1, 1, 1, 1])\n", "bzmsk_tight = fuller.generator.hexmask(hexdiag=202, imside=208, padded=True, margins=[3, 3, 3, 3])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nbands = 8" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generate photoemission data without padding\n", "bshape = (208, 208)\n", "amps = np.ones(bshape)\n", "xs = np.linspace(-4.5, 0.5, 280, endpoint=True)\n", "syndat = np.zeros((280, 208, 208))\n", "gamss = []\n", "for i in tqdm(range(nbands)):\n", " gams = 0.05\n", " syndat += aly.voigt(feval=True, vardict={'amp':amps, 'xvar':xs[:,None,None], 'ctr':(bandout[i,...] + 0.86813),\n", " 'sig':0.1, 'gam':gams})" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generate edge-padded bands\n", "synfbands = []\n", "padsize = ((24, 24), (24, 24))\n", "for i in tqdm(range(nbands)): \n", " impad = fuller.generator.hexpad(bandout[i,...] + 0.86813, cvd=104, mask=bzmsk, edgepad=padsize)\n", " synfbands.append(fuller.generator.restore(impad, method='cubic'))\n", "synfbands = np.asarray(synfbands)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generate edge-padded photoemission data\n", "bshape = (256, 256)\n", "amps = np.ones(bshape)\n", "xs = np.linspace(-4.5, 0.5, 280, endpoint=True)\n", "synfdat = np.zeros((280, 256, 256))\n", "gamss = []\n", "for i in tqdm(range(nbands)):\n", "# btemp = np.nan_to_num(synbands[i,...])\n", "# gams = np.abs(synfbands[i,...] - np.nanmean(synfbands[i,...]))/3\n", " gams = 0.05\n", "# gamss.append(gams)\n", " synfdat += aly.voigt(feval=True, vardict={'amp':amps, 'xvar':xs[:,None,None], 'ctr':(synfbands[i,...]),\n", " 'sig':0.1, 'gam':gams})\n", "# gamss = np.asarray(gamss)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xss = np.linspace(-4.5, 0.5, 280, endpoint=True)\n", "xss[1] - xss[0], xss.size" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.imshow(synfdat[:,80,:], aspect=0.5, origin='lower', cmap='terrain_r')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generate mask for large coefficients\n", "cfmask = bcfs.copy()\n", "cfmask[np.abs(cfmask) >= 1e-2] = 1.\n", "cfmask[np.abs(cfmask) < 1e-2] = 0\n", "cfmask[:, 0] = 0 # No rigid shift modulation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generate coefficient-scaled data\n", "synfscaled = {}\n", "errs = np.around(np.arange(0.3, 2.01, 0.05), 2)\n", "bscmod = bcfs.copy()\n", "\n", "for err in tqdm(errs):\n", " \n", " synbands = []\n", " for i in range(nbands):\n", " \n", " bscmod[i, 1:] = err*bcfs[i, 1:] # Scale only the dispersion terms (leave out the first offset term)\n", " bandmod = fuller.generator.reconstruction_hex2d(bscmod[i, :], bases=bases)\n", " \n", " # Sixfold rotational symmetrization\n", " symmed = fuller.generator.rotosymmetrize(bandmod, center=(104, 104), rotsym=6)[0]\n", " symmed = fuller.generator.reflectosymmetrize(symmed, center=(104, 104), refangles=[0, 90])\n", " padded = fuller.generator.hexpad(symmed, cvd=104, mask=bzmsk_tight, edgepad=padsize)\n", " synbands.append(fuller.generator.restore(padded, method='nearest'))\n", " \n", " synfscaled[str(err)] = np.asarray(synbands)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(8, 8))\n", "plt.imshow(synbands[0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generate coefficient-perturbed data\n", "synfperturbed = {}\n", "noizamp = 0.02\n", "# noizamps = np.asarray([5e-3, 1e-2, 2.5e-2, 5e-2, 7.5e-2, 1e-1, 2.5e-1, 5e-1])\n", "bscmod = bcfs.copy()\n", "\n", "for si in tqdm(range(nbands)):\n", " \n", " # Generate random perturbation to the coefficients\n", " np.random.seed(si)\n", " noiz = fuller.utils.coeffgen((nbands, 400), amp=noizamp, distribution='uniform', modulation='exp',\n", " mask=cfmask[:nbands,:], low=-1, high=1)\n", " bscmod[:nbands, 1:] += noiz[:, 1:]\n", " \n", " synbands = []\n", " for i in range(nbands):\n", " bandmod = fuller.generator.reconstruction_hex2d(noiz[i, :], bases=bases)*bzmsk\n", " bandmod += bandout[i,...]\n", " \n", " # Sixfold rotational symmetrization\n", " symmed = fuller.generator.rotosymmetrize(bandmod, center=(104, 104), rotsym=6)[0]\n", " symmed = fuller.generator.reflectosymmetrize(symmed, center=(104, 104), refangles=[0, 90])*bzmsk_tight\n", " padded = fuller.generator.hexpad(symmed, cvd=104, mask=bzmsk_tight, edgepad=padsize)\n", " synbands.append(fuller.generator.restore(padded, method='nearest'))\n", " \n", " synfperturbed[str(si).zfill(2)] = np.asarray(synbands)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(8, 8))\n", "plt.imshow(synbands[0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generate coefficient-perturbed data\n", "synfperturbed2 = {}\n", "noizamp = 0.05\n", "# noizamps = np.asarray([5e-3, 1e-2, 2.5e-2, 5e-2, 7.5e-2, 1e-1, 2.5e-1, 5e-1])\n", "bscmod = bcfs.copy()\n", "\n", "for si in tqdm(range(nbands)):\n", " \n", " # Generate random perturbation to the coefficients\n", " np.random.seed(si)\n", " noiz = fuller.utils.coeffgen((nbands, 400), amp=noizamp, distribution='uniform', modulation='exp',\n", " mask=cfmask[:nbands,:], low=-1, high=1)\n", " bscmod[:nbands, 1:] += noiz[:, 1:]\n", " \n", " synbands = []\n", " for i in range(nbands):\n", " bandmod = fuller.generator.reconstruction_hex2d(noiz[i, :], bases=bases)*bzmsk\n", " bandmod += bandout[i,...]\n", " \n", " # Sixfold rotational symmetrization\n", " symmed = fuller.generator.rotosymmetrize(bandmod, (104, 104), rotsym=6)[0]\n", " symmed = fuller.generator.reflectosymmetrize(symmed, center=(104, 104), refangles=[0, 90])*bzmsk_tight\n", " padded = fuller.generator.hexpad(symmed, cvd=104, mask=bzmsk_tight, edgepad=padsize)\n", " synbands.append(fuller.generator.restore(padded, method='nearest'))\n", " \n", " synfperturbed2[str(si).zfill(2)] = np.asarray(synbands)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fuller.utils.saveHDF(*[['data', {'bands':bandout[:8,...], 'bands_padded':synfbands, 'mpes':syndat, 'mpes_padded':synfdat}],\n", " ['estimates_amp_tuning_padded', synfscaled], \n", " ['estimates_amp=0.02', synfperturbed], ['estimates_amp=0.05', synfperturbed2],\n", " ['params', {'coeffs':bcfs, 'basis':bases, 'E':xs, 'amps':amps, 'sig':0.1, 'gam':gams,\n", " 'kx':axes['axes'][0], 'ky':axes['axes'][1], 'mask':bzmsk, 'mask_tight':bzmsk_tight}]],\n", " save_addr=r'./synth_data_test_004_WSe2_LDA_top8.h5')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calibrate momentum axes\n", "mc = aly.MomentumCorrector(np.asarray(synbands))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc.selectSlice2D(selector=slice(0,1), axis=0)\n", "mc.view(mc.slice)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc.featureExtract(mc.slice, method='daofind', fwhm=30, sigma=20)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc.view(mc.slice, annotated=True, points=mc.features)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculate distances\n", "dg = 1.64/np.cos(np.radians(30))\n", "dg" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "axes = mc.calibrate(mc.slice, mc.pouter_ord[0,:], mc.pcent, dist=dg, equiscale=True, ret='axes')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "axes['axes'][0][0], axes['axes'][0][-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".pyenv38", "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.12" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
examples/01_Hexagonal_tiling.ipynb
.ipynb
2,556
122
{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from mpes import visualization as vis\n", "import fuller\n", "import matplotlib.pyplot as plt\n", "import os" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_path = '../' # Put in Path to a storage of at least 20 Gbyte free space.\n", "if not os.path.exists(data_path + \"/data.zip\"):\n", " os.system(f\"curl -L --output {data_path}/data.zip https://zenodo.org/records/7314278/files/data.zip\")\n", "if not os.path.isdir(data_path + \"/data\"):\n", " os.system(f\"unzip -d {data_path} -o {data_path}/data\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pbedata = fuller.utils.load_calculation('../data/theory/patch/band_all_paths_cart.out.pbe')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pbedata.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.imshow(pbedata[..., 285])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pbe_vb, pbe_cb = fuller.generator.bandstack(pbedata[:50,:,:], nvb=80, ncb=40, gap_id=286, cvd=103.9)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pbe_vb.shape, pbe_cb.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.imshow(pbe_vb[0,...])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "axs = vis.sliceview3d(pbe_cb, axis=0, ncol=8, colormap='rainbow');" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".pyenv38", "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.12" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
examples/02_Brillouin_zoning.ipynb
.ipynb
6,441
300
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Cutting band structure or band mapping data to the first Brillouin zone" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import fuller\n", "import scipy.io as sio\n", "import matplotlib.pyplot as plt\n", "import os" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_path = '../' # Put in Path to a storage of at least 20 Gbyte free space.\n", "if not os.path.exists(data_path + \"/data.zip\"):\n", " os.system(f\"curl -L --output {data_path}/data.zip https://zenodo.org/records/7314278/files/data.zip\")\n", "if not os.path.isdir(data_path + \"/data\"):\n", " os.system(f\"unzip -d {data_path} -o {data_path}/data\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1. Load data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bs_hse = sio.loadmat('../data/theory/WSe2_HSE06_bands.mat')\n", "bshse = np.moveaxis(bs_hse['evb'][::2,...], 1, 2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "bs_hse['kxxsc'].shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2. Determine Brillouin zone boundary using landmarks" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn = fuller.generator.BrillouinZoner(bands=bshse, axis=0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.select_slice(selector=slice(0, 1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.findlandmarks(image=bzn.slice, method='daofind', sigma=25, fwhm=40, sigma_radius=4, image_ofs=[25,25,0,0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.visualize(bzn.slice, annotated=True, points=dict(pts=bzn.pouter_ord))\n", "# plt.scatter(bzn.pcent[1], bzn.pcent[0], s=100, c='r')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3. Calculate geometric parameters for creating data mask" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "imr, imc = bzn.slice.shape\n", "hexside = np.linalg.norm(bzn.pouter_ord[1,:] - bzn.pouter_ord[2,:])\n", "hexdiag = np.linalg.norm(bzn.pouter_ord[1,:] - bzn.pouter_ord[4,:])\n", "imside = min(bzn.slice.shape)\n", "ptop = (imr - hexdiag) / 2\n", "# Calculate the distance of twice of the apothem (apo diameter)\n", "apod = np.abs(np.sqrt(3)*hexside)\n", "pleft = (imc - hexdiag) / 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.maskgen(hexdiag=int(hexdiag), imside=imside, image=None, padded=True,\n", " pad_top=int(ptop), pad_left=int(pleft), ret='all')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.visualize(bzn.mask*bzn.slice, annotated=True, points=dict(pts=bzn.pouter_ord))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.bandcutter(selector=slice(0, None))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Energy band data sliced to the first Brillouin zone now bears the name `bandcuts`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.bandcuts.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4. Save sliced data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.summary();" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.save_data(form='h5', save_addr=r'./wse2_hse_bandcuts.h5')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.imshow(bzn.bandcuts[0,...])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.visualize(bzn.bandcuts[12,...])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load data using external function\n", "Demonstration here using ``fuller.utils.load_multiple_bands()``" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fdir = '../data/theory/bands_1BZ/'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn = fuller.generator.BrillouinZoner(folder=fdir)\n", "bzn.load_data('', loadfunc=fuller.utils.load_multiple_bands, ret=False, ename='bands/Eb', kname='axes')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.select_slice(selector=slice(0, 1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bzn.visualize(bzn.slice, annotated=False)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".pyenv38", "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.12" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
examples/04_mpes_reconstruction_mrf.ipynb
.ipynb
4,360
186
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Reconstruction of band using Markov Random Field Model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Model setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import packages\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "from fuller.mrfRec import MrfRec\n", "from fuller.utils import loadHDF\n", "\n", "import os" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_path = '../' # Put in Path to a storage of at least 20 Gbyte free space.\n", "if not os.path.exists(data_path + \"/data.zip\"):\n", " os.system(f\"curl -L --output {data_path}/data.zip https://zenodo.org/records/7314278/files/data.zip\")\n", "if not os.path.isdir(data_path + \"/data\"):\n", " os.system(f\"unzip -d {data_path} -o {data_path}/data\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load preprocessed data\n", "data = loadHDF('../data/pes/1_sym.h5')\n", "E = data['E']\n", "kx = data['kx']\n", "ky = data['ky']\n", "I = data['V']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create MRF model\n", "mrf = MrfRec(E=E, kx=kx, ky=ky, I=I, eta=.12)\n", "mrf.I_normalized = True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Initialization" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Initialize mrf model with band structure approximation from DFT\n", "path_dft = '../data/theory/WSe2_PBEsol_bands.mat'\n", "\n", "band_index = 4\n", "offset = .5\n", "k_scale = 1.1\n", "\n", "kx_dft, ky_dft, E_dft = mrf.loadBandsMat(path_dft)\n", "mrf.initializeBand(kx=kx_dft, ky=ky_dft, Eb=E_dft[band_index,...], offset=offset, kScale=k_scale, flipKAxes=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot slices with initialiation to check offset and scale\n", "mrf.plotI(ky=0, plotBandInit=True, cmapName='coolwarm')\n", "mrf.plotI(kx=0, plotBandInit=True, cmapName='coolwarm')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reconstruction" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "# Run optimization to perform reconstruction\n", "eta = .1\n", "n_epochs = 150\n", "\n", "mrf.eta = eta\n", "mrf.iter_para(n_epochs)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "# Plot results\n", "mrf.plotBands()\n", "mrf.plotI(ky=0, plotBand=True, plotBandInit=True, plotSliceInBand=False, cmapName='coolwarm')\n", "mrf.plotI(ky=0.5, plotBand=True, plotBandInit=True, plotSliceInBand=False, cmapName='coolwarm')\n", "mrf.plotI(kx=0, plotBand=True, plotBandInit=True, plotSliceInBand=False, cmapName='coolwarm')\n", "mrf.plotI(kx=0.5, plotBand=True, plotBandInit=True, plotSliceInBand=False, cmapName='coolwarm')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Save results\n", "path_save = 'reconstructed_bands'\n", "mrf.saveBand(path_save + 'mrf_rec_%02i.h5' % band_index, index=band_index)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".pyenv38", "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.12" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
examples/interpolation_cutter.ipynb
.ipynb
4,555
203
{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import fuller\n", "import scipy.io as sio\n", "from mpes import fprocessing as fp, analysis as aly\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from imp import reload\n", "reload(aly)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bm = fp.readBinnedhdf5('..\\data\\WSe2_256x256x1024_fullrange_rotsym.h5')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bm['V'].shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "emax, emin = -bm['E'][::-1][0], -bm['E'][::-1][499]\n", "emax, emin" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc = aly.MomentumCorrector(bm['V'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc.selectSlice2D(slice(30, 38), axis=2)\n", "mc.view(mci.slice)\n", "plt.axvline(x=129)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mc.featureExtract(mc.slice, method='daofind', sigma=4, fwhm=7, sigma_radius=2)\n", "mc.view(mc.slice, annotated=True, points=mc.features)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "G = mc.pcent\n", "K = mc.pouter_ord[0,:]\n", "M = mc.pouter_ord[:2,:].mean(axis=0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rpts = np.asarray([G[0], M[0], K[0], G[0]])\n", "cpts = np.asarray([G[1], M[1], K[1], G[1]])\n", "rr, cc, ids = aly.points2path(rpts, cpts, npoints=[40, 32, 50])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "paths = np.concatenate((rr, cc, np.ones((120, 1))), axis=1)\n", "bc = aly.bandpath_map(bm['V'][:,:,:500], pathr=rr, pathc=cc, eaxis=2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(10,8))\n", "plt.imshow(bc, cmap='terrain_r', aspect=10, extent=[0, 119, emin, emax])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from skimage.exposure import equalize_adapthist" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bceq = equalize_adapthist(bc/100, kernel_size=(20, 12), clip_limit=0.015)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f, ax = plt.subplots(figsize=(10,8))\n", "plt.imshow(bceq, cmap='terrain_r', aspect=9, extent=[0, 119, emin, emax])\n", "for j in range(len(ids)):\n", " plt.axvline(ids[j], ls='--', dashes=(5, 5), color='r', lw=2)\n", "# plt.xticks([])\n", "plt.tick_params(labelsize=15)\n", "plt.xlim([ids[0], ids[-1]-1])\n", "plt.ylabel('Binding energy (eV)', fontsize=15)\n", "ax.set_xticks([ 0, 39, 70, 119])\n", "ax.set_xticklabels(['$\\Gamma$', 'M', 'K', '$\\Gamma$']);\n", "# plt.savefig('WSe2_Comparison_ExperimentSym_TheoryLDA_Ramp.pdf', bbox_inches='tight', dpi=300)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dicta = [['data', {'cut':bc, 'cut_clahe':bceq}]]\n", "fuller.utils.saveHDF(*dicta, save_addr=r'.\\WSe2_BZSymLineCut.h5')" ] }, { "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
mpes-kit/fuller
examples/03_preprocessing.ipynb
.ipynb
5,321
242
{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# Illustration of the preprocessing steps" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import packages\n", "import numpy as np\n", "import tensorflow as tf\n", "import matplotlib.pyplot as plt\n", "\n", "from fuller.mrfRec import MrfRec\n", "from fuller.generator import rotosymmetrize\n", "from fuller.utils import saveHDF\n", "\n", "from fuller.utils import loadHDF\n", "\n", "import os" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_path = '../' # Put in Path to a storage of at least 20 Gbyte free space.\n", "if not os.path.exists(data_path + \"/data.zip\"):\n", " os.system(f\"curl -L --output {data_path}/data.zip https://zenodo.org/records/7314278/files/data.zip\")\n", "if not os.path.isdir(data_path + \"/data\"):\n", " os.system(f\"unzip -d {data_path} -o {data_path}/data\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load data\n", "data = loadHDF('../data/pes/0_binned.h5')\n", "I = data['V']\n", "E = data['E']\n", "kx = data['kx']\n", "ky = data['ky']\n", "\n", "# Create reconstruction object from data file\n", "mrf = MrfRec(E=E, kx=kx, ky=ky, I=I)\n", "I_raw = I.copy()\n", "\n", "# Set plot folder\n", "plot_dir = 'plots'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create function for plotting\n", "def plot_slices(mrf, plot_dir, prefix):\n", " # ky sice\n", " mrf.plotI(ky=0., cmapName=\"coolwarm\")\n", " plt.xlim((-1.65, 1.65))\n", " plt.ylim((-8.5, 0.5))\n", " plt.savefig(plot_dir + '/' + prefix + '_ky_slice.png', dpi=300)\n", "\n", " # kx sice\n", " mrf.plotI(kx=0., cmapName=\"coolwarm\")\n", " plt.xlim((-1.65, 1.65))\n", " plt.ylim((-8.5, 0.5))\n", " plt.savefig(plot_dir + '/' + prefix + '_kx_slice.png', dpi=300)\n", "\n", " # ky sice\n", " mrf.plotI(E=-1.2, cmapName=\"coolwarm\", equal_axes=True, figsize=(9, 7.5))\n", " plt.xlim((-1.65, 1.65))\n", " plt.ylim((-1.65, 1.65))\n", " plt.tight_layout()\n", " plt.savefig(plot_dir + '/' + prefix + '_E_slice.png', dpi=300)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Plot raw data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "plot_slices(mrf, plot_dir, 'raw')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Rotational symmetrization" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mrf.symmetrizeI(mirror=False)\n", "plot_slices(mrf, plot_dir, 'sym_rot')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Mirror symetrization" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mrf.symmetrizeI(rotational=False)\n", "plot_slices(mrf, plot_dir, 'sym_mir')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Normalization using clahe" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "mrf.normalizeI(kernel_size=(30, 30, 40), n_bins=256, clip_limit=0.1, use_gpu=True)\n", "plot_slices(mrf, plot_dir, 'clahe')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Smoothing using Gaussian filter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mrf.smoothenI(sigma=(.8, .8, 1.))\n", "plot_slices(mrf, plot_dir, 'smooth')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Save preprocessed dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "data_save = [['axes', {'E': mrf.E, 'kx': mrf.kx, 'ky': mrf.ky}], ['binned', {'V': mrf.I}]]\n", "saveHDF(*data_save, save_addr='./WSe2_preprocessed.h5')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".pyenv38", "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.12" }, "pycharm": { "stem_cell": { "cell_type": "raw", "metadata": { "collapsed": false }, "source": [] } } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
mpes-kit/fuller
docs/conf.py
.py
8,956
276
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import sys import os # import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) sys.path.append(os.path.abspath('../..')) #sys.path.append(os.path.abspath('..')) import fuller import sphinx_theme # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.todo', 'sphinx.ext.githubpages', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # -- Project information ----------------------------------------------------- project = 'fuller' copyright = '2018-2020, Vincent Stimper, R. Patrick Xian' author = 'Vincent Stimper, R. Patrick Xian' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = fuller.__version__ # The full version, including alpha/beta/rc tags. release = fuller.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "stanford_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [sphinx_theme.get_html_theme_path('stanford-theme')] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'fullerdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'fuller.tex', u'fuller Documentation', u'Vincent Stimper, R. Patrick Xian', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'fuller', u'fuller Documentation', [u'Vincent Stimper, R. Patrick Xian'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'fuller', u'fuller Documentation', u'Vincent Stimper, R. Patrick Xian', 'fuller', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None}
Python
3D
Autodesk/molecular-design-toolkit
setup.py
.py
3,184
94
# Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys from os.path import relpath, join from setuptools import find_packages, setup from setuptools.command.install import install import versioneer PACKAGE_NAME = 'moldesign' CLASSIFIERS = """\ Development Status :: 4 - Beta Intended Audience :: Science/Research Intended Audience :: Developers Intended Audience :: Education License :: OSI Approved :: Apache Software License Programming Language :: Python :: 2 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Topic :: Scientific/Engineering :: Chemistry Topic :: Scientific/Engineering :: Physics Operating System :: POSIX Operating System :: Unix Operating System :: MacOS """ HOME = os.path.expanduser('~') CONFIG_DIR = os.path.join(HOME, '.moldesign') PYEXT = set('.py .pyc .pyo'.split()) with open('requirements.txt', 'r') as reqfile: requirements = [x.strip() for x in reqfile if x.strip()] def find_package_data(pkgdir): """ Just include all files that won't be included as package modules. """ files = [] for root, dirnames, filenames in os.walk(pkgdir): not_a_package = '__init__.py' not in filenames for fn in filenames: basename, fext = os.path.splitext(fn) if not_a_package or (fext not in PYEXT) or ('static' in fn): files.append(relpath(join(root, fn), pkgdir)) return files class PostInstall(install): def run(self): install.run(self) self.prompt_intro() def prompt_intro(self): # this doesn't actually display - print statements don't work? print('Thank you for installing the Molecular Design Toolkit!!!') print('For help, documentation, and any questions, visit us at ') print(' http://moldesign.bionano.autodesk.com/') print("\nFor visualization functionality inside python notebooks, please also install") print("the `mdtwidgets` package.") cmdclass = versioneer.get_cmdclass() cmdclass['install'] = PostInstall setup( name=PACKAGE_NAME, version=versioneer.get_version(), classifiers=CLASSIFIERS.splitlines(), packages=find_packages(), package_data={PACKAGE_NAME: find_package_data(PACKAGE_NAME)}, install_requires=requirements, url='http://moldesign.bionano.autodesk.com', cmdclass=cmdclass, license='Apache 2.0', author='Aaron Virshup, Autodesk Life Sciences', author_email='moleculardesigntoolkit@autodesk.com', description='A single, intuitive interface to a huge range of molecular modeling software')
Python
3D
Autodesk/molecular-design-toolkit
versioneer.py
.py
68,587
1,818
# Version: 0.17 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, and pypy * [![Latest Version] (https://pypip.in/version/versioneer/badge.svg?style=flat) ](https://pypi.python.org/pypi/versioneer/) * [![Build Status] (https://travis-ci.org/warner/python-versioneer.png?branch=master) ](https://travis-ci.org/warner/python-versioneer) This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere to your $PATH * add a `[versioneer]` section to your setup.cfg (see below) * run `versioneer install` in your source tree, commit the results ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes. The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See details.md in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/warner/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other langauges) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/warner/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/warner/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ### Unicode version strings While Versioneer works (and is continually tested) with both Python 2 and Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. Newer releases probably generate unicode version strings on py2. It's not clear that this is wrong, but it may be surprising for applications when then write these strings to a network connection or include them in bytes-oriented APIs like cryptographic checksums. [Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates this question. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . """ from __future__ import print_function try: import configparser except ImportError: import ConfigParser as configparser import errno import json import os import re import subprocess import sys class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. me = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(me)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(me), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise EnvironmentError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.SafeConfigParser() with open(setup_cfg, "r") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory def get(parser, name): if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" cfg.versionfile_source = get(parser, "versionfile_source") cfg.versionfile_build = get(parser, "versionfile_build") cfg.tag_prefix = get(parser, "tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = get(parser, "parentdir_prefix") cfg.verbose = get(parser, "verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode LONG_VERSION_PY['git'] = ''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.17 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%%s*" %% tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.17) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ def do_setup(): """Main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1)
Python
3D
Autodesk/molecular-design-toolkit
nb-output-filter.sh
.sh
137
6
#!/bin/bash git config filter.notebooks.clean moldesign/_notebooks/nbscripts/strip_nb_output.py git config filter.notebooks.smudge cat
Shell
3D
Autodesk/molecular-design-toolkit
DEVELOPMENT.md
.md
6,110
113
# DEVELOPING MDT ### Setting up a dev environment (still under construction) ### Install prequisites (first time only) You need to install docker, and an environment manager for Python 3 (Miniconda 3). Here's one way to do that: 1. Install docker: [link] 2. Install pyenv and pyenv-venv: [link] 3. Install miniconda3 by running: `pyenv install miniconda3-latest` 4. Switch to miniconda environment by running: `pyenv shell miniconda3-latest` ### Set up your environment (first time only) 1. Get MDT: `git clone http://github.com/Autodesk/molecular-design-toolkit` 1. `cd molecular-design-toolkit` 1. Create conda environment (optional but recommended) by running: [command to create conda env] 2. Activate the environment: `pyenv activate [environment name???]` 1. Install dev dependencies: `pip install -r requirements.txt DockerMakefiles/requirements.txt deployment/requirements.txt` 2. Set up for local dev mode (this tells MDT to use your local docker containers): ```bash mkdir ~/.moldesign echo "devmode: true" > ~/.moldesign/moldesign.yml ``` 8. Install MDT in "development mode": ``` pip install -e molecular-design-toolkit ``` ### To activate environment (in any new shell) 1. Run `pyenv activate [environment name???]` ### To rebuild docker images (first time and after changes that affect dockerized code) 5. Build development versions of all docker images: ```bash cd DockerMakefiles docker-make --all --tag dev ``` ### To run tests ```bash cd molecular-design-toolkit/moldesign/_tests py.test -n [number of concurrent tests] ``` See [the testing README](moldesign/_tests/README.md) for more details. ### Code style 1. Functions and variables should be `lowercase_with_underscores`. Class names and constructors should be `CapitalizedCamelCase`. 1. The user-exposed API should be clean, [PEP 8](https://www.python.org/dev/peps/pep-0008/) code. 1. Internally, readability and functionality are more important than consistency - that said, [Google's style guide](https://google.github.io/styleguide/pyguide.html), along with [PEP 8](https://www.python.org/dev/peps/pep-0008/), is strongly encouraged. # Contributing ### Who should contribute? Anyone with a molecular modeling workflow that they want to enable or share. Experience and research-level knowledge of the field is an important asset! In contrast, limited programming experience *is definitely not* barrier to contributing - we can help you with that! Please ask for help getting started in our forums [link]. ### Scope: What goes into MDT? Established techniques and general simulation tools that will be useful for **3-dimensional biomolecular modeling**. MDT aims to enable scientists to easily build new simulation techniques and workflows, but new, immature techniques, or those with limited applicability outside of a particular system should be implemented as separate projects that *use* MDT, not *part of* MDT. ###### Could (and should!) be implemented in MDT: * Physical simulation and modelilng: Lambda dynamics; homology modelling; surface hopping; RPMD; metadynamics; markov state models; a library of common 3D structures (such as amino acids, carbon nanotubes, small molecules, etc.) * Visualization and UI: transitions between different views; interactive structure building and editing; ray-traced rendering; movie exports ###### Should implemented as a separate project: * Computational techniques: fluid dynamics solver (not useful at the atomic level), biological network models (no clear connection to 3D structures); machine-learning based quantum chemistry (immature, untested) * Visualization and UI: visualizations for specific systems (not generally applicable); # Development guidelines ### Whenever commiting changes anywhere Make SURE that you've run `nb-output-filter.sh` at the project base. You only need to do this once (per copy of the repository). This will make sure that you don't accidentally commit any `ipynb` output fields into the repository. You can check to make sure the filters are working by running `git diff` on any notebook file that has output in it: all `output` and `metadata` fields should remain blank. ### Maintainers: Accepting a PR Work can be merged into `master` or a feature branch, as appropriate. Don't merge broken code into master, but it doesn't need to be totally production-ready either: only releases (below) are considered "stable". 1. Review the code. 1. Make sure that there's appropriate functional tests. 1. Check that the travis build is at least running all the way to the end. The tests don't *necessarily* need to pass, but you need to undertand why what's passing and what's not. ### Releases 1. Decide on the new version number (see below). For our purposes here, we'll pretend it's `0.9.3`. 1. Tag the relevant commit (the build must be passing) with a release candidate version number, e.g., `0.9.3rc1`. 1. Codeship will automatically deploy the updated release to PyPI and DockerHub 1. Manually test the example notebooks against this pre-release version. 1. If succesful, tag the relevant commit with the official release version `0.9.3` ### Versioning For now, we're using a subset [PEP 440](https://www.python.org/dev/peps/pep-0440/): 1. Every release should be of the form MAJOR.MINOR.PATCH, e.g. `0.1.2` 2. Pre-releases should be numbered consecutively, and may be alpha, beta, or "release candidate", e.g. `1.0.1rc3` or `0.5.3a1` 3. Our deployment infrastructure uses this regular expression to accept version strings: `^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)((a|rc|b)(0|[1-9]\d*))?$` ### Maintainers: updating the documentation Documentation is NOT coupled to the package releases; docs tend to get updated continuously. 1. In the `master` branch, update the version numbers in `docs/conf.py` 1. Run `cd docs; make clean; make html`. 1. In a separate directory, check out a fresh copy of the repo and run `git checkout gh-pages` 1. Copy the contents of `[master branch]/docs/_build/html` into the root of the `gh-pages` branch. 1. Commit your changes to the `gh-pages` branch and push them back to GitHub.
Markdown
3D
Autodesk/molecular-design-toolkit
CONTRIBUTING.md
.md
6,484
119
# Contributing to Molecular Design Toolkit <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)* - [Contributing to Molecular Design Toolkit](#contributing-to-molecular-design-toolkit) - [Tips and guidelines](#tips-and-guidelines) - [What can I contribute?](#what-can-i-contribute) - [Pull requests are always welcome](#pull-requests-are-always-welcome) - [Design and cleanup proposals](#design-and-cleanup-proposals) - [Submission Guidelines](#submission-guidelines) - [Project Roles](#project-roles) - [Timing](#timing) - [Issues](#issues) - [Pull Requests](#pull-requests) <!-- END doctoc generated TOC please keep comment here to allow auto update --> <!-- to generate: npm install doctoc: doctoc --gitlab --maxlevel 3 CONTRIBUTING.md--> ## Tips and guidelines ### What can I contribute? Contributions to this project are encouraged! Email the maintainers at `moldesign_maintainers@autodesk.com` to become a contributor. If you're interested in getting started, here are some general contributions that are always welcome. We also maintain a [wishlist of specific ideas on the wiki](https://github.com/Autodesk/molecular-design-toolkit/wiki/Contribution-ideas). **Tests**: This is one of the easiest ways to get started - see also `moldesign/tests/README.md` * **Contribute unit tests** - test that MDT's functions work correctly in a variety of situations, and that they report errors when appropriate * **Validate methods** - methods need to be tested against known results for accuracy; for instance, we need to check that a Hartree-Fock calculation gives the same results as Gaussian, GAMESS, and MolDesign **Examples**: See also `moldesign/notebooks` * **Best practices** - put together template notebooks that will help users get started with a particular workflow, from modeling proteins from crystal structures to exploring electronic structure * **Interesting use cases** - Contribute a notebook that shows off a cool bit of science or design. **Bug fixes:** Found a typo in the code? Found that a function fails under certain conditions? Know how to fix it? Great! Go for it. Please do [open an issue](https://github.com/autodesk/molecular-design-toolkit/issues) so that we know you're working on it, and submit a pull request when you're ready. **Features:** The chemical modeling universe is vast, and we want toolkit users to have access to a lot of it. Whether you want free energy perturbation, or Boyes' localization, or 3D structural alignment - we want it too! As always, please [open an issue](https://github.com/autodesk/molecular-design-toolkit/issues) so that we know what you're working on. **Whatever:** There's ALWAYS something to do, whether supporting other languages (e.g., Spanish or Bahasa Indonesia, not Fortran or C++); improving 3D viewer performance; improving documentation; adding Python 3.X support; or integrating with other IDE technologies. ### Pull requests are always welcome All PRs should be documented as [GitHub issues](https://github.com/autodesk/molecular-design-toolkit/issues), ideally BEFORE you start working on them. ### Design and cleanup proposals Good API design is at the heart of this project, and you don't need to do any programming to help with this! For example: * You could describe how a user will run a Hamiltonian replica exchange calculation (should it be a class or a function? What are the method names? How does the user specify the temperatures?). * You can also propose redesigns for existing features - maybe you think `mdt.add_hydrogens(mol)` should be renamed to `mol.add_hydrogens()`, or you want to propose a better way to access trajectory data. To get started, as always: [open an issue](https://github.com/autodesk/molecular-design-toolkit/issues). For information on making these types of contributions, see [the development guide](DEVELOPMENT.md). ## Submission Guidelines ### Maintainers Maintainers are responsible for responding to pull requests and issues, as well as guiding the direction of the project. Aaron Virshup - Lead developer and maintainer<br> Dion Amago - Maintainer<br> Malte Tinnus - Maintainer If you've established yourself as an impactful contributor for the project, and are willing take on the extra work, we'd love to have your help maintaining it! Email the maintainers list at `moldesign_maintainers@autodesk.com` for details. ### Timing We will attempt to address all issues and pull requests within one week. It may a bit longer before pull requests are actually merged, as they must be inspected and tested. ### Issues If MDT isn't working like you expect, please open a new issue! We appreciate any effort you can make to avoid reporting duplicate issues, but please err on the side of reporting the bug if you're not sure. Providing the following information will increase the chances of your issue being dealt with quickly: * **Overview of the Issue** - Please describe the issue, and include any relevant exception messages or screenshots. * **Environment** - Include the relevant output of `pip freeze` as well as your system and python version info. * **Help us reproduce the issue** - Please include code that will help us reproduce the issue. For complex situations, attach a notebook file. * **Related Issues** - Please link to other issues in this project (or even other projects) that appear to be related ### Pull Requests Before you submit your pull request consider the following guidelines: * Search GitHub for an open or closed Pull Request that relates to your submission. You don't want to duplicate effort. * Make your changes in a new git branch: ```shell git checkout -b my-fix-branch [working-branch-name] ``` * Create your patch. * Commit your changes using a descriptive commit message. ```shell git commit -a ``` Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files. * Push your branch to GitHub: ```shell git push origin my-fix-branch ``` * In GitHub, send a pull request to `molecular-design-toolkit:dev` * Before any request is merged, you'll need to agree to the contribution boilerplate. Email us at `moldesign_maintainers@autodesk.com` for details.
Markdown
3D
Autodesk/molecular-design-toolkit
DockerMakefiles/buildfiles/notebook/run_notebook.sh
.sh
84
4
#!/bin/bash jupyter notebook --ip=0.0.0.0 --no-browser --port=8888 --allow-root $@
Shell
3D
Autodesk/molecular-design-toolkit
DockerMakefiles/buildfiles/ambertools/runsander.py
.py
7,026
255
#!/usr/bin/env python """ This script drives an NWChem calculation given a generic QM specification """ import json import os import pint ureg = pint.UnitRegistry() ureg.define('bohr = a0 = hbar/(m_e * c * fine_structure_constant') """ &cntrl ntb=1, ! use PBC imin=1, ! run minimization ntmin=5 ! run steepest descent maxcyc=10, ! minimize for 10 steps ncyc=0, ! no switch to congugate gradient cut=8.0, ! MM cutoff ntc=2, ntf=2, ! SHAKE ioutfmt=1 ! netcdf output / """ FILENAME_DEFAULTS = {x+"_file":x for x in "inpcrd mdcrd prmtop mdvel".split()} def run_calculation(parameters): """ Drive the calculation, based on passed parameters Args: parameters (dict): dictionary describing this run (see https://github.com/Autodesk/molecular-design-toolkit/wiki/Generic-parameter-names ) """ for key, val in FILENAME_DEFAULTS: parameters.setdefault(key, val) if parameters.get('num_processors', 1) > 1: cmd = 'mpirun -n %d sander.MPI' % parameters['num_processors'] else: cmd = ('sander -i {inpcrd_file} -o {mdcrd_file} -p {prmtop_file} ' '-v {mdvel_file} ').format(**parameters) os.system(cmd) def write_inputs(parameters): """ Write input files using passed parameters Args: parameters (dict): dictionary describing this run (see https://github.com/Autodesk/molecular-design-toolkit/wiki/Generic-parameter-names ) """ # check that coordinates were passed assert os.path.isfile('input.xyz'), 'Expecting input coordinates at input.xyz' os.mkdir('./perm') inputs = _make_input_files(parameters) for filename, contents in inputs.iteritems(): with open(filename, 'w') as inputfile: inputfile.write(contents) def convert(q, units): """ Convert a javascript quantity description into a floating point number in the desired units Args: q (dict): Quantity to convert (of form ``{value: <float>, units: <str>}`` ) units (str): name of the units Returns: float: value of the quantity in the passed unit system Raises: pint.DimensionalityError: If the units are incompatible with the desired quantity Examples: >>> q = {'value':1.0, 'units':'nm'} >>> convert(q, 'angstrom') 10.0 """ quantity = q['value'] * ureg(q['units']) return quantity.value_in(units) ##### helper routines below ###### def _make_input_files(calc): nwin = [_header(calc), _geom_block(calc), _basisblock(calc), _chargeblock(calc), _theoryblock(calc), _otherblocks(calc), _taskblock(calc)] return {'nw.in': '\n'.join(nwin)} def _header(calc): return '\nstart mol\n\npermanent_dir ./perm\n' def _geom_block(calc): lines = ['geometry units angstrom noautoz noautosym nocenter', ' load format xyz input.xyz', 'end'] return '\n'.join(lines) def _basisblock(calc): return 'basis\n * library %s\nend' % calc['basis'] # TODO: translate names def _theoryblock(calc): lines = [_taskname(calc), _multiplicityline(calc), _theorylines(calc), 'end' ] return '\n'.join(lines) def _otherblocks(calc): lines = [] if calc['runType'] == 'minimization': lines.append('driver\n xyz opt\n print high\n') if 'minimization_steps' in calc: lines.append('maxiter %d' % calc['minimization_steps']) lines.append('end') return '\n'.join(lines) TASKNAMES = {'rhf': 'scf', 'uhf': 'scf', 'rks': 'dft', 'uks': 'dft'} def _taskname(calc): return TASKNAMES[calc['theory']] SCFNAMES = {'rhf': 'rhf', 'uhf': 'uhf', 'rks': 'rhf', 'uks': 'uhf'} def _scfname(calc): return SCFNAMES[calc['theory']] def _taskblock(calc): if calc['runType'] == 'minimization': tasktype = 'optimize' elif 'forces' in calc['properties']: tasktype = 'gradient' else: tasktype = 'energy' return 'task %s %s' % (_taskname(calc), tasktype) STATENAMES = {1: "SINGLET", 2: "DOUBLET", 3: "TRIPLET", 4: "QUARTET", 5: "QUINTET", 6: "SEXTET", 7: "SEPTET", 8: "OCTET"} def _multiplicityline(calc): if calc['theory'] in ('rks', 'uks'): return 'mult %s' % calc.get('multiplicity', 1) else: return STATENAMES[calc.get('multiplicity', 1)] def _constraintblock(calc): """ Constraints / restraints are specified in JSON objects at calc.constraints and calc.restraints. "Constraints" describe a specific degree of freedom and its value. This value is expected to be rigorously conserved by any dynamics or optimization algorithms. A "restraint", in constrast, is a harmonic restoring force applied to a degree of freedom. Restraint forces should be added to the nuclear hamiltonian. A restraint's "value" is the spring's equilibrium position. The list at calc['constraints'] has the form: [{type: <str>, restraint: <bool>, value: {value: <float>, units: <str>} atomIdx0: <int>...} ...] For example, fixes atom constraints have the form: {type: 'atomPosition', restraint: False, atomIdx: <int>} Restraints are described similary, but include a spring constant (of the appropriate units): {type: 'bond', restraint: True, atomIdx1: <int>, atomIdx2: <int>, springConstant: {value: <float>, units: <str>}, value: {value: <float>, units: <str>}} """ clist = calc.get('constraints', None) if clist is None: return lines = ['constraints'] for constraint in clist: if constraint['type'] == 'position': lines.append(' fix atom %d' % constraint['atomIdx']) elif constraint['type'] == 'distance' and constraint['restraint']: k = convert(constraint['springConstant'], 'hartree/(a0*a0)') d0 = convert(constraint('value', 'a0')) lines.append(' spring bond %d %d %20.10f %20.10f' % (constraint['atomIdx1']+1, constraint['atomIdx2']+1, k, d0)) else: raise NotImplementedError('Constraint type %s (as restraint: %b) not implemented' % (constraint['type'], constraint['restraint'])) lines.append('end') return '\n'.join(lines) def _chargeblock(calc): return '\ncharge %s\n' % calc.get('charge', 0) def _theorylines(calc): lines = ['direct'] if _taskname(calc) == 'dft': lines.append('XC %s' % calc['functional']) return '\n'.join(lines) if __name__ == '__main__': with open('params.json','r') as pjson: parameters = json.load(pjson) write_inputs(parameters) run_calculation(parameters)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/parameters.py
.py
9,802
238
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module stores definitions of common parameters for common techniques. These are used to standardize our interfaces to other codes, and automatically generate interactive notebook interfaces to configure various techniques. """ import operator as op import copy from . import units as u from . import utils from .utils import named_dict def isin(a, b): return a in b class WhenParam(object): def __init__(self, parameter, operator, checkval): self.operator = operator self.parameter = parameter self.checkval = checkval def __call__(self, paramset): """ Args: paramset (dict): Returns: bool: True if the parameter is releveant, false otherwise """ #TODO: anything relevant to an irrelevant parameter is also irrelevant return self.operator(paramset[self.parameter], self.checkval) class Parameter(object): """ A generic parameter for a computational method Args: name (str): the arguments name (this is also its key in the method's ``params`` dictionary) short_description (str): A more readable description of about 100 characters type: The type of the param, including units if applicable. This may be a type (``int``, ``str``, etc.); if the quantity has physical units, you may also pass an example of this quantity (e.g., ``1.0 * units.angstrom``) default: the default value, or None if the user is required to set this parameter manually choices (list): A list of allowable values for the parameter help_url (str): URL for detailed help (not currently implemented) relevance (WhenParam): specifies when a given parameter will affect the dynamics Examples: >>> Parameter('timestep', 'Dynamics timestep', type=1.0*u.fs, default=2.0*u.fs) <Parameter "timestep", type: float, units: fs> >>> Parameter('functional', 'DFT XC functional', choices=['b3lyp', 'pbe0'], >>> relevance=WhenParam('theory', op.eq, 'rks')) <Parameter "functional", type: str> """ def __init__(self, name, short_description=None, type=None, default=None, choices=None, help_url=None, relevance=None, help=None): self.name = name self.displayname = utils.if_not_none(short_description, name) self.value = None self.default = default self.choices = utils.if_not_none(choices, []) self.type = type self.help_url = help_url self.help = help if isinstance(type, u.MdtQuantity): type = type.units if isinstance(type, u.MdtUnit): self.type = float self.units = type else: self.units = None self.relevance = relevance def __str__(self): s = '%s "%s", type: %s' % (type(self).__name__, self.name, self.type.__name__) if self.units is not None: s += ', units: %s' % self.units return s def __repr__(self): try: return '<%s>' % self except (KeyError, AttributeError): return '<%s at %x - exception in __repr__>' % (type(self), id(self)) def copy(self): """ Make a copy of this parameter (usually to modify it for a given method) Returns: Parameter: a copy of this parameter type """ return copy.deepcopy(self) mm_model_parameters = named_dict([ Parameter('cutoff', 'Cutoff for nonbonded interactions', default=1.0 * u.nm, type=u.nm, relevance=WhenParam('nonbonded', op.ne, 'nocutoff')), Parameter('nonbonded', 'Nonbonded interaction method', default='cutoff', type=str, choices=['cutoff', 'pme', 'ewald', 'nocutoff']), Parameter('implicit_solvent', 'Implicit solvent method', type=str, choices=['gbsa', 'obc', 'pbsa', None]), Parameter('solute_dielectric', 'Solute dielectric constant', default=1.0, type=float), Parameter('solvent_dielectric', 'Solvent dielectric constant', default=78.5, type=float), Parameter('ewald_error', 'Ewald error tolerance', default=0.0005, type=float), Parameter('periodic', 'Periodicity', default=False, choices=[False, 'box']) ]) QMTHEORIES = ['rhf', 'rks', 'mp2', 'casscf', 'casci', 'fci'] BASISSETS = ['3-21g', '4-31g', '6-31g', '6-31g*', '6-31g**', '6-311g', '6-311g*', '6-311g+', '6-311g*+', 'sto-3g', 'sto-6g', 'minao', 'weigend', 'dz' 'dzp', 'dtz', 'dqz', 'aug-cc-pvdz', 'aug-cc-pvtz', 'aug-cc-pvqz'] FUNCTIONALS = ['b3lyp', 'blyp', 'pbe0', 'x3lyp', 'mpw3lyp5'] # This is a VERY limited set to start with; all hybrid functionals for now # Need to think more about interface and what to offer by default # PySCF xcs are at https://github.com/sunqm/pyscf/blob/master/dft/libxc.py for now qm_model_parameters = named_dict([ Parameter('theory', 'QM theory', choices=QMTHEORIES), Parameter('functional', 'DFT Functional', default='b3lyp', choices=FUNCTIONALS, # TODO: allow separate x and c functionals relevance=WhenParam('theory', isin, 'dft rks ks uks'.split())), Parameter('active_electrons', 'Active electrons', type=int, default=2, relevance=WhenParam('theory', isin, ['casscf', 'mcscf', 'casci'])), Parameter('active_orbitals', 'Active orbitals', type=int, default=2, relevance=WhenParam('theory', isin, ['casscf', 'mcscf', 'casci'])), Parameter('state_average', 'States to average for SCF', type=int, default=1, relevance=WhenParam('theory', isin, ['casscf', 'mcscf'])), Parameter('basis', 'Basis set', choices=BASISSETS), Parameter('wfn_guess', 'Starting guess method', default='huckel', choices=['huckel', 'minao', 'stored']), Parameter('store_orb_guesses', 'Automatically use orbitals for next initial guess', default=True, type=bool), Parameter('multiplicity', 'Spin multiplicity', default=1, type=int), Parameter('symmetry', 'Symmetry detection', default=None, choices=[None, 'Auto', 'Loose']), Parameter('initial_guess', 'Wfn for initial guess', relevance=WhenParam('wfn_guess', op.eq, 'stored')) ]) integrator_parameters = named_dict([ Parameter('timestep', 'Dynamics timestep', default=1.0*u.fs, type=u.default.time), Parameter('frame_interval', 'Time between frames', default=1.0*u.ps, type=u.fs) ]) md_parameters = named_dict([ Parameter('remove_translation', 'Remove global translations', default=True, type=bool), Parameter('constrain_hbonds', 'Constrain covalent hydrogen bonds', default=True, type=bool), Parameter('constrain_water', 'Constrain water geometries', default=True, type=bool), Parameter('remove_rotation', 'Remove global rotations', default=False, type=bool), ]) constant_temp_parameters = named_dict([ Parameter('temperature', 'Thermostat temperature', default=298 * u.kelvin, type=u.default.temperature)]) langevin_parameters = named_dict([ Parameter('collision_rate', 'Thermal collision rate', default=1.0/u.ps, type=1/u.ps) ]) num_cpus = Parameter('num_cpus', 'Number of CPUs (0=unlimited)', default=0, type=int) ground_state_properties = ['potential_energy', 'forces', 'dipole_moment', 'quadrupole_moment', 'octupole_moment', 'mulliken_charges', 'esp_charges', 'orbitals', 'orbital_energies', 'ci_vector', 'hessian', 'am1_bcc_charges'] """If you're just calculating these, then just pass the requested quantities as a list of keywords to the calculate method""" excited_state_properties = ['state_energies', 'state_forces', 'state_ci_vector'] """ When requesting these quantities, requests need to be passed to mol.calculate as a dict with a list of states for each quantity, e.g. >>> mol.calculate(requests={'state_energies':[1,2],'forces':[1,2]}) to get state_energies and forces for states 1 and 2. Adiabatic states are indexed starting at 0, so state 0 is the ground state, 1 is the first excited state, etc. E.g.. state_energies[0] == potential_energy """ multistate_properties = ['transition_dipole', 'nacv', 'oscillator_strength'] """ When requesting these quantities, requests need to be passed to mol.calculate as a dict with a list of *pairs* of states for each quantity, e.g. >>> mol.calculate(requests={'esp_charges':None, 'nacv':[(0,1),(0,2),(1,2)]}) """
Python
3D
Autodesk/molecular-design-toolkit
moldesign/HISTORY.md
.md
6,854
116
## Changelog ### 0.8.0 - September 9, 2017 MDT 0.8 represents a substantial refinement of the core MDT code, offering Python 2/3 support and increased stability and robustness. ##### NEW MODELING FEATURES - Initial **NWChem** integration and pre-compiled docker image ([\#120](https://github.com/autodesk/molecular-design-toolkit/issues/120)) - **ParmEd integration** - assigned forcefield parameters are now stored as ParmEd objects, and MDT `Molecule` objects can be interconverted with ParmEd `Structures` via `mdt.interfaces.parmed_to_mdt` and `mdt.interfaces.mdt_to_parmed` ([\#116](https://github.com/autodesk/molecular-design-toolkit/issues/116)) - **Orbital and basis function** descriptions are now mathematically complete, allowing operations such as gaussian multiplication, overlap calculations, and real-space amplitude evaluation ([\#167](https://github.com/autodesk/molecular-design-toolkit/issues/167)) - Overhauled **forcefield handling** ([\#149](https://github.com/autodesk/molecular-design-toolkit/issues/149)): 1. `mdt.assign_forcefield` has been replaced with flexible `ForceField` objects, which offer `Forcefield.assign` and `Forcefield.create_prepped_molecule` 2. Forcefield parameters are stored in ParmEd objects instead of text files 3. atom- and bond-specific terms can be retrieved through the `Atom.ff` and `Bond.ff` attributes 4. Replaced `mdt.parameterize` with `mdt.create_ff_parameters`, which creates a Forcefield object with parameters for a passed molecule. - Molecular **alignments** using principal moments of inertia and bond-bond alignment - Better **constraint handling**, making it easier to add, remove, and clear geometric constraints - **Drug discovery energy models** - mmff94, mmff94s, and Ghemical - available through the `OpenBabelPotential` model ([\#111](https://github.com/autodesk/molecular-design-toolkit/issues/111)) ##### INFRASTRUCTURE CHANGES - Simultaneous Python 2/3 support ([\#150](https://github.com/autodesk/molecular-design-toolkit/issues/150)) - `moldesign` no longer requires `nbmolviz`, making for a much lighter-weight installation ([\#140](https://github.com/autodesk/molecular-design-toolkit/issues/140)) - Users will be prompted to install the correct version of `nbmolviz` if necessary; that package now automatically installs itself in more cases - MDT can be configured to run external packages locally, if you'd prefer not to use docker - More robust molecular data structures make it harder (albeit still not THAT hard) to create an inconsistent topological state - More automation, runtime checks and notebook UI options to make sure sure that everything is installed correctly - "CCC" demo server removed. To automatically download and run dependencies like OpenBabel and NWChem, docker must be installed locally - Centralized handling of external software interactions via the `moldesign.compute.packages` module ##### BUGS Test coverage has gone from <40% in the last release to 88% in the current one; the test and deploy pipeline is now fully automated; and tests have been added for a variety of corner cases. All this testing exposed a veritable cornucopia of bugs, a panoply of off-by-one-errors, typos, race conditions and more. These have all been fixed, leaving the code on a much more stable footing moving forward. ### 0.7.3 - October 17, 2016 ##### NEW MODELING FEATURES - [\#33](https://github.com/autodesk/molecular-design-toolkit/issues/33) - Add DFT w/ gradients; MP2, CASSCF, CASCI w/out gradients - Constrained minimizations w/ SHAKE and scipy's SLQSP - Transition dipoles and oscillator strengths - GAFF parameterizer for small molecules -- `params = mdt.parameterize(mol)` - AM1-BCC and Gasteiger partial charge calculators: `mdt.calc_am1_bcc_charges` and `mdt.calc_gasteiger_charges` - Add PDB database and biomolecular assembly support for mmCIF files - [\#72](https://github.com/autodesk/molecular-design-toolkit/issues/72) - Add `moldesign.guess_formal_charges` and `moldesign.add_missing_data` - Excited and multi-state property calculations with CAS methods - Rename `build_bdna` to `build_dna_helix` and give access to all NAB helix types ##### OTHER ENHANCEMENTS - [\#78](https://github.com/autodesk/molecular-design-toolkit/issues/78) - `moldesign` now imports much more quickly - Add `GAFF` energy model to automate small molecule parameterization - Change Example 2 to show an absorption spectrum calculation - Add Example 4 on protein MD with a small ligand - Add Example 5: on constrained minimization and enthalpic barriers - Add Tutorial 3: QM data analysis - Show changelog and version check in the `mdt.about()` (aka `mdt.configure`) widget - Change moldesign.tools and moldesign.helpers modules into more rationally organized subpackages - `mdt.set_dihedral` can be called with two atoms in the same way as `mdt.dihedral` - Explicit parameter created to store wavefunction guesses - Better access to density matrix in wavefunction objects - Improved parsing support for PDB and mmCIF files ##### BUGFIXES - [\#61](https://github.com/autodesk/molecular-design-toolkit/issues/61) - fixed a KeyError when parsing PDBs with metal centers or ions - [\#74](https://github.com/autodesk/molecular-design-toolkit/issues/74) - Add function to create PDB files with correct TER records (used for TLeap input) - Better handling of chains with non-standard residues - `mdt.add_hydrogens` no longer creates structures with separated residues - Fix sign of dihedral gradient - Charge quantities now mostly have the correct units ### 0.7.2 - July 26, 2016 ##### NEW MODELING FEATURES - Add trajectory geometry analysis functions (`traj.dihedral`, `traj.angle`, etc.) - Can now calculate angles, dists, and dihedrals by name within a residue (`residue.distance('CA','CG')`) - Calculate dihedral angles using only two atoms defining the central bond (MDT will infer infer the other two in a consistent way) ##### CHANGES - Completed tutorials ##### BUGFIXES - [\#28](https://github.com/autodesk/molecular-design-toolkit/issues/28): Fixed a rounding error and logging problems with OpenMM trajectory snapshots - [\#21](https://github.com/autodesk/molecular-design-toolkit/issues/21): Better bond orders to structures in Amber files, which don't store them - [\#20](https://github.com/autodesk/molecular-design-toolkit/issues/20): Store OpenMM force vector correctly ### 0.7.1 - July 20, 2016 ##### BUGFIXES - [\#4](https://github.com/autodesk/molecular-design-toolkit/issues/4): Use public demo CCC server by default - [\#3](https://github.com/autodesk/molecular-design-toolkit/issues/3): Fix `python -m moldesign intro` #### 0.7.0 - July 15, 2016 - Initial public release
Markdown
3D
Autodesk/molecular-design-toolkit
moldesign/fileio.py
.py
16,197
501
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from past.builtins import basestring from future.utils import PY2 import bz2 import pickle as pkl # TODO: if cpickle fails, retry with regular pickle to get a better traceback import io import functools import gzip import os import moldesign as mdt from . import utils from .interfaces import biopython_interface from .interfaces import openbabel as openbabel_interface from .interfaces.parmed_interface import write_pdb, write_mmcif from .helpers import pdb from .external import pathlib # imported names read_amber = mdt.interfaces.openmm.amber_to_mol from_smiles = mdt.interfaces.openbabel.from_smiles from_inchi = mdt.interfaces.openbabel.from_inchi utils.exports_names('from_smiles', 'read_amber', 'from_inchi') @utils.exports def read(f, format=None): """Read in a molecule from a file, file-like object, or string. Will also depickle a pickled object. Note: Files with ``.bz2`` or ``.gz`` suffixes will be automatically decompressed. Currently does not support files with more than one record - only returns the first record Args: f (str or file-like or pathlib.Path): Either a path to a file, OR a string with the file's contents, OR a file-like object format (str): molecule format (pdb, xyz, sdf, etc.) or pickle format (recognizes p, pkl, or pickle); guessed from filename if not passed Returns: moldesign.Molecule or object: molecule parsed from the file (or python object, for pickle files) Raises: ValueError: if ``f`` isn't recognized as a string, file path, or file-like object """ filename = None closehandle = False streamtype = io.StringIO readmode = 'r' if PY2: f = pathlib._backport_pathlib_fixup(f) try: # Gets a file-like object, depending on exactly what was passed: # it's a path to a file if _ispath(f): path = pathlib.Path(f).expanduser() format, compression, modesuffix = _get_format(path.name, format) fileobj = COMPRESSION[compression](str(path), mode='r' + modesuffix) closehandle = True # it can create a file-like object elif hasattr(f, 'open'): if format in PICKLE_EXTENSIONS: readmode = 'rb' fileobj = f.open(readmode) closehandle = True # it's already file-like elif hasattr(f, 'read'): fileobj = f # It's a string with a file's content elif isinstance(f, basestring): if format is None: raise IOError(('No file named "%s"; ' % f[:50]) + 'please set the `format` argument if you want to parse the string') elif format in PICKLE_EXTENSIONS or isinstance(f, bytes): streamtype = io.BytesIO fileobj = streamtype(f) else: raise ValueError('Parameter to moldesign.read (%s) not ' % str(f) + 'recognized as string, file path, or file-like object') if format in READERS: mol = READERS[format](fileobj) else: # default to openbabel if there's not an explicit reader for this format mol = openbabel_interface.read_stream(fileobj, format) finally: if closehandle: fileobj.close() if filename is not None and mol.name not in (None, 'untitled'): mol.name = filename if isinstance(mol, mdt.Molecule): mdt.helpers.atom_name_check(mol) return mol def _ispath(f): if not f: return False elif isinstance(f, basestring) and _isfile(f): return True elif isinstance(f, pathlib.Path): return True elif PY2 and pathlib._backportpathlib and isinstance(f, pathlib._backportpathlib.Path): return True else: return False def _isfile(f): try: return os.path.isfile(f) except (TypeError, ValueError): return False @utils.exports def write(obj, filename=None, format=None): """ Write a molecule to a file or string. Will also pickle arbitrary python objects. Notes: Files with ``.bz2`` or ``.gz`` suffixes will be automatically compressed. Users will usually call this by way of ``Molecule.write``. Args: obj (moldesign.Molecule or object): the molecule to be written (or python object to be pickled) filename (str or pathlib.Path or file-like): path or buffer to write to (if not passed), string is returned format (str): molecule format (pdb, xyz, sdf, etc.) or a pickle file extension ('pkl' and 'mdt' are both accepted) Returns: str: if filename is none, return the output file as a string (otherwise returns ``None``) """ close_handle = False if hasattr(filename, 'write'): # it's a stream fileobj = filename return_string = False if format is None and getattr(fileobj, 'name', None): format, compression, mode = _get_format(fileobj.name, format) if format is None: raise ValueError("Could not determine format to write - please the 'format' argument") else: if ( format is None and filename is not None and not isinstance(filename, pathlib.Path) and len(str(filename)) < 5 and '.' not in filename): # lets users call mdt.write(obj, 'pdb') and get a string (without needing the "format" keyword path, format = None, filename elif filename is None: path = None elif isinstance(filename, str): path = pathlib.Path(filename).expanduser() else: path = filename filename = str(path) writemode = 'w' format, compression, mode = _get_format(filename, format) if mode == 'b': streamtype = io.BytesIO else: streamtype = io.StringIO # First, create an object to write to (either file handle or file-like buffer) if path: return_string = False fileobj = COMPRESSION[compression](str(path), mode=writemode + mode) close_handle = True else: return_string = True fileobj = streamtype() # Now, write to the object if format in WRITERS: WRITERS[format](obj, fileobj) else: fileobj.write(openbabel_interface.write_string(obj, format)) # Return a string if necessary if return_string: return fileobj.getvalue() elif close_handle: fileobj.close() @utils.exports def write_trajectory(traj, filename=None, format=None, overwrite=True): """ Write trajectory a file (if filename provided) or file-like buffer Args: traj (moldesign.molecules.Trajectory): trajectory to write filename (str): name of file (return a file-like object if not passed) format (str): file format (guessed from filename if None) overwrite (bool): overwrite filename if it exists Returns: StringIO: file-like object (only if filename not passed) """ format, compression, modesuffix = _get_format(filename, format) # If user is requesting a pickle, just dump the whole thing now and return if format.lower() in PICKLE_EXTENSIONS: write(traj, filename=filename, format=format) # for traditional molecular file formats, write the frames one after another else: if filename and (not overwrite) and _isfile(filename): raise IOError('%s exists' % filename) if not filename: fileobj = io.StringIO() else: fileobj = open(filename, 'w' + modesuffix) for frame in traj.frames: fileobj.write(frame.write(format=format)) if filename is None: fileobj.seek(0) return fileobj else: fileobj.close() def read_pdb(f, assign_ccd_bonds=True): """ Read a PDB file and return a molecule. This uses ParmEd's parser to get the molecular structure, with additional functionality to assign Chemical Component Dictionary bonds, detect missing residues, and find biomolecular assembly information. Note: Users won't typically use this routine; instead, they'll use ``moldesign.read``, which will delegate to this routine when appropriate. Args: f (filelike): filelike object giving access to the PDB file (must implement readline+seek) assign_ccd_bonds (bool): Use the PDB Chemical Component Dictionary (CCD) to create bond topology (note that bonds from CONECT records will always be created as well) Returns: moldesign.Molecule: the parsed molecule """ assemblies = pdb.get_pdb_assemblies(f) f.seek(0) mol = mdt.interfaces.parmed_interface.read_pdb(f) mol.properties.bioassemblies = assemblies f.seek(0) mol.metadata.missing_residues = mdt.helpers.get_pdb_missing_residues(f) # Assign bonds from residue templates if assign_ccd_bonds: pdb.assign_biopolymer_bonds(mol) if assemblies: pdb.warn_assemblies(mol, assemblies) return mol def read_mmcif(f): """ Read an mmCIF file and return a molecule. This uses OpenBabel's basic structure parser along with biopython's mmCIF bioassembly parser Note: Users won't typically use this routine; instead, they'll use ``moldesign.read``, which will delegate to this routine when appropriate. Args: f (filelike): file-like object that accesses the mmCIF file (must implement seek) Returns: moldesign.Molecule: the parsed molecular structure """ mol = mdt.interfaces.parmed_interface.read_mmcif(f) f.seek(0) assemblies = biopython_interface.get_mmcif_assemblies(f) if assemblies: pdb.warn_assemblies(mol, assemblies) mol.properties.bioassemblies = assemblies return mol def read_xyz(f): tempmol = openbabel_interface.read_stream(f, 'xyz') for atom in tempmol.atoms: atom.residue = None return mdt.Molecule(tempmol.atoms) def read_smiles_file(f): return _get_mol_from_identifier_file(f, from_smiles) def read_inchi_file(f): return _get_mol_from_identifier_file(f, from_inchi) def read_iupac_file(f): return _get_mol_from_identifier_file(f, from_name) def _get_mol_from_identifier_file(fileobj, mol_constructor): for line in fileobj: if line.strip()[0] == '#': continue else: return mol_constructor(line.strip()) else: raise IOError("Didn't find any chemical identifiers in the passed file.") def write_xyz(mol, fileobj): fileobj.write(u" %d\n%s\n" % (mol.num_atoms, mol.name)) for atom in mol.atoms: x, y, z = atom.position.value_in(mdt.units.angstrom) fileobj.write(u"%s %24.14f %24.14f %24.14f\n" % (atom.element, x, y, z)) @utils.exports def from_pdb(pdbcode, usecif=False): """ Import the given molecular geometry from PDB.org By default, this will use the structure from the PDB-formatted data; however, it will fall back to using the mmCIF data for this pdbcode if the PDB file is not present. See Also: http://pdb101.rcsb.org/learn/guide-to-understanding-pdb-data/introduction Args: pdbcode (str): 4-character PDB code (e.g. 3AID, 1BNA, etc.) usecif (bool): If False (the default), use the PDB-formatted file (default). If True, use the mmCIF-format file from RCSB.org. Returns: moldesign.Molecule: molecule object """ import requests assert len(pdbcode) == 4, "%s is not a valid PDB ID." % pdbcode fileext = 'cif' if usecif else 'pdb' url = 'https://www.rcsb.org/pdb/files/%s.%s' % (pdbcode, fileext) request = requests.get(url) if request.status_code == 404 and not usecif: # if not found, try the cif-format version print('WARNING: %s.pdb not found in rcsb.org database. Trying %s.cif...' % ( pdbcode, pdbcode), end=' ') retval = from_pdb(pdbcode, usecif=True) print('success.') return retval elif request.status_code != 200: raise ValueError('Failed to download %s.%s from rcsb.org: %s %s' % ( pdbcode, fileext, request.status_code, request.reason)) filestring = request.text mol = read(filestring, format=fileext) mol.name = pdbcode mol.metadata.sourceurl = url mol.metadata.structureurl = 'https://www.rcsb.org/pdb/explore.do?structureId=%s' % pdbcode mol.metadata.pdbid = pdbcode if usecif: mol.metadata.sourceformat = 'mmcif' else: mol.metadata.sourceformat = 'pdb' return mol @utils.exports def from_name(name): """Attempt to convert an IUPAC or common name to a molecular geometry. Args: name (str): molecular name (generally IUPAC - some common names are also recognized) Returns: moldesign.Molecule: molecule object """ from moldesign.interfaces.opsin_interface import name_to_smiles # TODO: fallback to http://cactus.nci.nih.gov/chemical/structure smi = name_to_smiles(name) mol = from_smiles(smi, name) return mol def _get_format(filename, format): """ Determine the requested file format and optional compression library Args: filename (str or None): requested filename, if present format (str or None): requested format, if present Returns: (str, str, str): (file format, compression format or ``None`` for no compression) Examples: >>> _get_format('mymol.pdb', None) ('pdb', None) >>> _get_format('smallmol.xyz.bz2', None) ('xyz','bz2') >>> _get_format('mymol.t.gz', 'sdf') ('sdf','gz') """ compressor = None if filename is None and format is None: raise ValueError('No filename or file format specified') elif filename is not None: fname, extn = os.path.splitext(filename) suffix = extn[1:].lower() compressor = None if suffix in COMPRESSION: compressor = suffix suffix = os.path.splitext(fname)[1][1:].lower() if format is None: format = suffix if format in PICKLE_EXTENSIONS: mode = 'b' elif (compressor == 'bz2' and not PY2) or compressor == 'gz': mode = 't' else: mode = '' return format, compressor, mode #################################### # FILE EXTENSION HANDLERS # #################################### # All extensions MUST be lower case READERS = {'pdb': read_pdb, 'cif': read_mmcif, 'mmcif': read_mmcif, 'smi': read_smiles_file, 'smiles': read_smiles_file, 'inchi': read_inchi_file, 'iupac': read_iupac_file, 'xyz': read_xyz} WRITERS = {'pdb': write_pdb, 'mmcif': write_mmcif, 'xyz': write_xyz} if PY2: bzopener = bz2.BZ2File else: bzopener = bz2.open PICKLE_EXTENSIONS = set("p pkl pickle mdt".split()) COMPRESSION = {'gz': gzip.open, 'gzip': gzip.open, 'bz2': bzopener, 'bzip2': bzopener, None: open} for ext in PICKLE_EXTENSIONS: READERS[ext] = pkl.load WRITERS[ext] = functools.partial(pkl.dump, protocol=2)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/__init__.py
.py
2,506
89
# Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function, absolute_import, division import os as _os _NBMOLVIZ_EXPECTED_VERSION = "0.7.0" _building_docs = bool(_os.environ.get('SPHINX_IS_BUILDING_DOCS', "")) from . import data PACKAGEPATH = data.PACKAGEPATH # Base subpackages - import these first from . import utils from . import units # Functional subpackages from . import compute from . import fileio from . import exceptions from . import external from . import forcefields from . import geom from . import helpers from . import integrators from . import interfaces from . import parameters from . import mathutils from . import min from . import models from . import method from . import orbitals from . import molecules from . import tools from . import widgets from .widgets import configure, about # Populate the top-level namespace (imports everything from each <submodule>.__all__ variable) from .exceptions import * from .fileio import * from .forcefields import * from .geom import * from .min import * from .orbitals import * from .molecules import * from .tools import * # Initialize confiugration compute.init_config() # package metadata from . import _version __version__ = _version.get_versions()['version'] __copyright__ = "Copyright 2017 Autodesk Inc." __license__ = "Apache 2.0" # Set warnings appropriately # TODO: don't clobber user's settings!!! import numpy as _np import warnings as _warnings _np.seterr(all='raise') _warnings.simplefilter('error', _np.ComplexWarning) # We keep a list of weak of references to every RPC job that's run import weakref as _weakref _lastjobs = _weakref.WeakValueDictionary() _njobs = 0 # For documentation purposes only - make sphinx document the toplevel namespace if _building_docs: __all__ = fileio.__all__ + \ geom.__all__ + \ min.__all__ + \ orbitals.__all__ + \ molecules.__all__ + \ tools.__all__
Python
3D
Autodesk/molecular-design-toolkit
moldesign/widgets.py
.py
2,933
90
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import functools from .utils import exports, exports_names from . import _NBMOLVIZ_EXPECTED_VERSION __all__ = 'BondSelector GeometryBuilder ResidueSelector Symmetrizer AtomSelector'.split() INSTALL_CMD = """Install `nbmolviz` by running these commands at the terminal: $ pip install "nbmolviz==%s" $ python -m nbmolviz activate Afterwards, restart python and reload any running notebooks."""%_NBMOLVIZ_EXPECTED_VERSION _warnings = [] try: import nbmolviz.widget_utils from nbmolviz import __version__ as nbv_version except ImportError: nbmolviz_enabled = False nbmolviz_installed = False else: nbmolviz_installed = True nbmolviz_enabled = nbmolviz.widget_utils.can_use_widgets() def notebook_only_method(*args, **kwargs): assert not nbmolviz_enabled if nbmolviz_installed: raise ImportError("This function is only available in a Jupyter notebook!") else: raise ImportError( "The `nbmolviz` library must be installed to use this function!\n" + INSTALL_CMD) if nbmolviz_enabled: # TODO: Make these into lazy imports from nbmolviz.widgets import (BondSelector, GeometryBuilder, ResidueSelector, Symmetrizer, AtomSelector) from nbmolviz.mdtconfig.compute import configure about = configure nbmolviz.widget_utils.print_extension_warnings(stream=sys.stderr) else: BondSelector = GeometryBuilder = ResidueSelector = AtomSelector = Symmetrizer = configure \ = about = notebook_only_method def _get_nbmethod(name): # don't import nbmolviz methods until a method is actually called from nbmolviz import methods as nbmethods module = nbmethods for item in name.split('.'): module = getattr(module, item) return module @exports class WidgetMethod(object): def __init__(self, name): self.name = name self.method = None def __get__(self, instance, owner): if not nbmolviz_enabled: return notebook_only_method elif self.method is None: self.method = _get_nbmethod(self.name) return functools.partial(self.method, instance)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/exceptions.py
.py
1,736
57
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class NotSupportedError(Exception): """ Raised when a given method can't support the requested calculation """ class ConvergenceFailure(Exception): """ Raised when an iterative calculation fails to converge """ pass class NotCalculatedError(Exception): """ Raised when a molecular property is requested that hasn't been calculated """ pass class UnhandledValenceError(Exception): def __init__(self, atom): self.message = 'Atom %s has unhandled valence: %d' % (atom, atom.valence) class QMConvergenceError(Exception): """ Raised when an iterative QM calculation (typically SCF) fails to converge """ pass class DockerError(Exception): pass class ForcefieldAssignmentError(Exception): """ Class that define displays for common errors in assigning a forcefield """ def __init__(self, msg, errors, mol=None, job=None): self.args = [msg] self.errors = errors self.mol = mol self.job = job
Python
3D
Autodesk/molecular-design-toolkit
moldesign/_version.py
.py
18,450
521
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.17 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versionfile_source = "moldesign/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None}
Python
3D
Autodesk/molecular-design-toolkit
moldesign/__main__.py
.py
10,065
303
""" This file collects the various command line tasks accessed via ``python -m moldesign [command]`` The functions here are intended help users set up their environment. Note that MDT routines will NOT be importable from this module when it runs as a script -- you won't be working with molecules or atoms in this module. """ from __future__ import print_function, absolute_import, division import atexit from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from future.utils import PY2 import argparse import distutils.spawn import errno import os import random import shutil import socket import subprocess import sys import time import yaml URL_OPENERS = ['Open', 'xdg-open', 'sensible-browser', 'gnome-open', 'x-www-browser'] JUPYTERPORT = 8888 DOCKER_TOOLS = 'docker docker-machine docker-compose'.split() DOCKER_REPOSITORY = 'docker-hub.autodesk.com/virshua/moldesign:' HOME = os.path.expanduser('~') CONFIG_DIR = os.path.join(HOME, '.moldesign') EXAMPLE_DIR_TARGET = os.path.join(os.path.curdir, 'moldesign-examples') MOLDESIGN_SRC = os.path.abspath(os.path.dirname(__file__)) EXAMPLE_DIR_SRC = unit_def_file = os.path.join(MOLDESIGN_SRC, '_notebooks') MDTVERSION = subprocess.check_output(['python', '-c', "import _version; print(_version.get_versions()['version'])"], cwd=MOLDESIGN_SRC).splitlines()[-1].decode('ascii') VERFILEPATH = os.path.join(EXAMPLE_DIR_TARGET, '.mdtversion') CONFIG_PATH = os.path.join(CONFIG_DIR, 'moldesign.yml') NO_NBMOLVIZ_ERR = 10 JUPYTER_ERR = 128 NO_EXAMPLE_OVERWRITE_ERR = 200 OUTDATED_EXAMPLES_ERR = 201 def main(): print('Molecular Design Toolkit v%s Launcher' % MDTVERSION) global CONFIG_PATH parser = argparse.ArgumentParser('python -m moldesign') subparsers = parser.add_subparsers(title='command', dest='command') subparsers.add_parser('intro', help='copy examples into current directory and launch a ' 'notebook') subparsers.add_parser('launch', help='launch a notebook and open it in a browser ' '(equivalent to running "jupyter notebook")') subparsers.add_parser('pull', help='download docker containers that MDT requires (' 'only when a docker client is configured)') subparsers.add_parser('config', help='print configuration and exit') subparsers.add_parser('copyexamples', help='Copy example notebooks') subparsers.add_parser('version', help='Write version string and exit') subparsers.add_parser('dumpenv', help="Dump environment for bug reports") parser.add_argument('-f', '--config-file', type=str, help='Path to config file') args = parser.parse_args() if args.config_file: CONFIG_PATH = args.config_file if args.command == 'intro': nbmolviz_check() copy_example_dir(use_existing=True) launch(cwd=EXAMPLE_DIR_TARGET, path='notebooks/Getting%20Started.ipynb') elif args.command == 'launch': nbmolviz_check() launch() elif args.command == 'copyexamples': copy_example_dir(use_existing=False) elif args.command == 'version': print(MDTVERSION) elif args.command == 'dumpenv': import moldesign as mdt mdt.data.print_environment() elif args.command == 'pull': pull_images() elif args.command == 'config': print('Reading config file from: %s' % CONFIG_PATH) print('----------------------------') with open(CONFIG_PATH, 'r') as cfgfile: for key, value in yaml.load(cfgfile).items(): print('%s: %s' % (key, value)) else: raise ValueError("Unhandled CLI command '%s'" % args.command) def pull_images(): from .compute import packages imgs = [x.get_docker_image_path() for x in packages.packages + packages.executables] print('\nPulling images:', ', '.join(imgs)) for i, img in enumerate(imgs): print('\n------------- Pulling image %s/%s : %s' % (i+1, len(imgs), img)) subprocess.check_call(['docker', 'pull', img]) print('------------- Done with %s' % img) def nbmolviz_check(): # Checks for the existence of nbmolviz before attempting to launch a notebook from . import widgets if not widgets.nbmolviz_installed: print('ERROR: nbmolviz not found - notebooks not available. Install it by running\n' ' $ pip install nbmolviz`') sys.exit(NO_NBMOLVIZ_ERR) def launch(cwd=None, path=''): server, portnum = launch_jupyter_server(cwd=cwd) wait_net_service('localhost', portnum, server) open_browser('http://localhost:%d/%s' % (portnum, path)) server.wait() def copy_example_dir(use_existing=False): print('Copying MDT examples to `%s` ...' % EXAMPLE_DIR_TARGET) if os.path.exists(EXAMPLE_DIR_TARGET): check_existing_examples(use_existing) else: shutil.copytree(EXAMPLE_DIR_SRC, EXAMPLE_DIR_TARGET) with open(VERFILEPATH, 'w') as verfile: print(MDTVERSION, file=verfile) print('Done.') def check_existing_examples(use_existing): if os.path.exists(VERFILEPATH): with open(VERFILEPATH, 'r') as vfile: version = vfile.read().strip() else: version = 'pre-0.7.4' if version != MDTVERSION: print('WARNING - your example directory is out of date! It corresponds to MDT version ' '%s, but you are using version %s'%(version, MDTVERSION)) print('To update your examples, please rename or remove "%s"' % EXAMPLE_DIR_TARGET) sys.exit(OUTDATED_EXAMPLES_ERR) if use_existing: return else: print('\n'.join( ['FAILED: directory already exists. Please:' ' 1) Rename or remove the existing directory at %s,'%EXAMPLE_DIR_TARGET, ' 2) Run this command in a different location, or' ' 3) Run `python -m moldesign intro` to launch the example gallery.'])) sys.exit(NO_EXAMPLE_OVERWRITE_ERR) def launch_jupyter_server(cwd=None): # pragma: no cover for i in range(8888, 9999): if localhost_port_available(i): portnum = i break else: print('WARNING: no available port found between 8888 and 9999. Will try a random port ... ') portnum = random.randint(10001, 65535) server = subprocess.Popen(('jupyter notebook --no-browser --port %d' % portnum).split(), cwd=cwd) atexit.register(server_shutdown, server) return server, portnum def server_shutdown(server): # pragma: no cover print('Shutting down jupyter server...') server.terminate() server.wait() print('Jupyter terminated.') def open_browser(url): # pragma: no cover for exe in URL_OPENERS: if distutils.spawn.find_executable(exe) is not None: try: subprocess.check_call([exe, url]) except subprocess.CalledProcessError: continue else: return print('Point your browser to %s to get started.' % url) # fallback def localhost_port_available(portnum): # pragma: no cover s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.2) try: s.connect(("localhost", portnum)) except socket.error as err: if err.errno == errno.ECONNREFUSED: return True else: raise else: return False def yaml_dumper(*args): return yaml.dump(*args, default_flow_style=False) def wait_net_service(server, port, process, timeout=None): # pragma: no cover """ Wait for network service to appear FROM http://code.activestate.com/recipes/576655-wait-for-network-service-to-appear/ @param timeout: in seconds, if None or 0 wait forever @return: True of False, if timeout is None may return only True or throw unhandled network exception """ import socket import errno if timeout: from time import time as now # time module is needed to calc timeout shared between two exceptions end = now() + timeout while True: if process.poll() is not None: print('ERROR: Jupyter process exited prematurely') sys.exit(JUPYTER_ERR) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: if timeout: next_timeout = end - now() if next_timeout < 0: return False else: s.settimeout(next_timeout) s.connect((server, port)) except socket.timeout as err: print('x') # this exception occurs only if timeout is set if timeout: return False except socket.error as err: if type(err.args) != tuple or err.errno not in (errno.ETIMEDOUT, errno.ECONNREFUSED): raise else: s.close() return True print('.', end=' ') sys.stdout.flush() time.sleep(0.1) def check_path(exes): return {c: distutils.spawn.find_executable(c) for c in exes} is_mac = (check_path(['osascript'])['osascript'] is not None) if __name__ == '__main__': main()
Python
3D
Autodesk/molecular-design-toolkit
moldesign/method.py
.py
4,182
135
""" This module contains abstract base classes for potential models, integrators, and various associated data types (force fields, orbitals, basis sets, etc.). """ from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from future.utils import with_metaclass import funcsigs import moldesign as mdt from .widgets import WidgetMethod from . import utils class _InitKeywordMeta(type): """ Constructs a custom call signature for __init__ based on cls.PARAMETERS. """ @property def __signature__(self): if hasattr(self, '__customsig'): return self.__customsig kwargs = [] for param in self.PARAMETERS: kwargs.append(funcsigs.Parameter(param.name, default=param.default, kind=funcsigs.Parameter.POSITIONAL_OR_KEYWORD)) self.__customsig = funcsigs.Signature(kwargs, __validate_parameters__=True) return self.__customsig class Method(with_metaclass(_InitKeywordMeta, object)): """Abstract Base class for energy models, integrators, and "heavy duty" simulation objects Args: **kwargs (dict): list of parameters for the method. Attributes: mol (mdt.Molecule): the molecule this method is associated with """ PARAMETERS = [] """ list: list of Parameters that can be used to configure this method """ PARAM_SUPPORT = {} """ Mapping(str, list): List of supported values for parameters (if a parameter is not found, it's assumed that all possible values are supported) """ configure = WidgetMethod('method.configure') def __reduce__(self): return _make_method, (self.__class__, self.params, self.mol) def __init__(self, **params): """ :param params: :return: """ # TODO: better documentation for the expected keywords self._prepped = False self.status = None self.mol = None self.params = utils.DotDict(params) # Set default parameter values for param in self.PARAMETERS: if param.name not in self.params: self.params[param.name] = param.default @classmethod def supports_parameter(cls, paramname): for parameter in cls.PARAMETERS: if parameter.name == paramname: return True else: return False def __eq__(self, other): return self.__class__ is other.__class__ and self.params == other.params @classmethod def get_parameters(cls): """ This doesn't do anything right now except provide guidelines for programmers """ return cls.PARAMETERS def get_forcefield(self): raise NotImplementedError() @classmethod def print_parameters(cls): params = cls.PARAMETERS lines = [] for obj in params: description = '' if obj.choices: description = '%s' % obj.choices if obj.types: description += ' or ' if obj.types: description += 'Type %s' % obj.types doc = '%s: %s (DEFAULT: %s)' % (obj.name, description, obj.default) lines.append(doc) return '\n'.join(lines) def _make_method(cls, params, mol): """ Helper for serialization - allows __reduce__ to use kwargs """ obj = cls(**params) obj.mol = mol return obj
Python
3D
Autodesk/molecular-design-toolkit
moldesign/helpers/qmmm.py
.py
3,277
93
# Copyright 2016 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import moldesign as mdt LINKBONDRATIO = 0.709 # fixed ratio of C-C to C-H bond length for link atoms def create_link_atoms(mol, qmatoms): """ Create hydrogen caps for bonds between QM and MM regions. Each link atom will have ``metadata.mmatom``, ``metadata.mmpartner`` attributes to identify the atom it replaces and the atom it's bonded to in the MM system. Raises: ValueError: if any MM/QM atom is bonded to more than one QM/MM atom, or the bond order is not one Returns: List[mdt.Atom]: list of link atoms """ linkatoms = [] qmset = set(qmatoms) for qmatom in qmatoms: mmatom = _get_mm_nbr(mol, qmatom, qmset) if mmatom is None: continue la = mdt.Atom(atnum=1, name='HL%d' % len(linkatoms), metadata={'mmatom': mmatom, 'mmpartner': qmatom}) linkatoms.append(la) set_link_atom_positions(linkatoms) return linkatoms def _get_mm_nbr(mol, qmatom, qmset): mm_nbrs = [nbr for nbr in qmatom.bonded_atoms if nbr not in qmset] if len(mm_nbrs) == 0: return None # everything below is sanity checks mmatom = mm_nbrs[0] if len(mm_nbrs) != 1: raise ValueError('QM atom %s is bonded to more than one MM atom' % qmatom) if mol.bond_graph[qmatom][mmatom] != 1: raise ValueError('Bond crossing QM/MM boundary (%s - %s) does not have order 1' % (qmatom, mmatom)) if qmatom.atnum != 6 or mmatom.atnum != 6: print ('WARNING: QM/MM bond involving non-carbon atoms: %s - %s' % (qmatom, mmatom)) mm_qm_nbrs = [qmnbr for qmnbr in mmatom.bonded_atoms if qmnbr in qmset] if len(mm_qm_nbrs) != 1: raise ValueError('MM atom %s is bonded to more than one QM atom'%mmatom) return mmatom def set_link_atom_positions(linkatoms): """ Set link atom positions using a fixed ratio of MM bond length to QM bond length Warnings: - This is only valid for - Presumably, the most "correct" way to do this is to place the hydrogen in order to match the force exterted on the QM atom by the MM atom. This is not currently supported. Args: linkatoms (List[mdt.Atom]): list of link atoms to set positions for References: http://www.nwchem-sw.org/index.php/Qmmm_link_atoms """ for atom in linkatoms: nbr = atom.metadata.mmpartner proxy = atom.metadata.mmatom dist = LINKBONDRATIO * nbr.distance(proxy) atom.position = (nbr.position + dist * mdt.mathutils.normalized(proxy.position - nbr.position))
Python
3D
Autodesk/molecular-design-toolkit
moldesign/helpers/__init__.py
.py
82
5
from .helpers import * from .pdb import * from .qmmm import * from .logs import *
Python
3D
Autodesk/molecular-design-toolkit
moldesign/helpers/helpers.py
.py
4,375
133
""" This module contains various helper functions used by MDT internally. """ from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections def get_all_atoms(*objects): """ Given Atoms, AtomContainers, lists of Atoms, and lists of AtomContainers, return a flat list of all atoms contained therein. A given atom is only returned once, even if it's found more than once. Args: *objects (moldesign.Atom OR moldesign.AtomContainer OR List[moldesign.Atom] OR List[moldesign.AtomContainer]): objects to take atoms from """ from moldesign import molecules atoms = collections.OrderedDict() for obj in objects: if isinstance(obj, molecules.Atom): atoms[obj] = None elif hasattr(obj, 'atoms'): atoms.update((x,None) for x in obj.atoms) else: for item in obj: if isinstance(item, molecules.Atom): atoms[item] = None elif hasattr(item, 'atoms'): atoms.update((x, None) for x in item.atoms) return molecules.AtomList(iter(atoms.keys())) def kinetic_energy(momenta, masses): """ Returns kinetic energy This is just a helper for the KE formula, because the formula is used frequently but not particularly recognizable or easy to read Args: momenta (Matrix[momentum, shape=(*,3)]): atomic momenta dim_masses (Vector[mass]): atomic masses Returns: Scalar[energy]: kinetic energy of these atoms """ return 0.5 * (momenta*momenta/masses[:,None]).sum() def kinetic_temperature(ke, dof): from moldesign.units import k_b t = (2.0*ke)/(k_b*dof) return t.defunits() def atom_name_check(mol, force=False): """ Makes sure atom names are unique in each residue. If atoms names aren't unqiue: - if the names are just the names of the elements, rename them - else print a warning """ badres = [] for residue in mol.residues: names = set(atom.name for atom in residue.atoms) if len(names) != residue.num_atoms: # atom names aren't unique, check if we can change them for atom in residue.atoms: if atom.name.lower() != atom.symbol.lower(): badres.append(residue) if not force: break else: # rename the atoms atomnums = {} for atom in residue.atoms: atom.name = atom.symbol + str(atomnums.setdefault(atom.symbol, 0)) atomnums[atom.symbol] += 1 if badres: print('WARNING: residues do not have uniquely named atoms: %s' % badres) def restore_topology(mol, topo): """ Restores chain IDs and residue indices (these are stripped by some methods) Args: mol (mdt.Molecule): molecule to restore topology to topo (mdt.Molecule): reference topology Returns: mdt.Molecule: a copy of ``mol`` with a restored topology """ import moldesign as mdt assert mol.num_residues == topo.num_residues assert mol.num_chains == 1 chain_map = {} for chain in topo.chains: chain_map[chain] = mdt.Chain(name=chain.name) for res, refres in zip(mol.residues, topo.residues): if refres.resname != res.resname: print(('INFO: Residue #{res.index} residue code changed from "{refres.resname}"' ' to "{res.resname}".').format(res=res, refres=refres)) res.pdbindex = refres.pdbindex res.name = refres.name res.chain = chain_map[refres.chain] return mdt.Molecule(mol.atoms)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/helpers/pdb.py
.py
10,837
323
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PDB file parsing utilities We don't yet (and hopefully will never need) an internal PDB parser or writer. For now, routines in this module read and write data that's not necessarily parsed by other implementations. """ from past.builtins import basestring import collections from io import StringIO import numpy as np import moldesign as mdt BioAssembly = collections.namedtuple('BioAssembly', 'desc chains transforms') def get_conect_pairs(mol): """ Returns a dicitonary of HETATM bonds for a PDB CONECT record Note that this doesn't return the text records themselves, because they need to reference a specific PDB sequence number """ conects = collections.OrderedDict() for residue in mol.residues: # intra-residue bonds if not residue.is_standard_residue: for bond in residue.bonds: if bond.order <= 1: order = 1 else: order = bond.order for i in range(order): conects.setdefault(bond.a1, []).append(bond.a2) # inter-residue bonds try: r2 = residue.next_residue except (StopIteration, KeyError, NotImplementedError): continue if not (residue.is_standard_residue and r2.is_standard_residue): for bond in residue.bonds_to(r2): conects.setdefault(bond.a1, []).append(bond.a2) return conects def warn_assemblies(mol, assemblies): """ Print a warning message if the PDB structure contains a biomolecular assembly """ # Don't warn if the only assembly is the asymmetric unit if len(assemblies) > 1 or len(list(assemblies.values())[0].transforms) > 1: print("WARNING: This PDB file contains the following biomolecular assemblies:") for name, asm in assemblies.items(): print('WARNING: Assembly "%s": %d copies of chains %s'%( name, len(asm.transforms), ', '.join(asm.chains))) print('WARNING: Use ``mdt.build_assembly([molecule],[assembly_name])``' \ ' to build one of the above assemblies') class MissingResidue(object): type = 'protein' missing = True def __init__(self, chain, resname, pdbindex): self.chain = chain self.resname = resname self.pdbindex = pdbindex @property def code(self): """str: one-letter amino acid code or two letter nucleic acid code, or '?' otherwise""" return mdt.data.RESIDUE_ONE_LETTER.get(self.resname, '?') def get_pdb_missing_residues(fileobj): """ Parses missing residues from a PDB file. Args: fileobj (filelike): file-like access to the PDB file Returns: dict: listing of the missing residues of the form ``{[chain_id]:{[residue_number]:[residue_name], ...}, ...}`` Examples: >>> with open('2jaj.pdb') as pdbfile: >>> res = get_pdb_missing_residues(pdbfile) >>> res 'A': {-4: 'GLY', -3: 'PRO', [...] 284: 'SER'}, 'B': {34: 'GLY', 35: 'GLU', [...] """ lineiter = iter(fileobj) while True: try: fields = next(lineiter).split() except StopIteration: missing = {} # no missing residues found in file break if fields == ['REMARK', '465', 'M', 'RES', 'C', 'SSSEQI']: missing = _parse_missing_xtal(fileobj) break elif fields[:3] == ['REMARK', '465', 'MODELS']: missing = _parse_missing_nmr(fileobj) break summary = {} for m in missing: summary.setdefault(m.chain, {})[m.pdbindex] = m.resname return summary def _parse_missing_xtal(fileobj): missing = [] while True: fields = next(fileobj).split() if fields[:2] != ['REMARK', '465']: break if len(fields) == 6: has_modelnum = 1 if fields[2] != 1: # only process the first model continue else: has_modelnum = 0 missing.append(MissingResidue(chain=fields[3+has_modelnum], resname=fields[2+has_modelnum], pdbindex=int(fields[4+has_modelnum]))) return missing def _parse_missing_nmr(fileobj): header = next(fileobj).split() assert header == ['REMARK', '465', 'RES', 'C', 'SSSEQI'] missing = [] while True: fields = next(fileobj).split() if fields[:2] != ['REMARK', '465']: break missing.append(MissingResidue(chain=fields[3], resname=fields[2], pdbindex=int(fields[4]))) return missing def get_pdb_assemblies(fileobj): """Parse a PDB file, return biomolecular assembly specifications Args: fileobj (file-like): File-like object for the PDB file (this object will be rewound before returning) Returns: Mapping[str, BioAssembly]: dict mapping assembly ids to BioAssembly instances """ assemblies = {} lineiter = iter(fileobj) while True: # first, search for assembly transformations line = next(lineiter) fields = line.split() # Conditions that indicate we're past the "REMARK 350" section if fields[0] in ('ATOM', 'HETATM', 'CONECT'): break if fields[0] == 'REMARK' and int(fields[1]) > 350: break # look for start of a assembly transformation, i.e. "REMARK 350 BIOMOLECULE: [name] " if fields[:3] == 'REMARK 350 BIOMOLECULE:'.split(): assembly_name = fields[-1] assemblies[assembly_name] = _read_pdb_assembly(lineiter) return assemblies def _read_pdb_assembly(lineiter): """Helper for get_pdb_assemblies """ # First, there's description lines: "REMARK 350 AUTHOR DETERMINED BIOLOGICAL UNIT: OCTAMERIC" description_lines = [] line = next(lineiter) fields = line.split() while fields[:7] != 'REMARK 350 APPLY THE FOLLOWING TO CHAINS:'.split(): description_lines.append(line[len('REMARK 350 '):]) line = next(lineiter) fields = line.split() description = (''.join(description_lines)).strip() # Next, we get the chains in this assembly: "REMARK 350 APPLY THE FOLLOWING TO CHAINS: C, D" assert fields[:7] == 'REMARK 350 APPLY THE FOLLOWING TO CHAINS:'.split() chain_names = [x.rstrip(',') for x in fields[7:]] while fields[-1][-1] == ',': # deal with multi-line lists of chains line = next(lineiter) fields = line.split() assert fields[2:4] == ['AND', 'CHAINS:'] chain_names.extend(x.rstrip(',') for x in fields[4:]) transforms = [] while True: # loop over each assembly transformation # example: "REMARK 350 BIOMT1 1 1.000000 0.000000 0.000000 0.00000 " t = np.zeros((4, 4)) t[3, 3] = 1.0 for idim in range(3): line = next(lineiter) fields = line.split() if idim == 0 and len(fields) == 2: return BioAssembly(description, chain_names, transforms) assert int(fields[3]) == len(transforms)+1 assert fields[2] == ('BIOMT%d' % (idim+1)) t[idim, :] = list(map(float, fields[4:8])) transforms.append(t) def assign_biopolymer_bonds(mol): """ Assign bonds to all standard residues using the PDB chemical component dictionary Any unrecognized residues are ignored. References: http://www.wwpdb.org/data/ccd """ for chain in mol.chains: try: chain.assign_biopolymer_bonds() except KeyError: print(('WARNING: failed to assign backbone bonds for %s') % str(chain)) for residue in mol.residues: try: residue.assign_template_bonds() except KeyError: if residue.type not in ('ion', 'water'): print(('WARNING: failed to assign bonds for %s; use ' '``residue.assign_distance.bonds`` to guess the topology') % str(residue)) def assign_unique_hydrogen_names(mol): """ Assign unique names to all hydrogens, based on either: 1) information in the Chemical Component Database, or 2) newly generated, unique names Args: mol (moldesign.Molecule): """ for residue in mol.residues: if residue.resname in mdt.data.RESIDUE_BONDS: _assign_hydrogen_names_from_ccd(residue) else: _assign_unique_hydrogen_names_in_order(residue) residue.rebuild() def _assign_hydrogen_names_from_ccd(residue): ccd_bonds = mdt.data.RESIDUE_BONDS[residue.resname] taken = set(atom.name for atom in residue.atoms) if 'H' not in taken: return # nothing to do if 'H' in ccd_bonds: taken.remove('H') # someone will actually need to be named "H' for atom in residue: if atom.atnum != 1 or atom.name != 'H': continue assert atom.num_bonds == 1, 'Hydrogen has more than one bond' bond = atom.bonds[0] other = bond.partner(atom).name for partner in ccd_bonds[other]: if partner[0] == 'H' and partner not in taken: assert ccd_bonds[other][partner] == 1, 'Hydrogen bond order is not 1' atom.name = partner taken.add(partner) break def _assign_unique_hydrogen_names_in_order(residue): n_hydrogen = 1 namecounts = collections.Counter(x.name for x in residue.atoms) if namecounts.get('H', 0) > 1: used_names = set(atom.name for atom in residue.atoms) for atom in residue.atoms: if atom.name == 'H': name = 'H%d' % n_hydrogen while name in used_names: n_hydrogen += 1 name = 'H%d' % n_hydrogen atom.name = name used_names.add(name)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/helpers/logs.py
.py
3,405
93
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..utils import exports_names, exports from ..widgets import nbmolviz_enabled from .. import units as u if nbmolviz_enabled: from nbmolviz.uielements import Logger, display_log exports_names('Logger', 'display_log') else: @exports class Logger(object): def __init__(self, title='log', **kwargs): kwargs.setdefault('width', '75%') kwargs.setdefault('height', '300px') kwargs.setdefault('font_family', 'monospace') self.title = title self._is_widget = False self.active = False self.disabled = True # so user can't overwrite def _write(self, string): print(string.strip()) # temporary so that we can use this like a logging module later error = warning = info = handled = debug = status = _write @exports def display_log(obj, title=None, show=False): """ Registers a new view. This is mostly so that we can display all views from a cell in a LoggingTabs object. :param obj: The object to display. If it has a "get_display_object" method, \ its return value is displayed :param title: A name for the object (otherwise, str(obj) is used) :return: """ print(obj) @exports class DynamicsLog(object): ROW_FORMAT = ("{:<10.2f}") + 3*(" {:>15.4f}") HEADER_FORMAT = ROW_FORMAT.replace('.4f','s').replace('.2f','s') def __init__(self): self._printed_header = False def print_header(self): timeheader = 'time /' peheader = 'potential /' keheader = 'kinetic /' temperatureheader = 'T /' print(self.HEADER_FORMAT.format(timeheader, peheader, keheader, temperatureheader)) timeunits = '{}'.format(u.default.time) peunits = '{}'.format(u.default.energy) keunits = '{}'.format(u.default.energy) temperatureunits = '{}'.format(u.default.temperature) print(self.HEADER_FORMAT.format(timeunits, peunits, keunits, temperatureunits)) self._printed_header = True def print_step(self, mol, properties): from . import kinetic_energy, kinetic_temperature if not self._printed_header: self.print_header() ke = kinetic_energy(properties['momenta'], mol.masses) t = kinetic_temperature(ke, mol.dynamic_dof) print(self.ROW_FORMAT.format(properties['time'].defunits_value(), properties['potential_energy'].defunits_value(), ke.defunits_value(), t.defunits_value()))
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/descriptors.py
.py
2,890
95
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Alias(object): """ Descriptor that delegates to a child's attribute or method. e.g. >>> class A(object): >>> childkeys = Alias('child.keys') >>> child = dict() >>> >>> a = A() >>> a.child['key'] = 'value' >>> a.childkeys() # calls a.child.keys(), returns ['key'] ['key'] """ def __init__(self, objattr): objname, attrname = objattr.split('.') self.objname = objname self.attrname = attrname def __get__(self, instance, owner): if instance is None: assert owner is not None return _unbound_getter(self.objname, self.attrname) else: proxied = getattr(instance, self.objname) return getattr(proxied, self.attrname) def __set__(self, instance, value): if instance is None: raise NotImplementedError() else: proxied = getattr(instance, self.objname) setattr(proxied, self.attrname, value) def _unbound_getter(objname, methodname): def _method_getter(s, *args, **kwargs): obj = getattr(s, objname) meth = getattr(obj, methodname) return meth(*args, **kwargs) return _method_getter class IndexView(object): def __init__(self, attr, index): self.attr = attr self.index = index def __get__(self, instance, owner): return getattr(instance, self.attr)[self.index] class Synonym(object): """ An attribute (class or intance) that is just a synonym for another. """ def __init__(self, name): self.name = name def __get__(self, instance, owner): return getattr(instance, self.name) def __set__(self, instance, value): setattr(instance, self.name, value) class Attribute(object): """For overriding a property in a superclass - turns the attribute back into a normal instance attribute""" def __init__(self, name): self.name = name def __get__(self, instance, cls): return getattr(instance, self.name) def __set__(self, instance, value): return setattr(instance, self.name, value)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/classes.py
.py
6,291
226
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections from .descriptors import Alias class Categorizer(dict): """ Create a dict of lists from an iterable, with dict keys given by keyfn """ def __init__(self, keyfn, iterable): super().__init__() self.keyfn = keyfn for item in iterable: self.add(item) def add(self, item): key = self.keyfn(item) if key not in self: self[key] = [] self[key].append(item) class NewUserDict(collections.MutableMapping): """ Reimplementation of UserDict with new-style classes but without subclassing dict. In addition to the normal dict methods, the only addition here is the ``data`` attribute that gives us an actual ``dict`` to store things in Unlike dict, pickles easily. Unlike UserDict, uses new-style classes. """ def __init__(self, *args, **kwargs): self.data = dict(*args, **kwargs) __delitem__ = Alias('data.__delitem__') __setitem__ = Alias('data.__setitem__') __getitem__ = Alias('data.__getitem__') __len__ = Alias('data.__len__') __iter__ = Alias('data.__iter__') class ExclusiveList(object): """ Behaves like a list, but won't allow items with duplicate keys to be added. """ def __init__(self, iterable=None, key=None): self._keys = collections.OrderedDict() if key is None: self._keyfn = self._identity else: self._keyfn = key if iterable is not None: self.extend(iterable) def append(self, obj): k = self._keyfn(obj) if k in self._keys: raise KeyError("'%s' can't be added because its key '%s' already exists" % (obj, k)) else: self._keys[k] = obj def clear(self): self._keys = collections.OrderedDict() @staticmethod def _identity(obj): return obj def __iter__(self): return iter(self._keys.values()) def __len__(self): return len(self._keys) def __getitem__(self, item): return list(self._keys.values())[item] def remove(self, obj): k = self._keyfn(obj) stored = self._keys[k] if obj is not stored: raise KeyError(obj) else: self._keys.pop(k) def extend(self, iterable): for item in iterable: self.append(item) def pop(self, index=None): if index is None: return self._keys.popitem()[1] else: k = list(self._keys.keys())[index] return self._keys.pop(k) def __repr__(self): return '%s(%s)' % (type(self).__name__, list(self._keys.values())) __str__ = __repr__ class DotDict(object): """ An attribute-accessible dictionary that preserves insertion order """ def __init__(self, *args, **kwargs): self._od = collections.OrderedDict(*args, **kwargs) self._init = True def __delattr__(self, item): if not self.__dict__.get('_init', False): super().__delattr__(item) else: try: del self._od[item] except KeyError: raise AttributeError() def __delitem__(self, key): if not self.__dict__.get('_init', False): raise TypeError() else: del self._od[key] def __dir__(self): return list(self.keys()) + super().__dir__() def __getstate__(self): return {'od': self._od} def __setstate__(self, state): self._od = state['od'] self._init = True def copy(self): return self.__class__(self._od.copy()) def copydict(self): """ Returns a copy of the core dictionary in its native class """ return self._od.copy() def __eq__(self, other): try: return self._od == other._od except AttributeError: return False def __repr__(self): return str(self._od).replace('OrderedDict', self.__class__.__name__) def __getattr__(self, key): if not self.__dict__.get('_init', False): return self.__getattribute__(key) if key in self._od: return self._od[key] else: raise AttributeError(key) def __setattr__(self, key, val): if not self.__dict__.get('_init', False): super().__setattr__(key, val) else: self._od[key] = val def __bool__(self): return bool(self._od) __nonzero__ = __bool__ for _v in ('keys values items __iter__ __getitem__ __len__ __contains__ clear ' ' __setitem__ pop setdefault get update').split(): setattr(DotDict, _v, Alias('_od.%s' % _v)) def named_dict(l): """ Creates a DotDict from a list of items that have a ``name`` attribute Args: l (List[object]): list of objects that have a ``name`` or ``__name__`` attribute Returns: DotDict[str, object]: mapping of objects' names to objects Example: >>> import moldesign as mdt >>> m1 = mdt.from_name('benzene') >>> m2 = mdt.from_name('propane') >>> d = named_dict([m1, m2, DotDict]) >>> list(d.keys()) ['benzene', 'propane', 'DotDict'] >>> d.propane <propane (Molecule), 11 atoms> >>> d.DotDict moldesign.utils.classes.DotDict """ return DotDict((_namegetter(obj), obj) for obj in l) def _namegetter(obj): try: return obj.name except AttributeError: return obj.__name__
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/__init__.py
.py
844
25
# Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from .exportutils import * from . import docparsers from .callsigs import * from .descriptors import * from .classes import * from .databases import * from .utils import * from .numerical import * from .json_extension import *
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/databases.py
.py
2,281
82
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import zlib import future.utils from . import Alias if future.utils.PY2: import dumbdbm else: import dbm.dumb as dumbdbm class CompressedJsonDbm(object): """ Quick-and-dirty interface to a DBM file """ def __init__(self, filename, flag='r', dbm=dumbdbm): self.dbm = dbm if hasattr(dbm, 'open'): self.db = self.dbm.open(filename, flag) else: self.db = self.dbm(filename, flag) def __getattr__(self, item): return getattr(self.db, item) def __dir__(self): return list(self.__dict__.keys()) + dir(self.db) def __len__(self): return len(self.db) def __getitem__(self, key): gzvalue = self.db[key] return json.loads(zlib.decompress(gzvalue).decode()) def __setitem__(self, key, value): gzvalue = zlib.compress(json.dumps(value)) self.db[key] = gzvalue __contains__ = Alias('db.__contains__') class ReadOnlyDumb(dumbdbm._Database): """ A read-only subclass of dumbdbm All possible operations that could result in a disk write have been turned into no-ops or raise exceptions """ def _commit(self): # Does nothing! pass def __setitem__(self, key, value): raise NotImplementedError('This is a read-only database') def __delitem__(self, key): raise NotImplementedError('This is a read-only database') def _addkey(self, *args): assert False, 'Should never be here - this is a read-only database'
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/numerical.py
.py
3,902
107
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from . import Alias class ResizableArray(object): """ Behaves like a numpy array, but with fast extends and appends for the first index. Similar to python lists, the underlying array is reallocated in large chunks whenever the number of elements grows beyond the current memory allocation. """ #@args_from(np.array) def __init__(self, *args, **kwargs): self._array = np.array(*args, **kwargs) self._len = len(self._array) self._subarray = self._array[:self._len] self._size = self._len def __getattr__(self, item): if item == '_subarray': return self.__getattribute__('_subarray') return getattr(self._subarray, item) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, repr(self._subarray)) def append(self, item): self.extend([item]) def extend(self, its): try: ll = len(its) except TypeError: its = list(its) ll = len(its) newlen = self._len + ll if newlen > self._size: self._resize(newlen) for item in its: self._array[self._len] = item self._len += 1 self._subarray = self._array[:self._len] def _resize(self, minsize): newsize = round_up_to_power_of_two(minsize) if newsize <= self._size: return newshape = (newsize,) + self._array.shape[1:] newarray = np.empty(newshape, dtype=self._array.dtype) newarray[:self._len] = self._array self._array = newarray self._size = newsize # delegate magic methods as well - this is a list of all math-related array methods _ARRAYMAGIC = ('__abs__', '__add__', '__and__', '__array__', '__contains__', '__copy__', '__deepcopy__', '__delitem__', '__delslice__', '__div__', '__divmod__', '__eq__', '__float__', '__floordiv__', '__ge__', '__getitem__', '__getslice__', '__gt__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__', '__ilshift__', '__imod__', '__imul__', '__index__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__itruediv__', '__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setitem__', '__setslice__', '__str__', '__sub__', '__truediv__', '__xor__') for _methname in _ARRAYMAGIC: setattr(ResizableArray, _methname, Alias('_subarray.%s' % _methname)) def round_up_to_power_of_two(n): """ From http://stackoverflow.com/a/14267825/1958900 """ if n < 0: raise TypeError("Nonzero positive integers only") elif n == 0: return 1 else: return 1 << (n-1).bit_length()
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/exportutils.py
.py
1,476
50
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect __all__ = 'exports exports_names'.split() def exports(f): """ Add a function to its module's __all__ attribute """ all_list = _get_module_all(1) all_list.append(f.__name__) return f def exports_names(*names): """ Add names to this module's __all__ attribute """ all_list = _get_module_all(1) all_list.extend(names) def _get_module_all(depth): """ Get a reference to the __all__ attribute of the module calling the function that calls this function :) FROM http://stackoverflow.com/q/6187355/1958900""" frm = inspect.stack()[depth+1] mod = inspect.getmodule(frm[0]) if not hasattr(mod, '__all__'): mod.__all__ = [] return mod.__all__
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/utils.py
.py
9,726
329
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() import future.utils from functools import reduce import fractions import operator import os import re import sys import tempfile from html.parser import HTMLParser def make_none(*args, **kwargs): return None def if_not_none(item, default): """ Equivalent to `item if item is not None else default` """ if item is None: return default else: return item class MLStripper(HTMLParser): """ Strips markup language tags from a string. FROM http://stackoverflow.com/a/925630/1958900 """ def __init__(self): if not future.utils.PY2: super().__init__() self.reset() self.fed = [] self.strict = False self.convert_charrefs = True def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def html_to_text(html): """ FROM http://stackoverflow.com/a/925630/1958900 """ s = MLStripper() s.unescape = True # convert HTML entities to text s.feed(html) return s.get_data() def printflush(s, newline=True): if newline: print(s) else: print(s, end=' ') sys.stdout.flush() def which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. Note: Copied without modification from Python 3.6.1 ``shutil.which` source code """ # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # If we're given a path with a directory part, look it up directly rather # than referring to PATH directories. This includes checking relative to the # current directory, e.g. ./script if os.path.dirname(cmd): if _access_check(cmd, mode): return cmd return None if path is None: path = os.environ.get("PATH", os.defpath) if not path: return None path = path.split(os.pathsep) if sys.platform == "win32": # The current directory takes precedence on Windows. if not os.curdir in path: path.insert(0, os.curdir) # PATHEXT is necessary to check on Windows. pathext = os.environ.get("PATHEXT", "").split(os.pathsep) # See if the given file matches any of the expected path extensions. # This will allow us to short circuit when given "python.exe". # If it does match, only test that one, otherwise we have to try # others. if any(cmd.lower().endswith(ext.lower()) for ext in pathext): files = [cmd] else: files = [cmd + ext for ext in pathext] else: # On other platforms you don't have things like PATHEXT to tell you # what file suffixes are executable, so just pass on cmd as-is. files = [cmd] seen = set() for dir in path: normdir = os.path.normcase(dir) if not normdir in seen: seen.add(normdir) for thefile in files: name = os.path.join(dir, thefile) if _access_check(name, mode): return name return None class methodcaller(object): """The pickleable implementation of the standard library operator.methodcaller. This was copied without modification from: https://github.com/python/cpython/blob/065990fa5bd30fb3ca61b90adebc7d8cb3f16b5a/Lib/operator.py The c-extension version is not pickleable, so we keep a copy of the pure-python standard library code here. See https://bugs.python.org/issue22955 Original documentation: Return a callable object that calls the given method on its operand. After f = methodcaller('name'), the call f(r) returns r.name(). After g = methodcaller('name', 'date', foo=1), the call g(r) returns r.name('date', foo=1). """ __slots__ = ('_name', '_args', '_kwargs') def __init__(*args, **kwargs): if len(args) < 2: msg = "methodcaller needs at least one argument, the method name" raise TypeError(msg) self = args[0] self._name = args[1] if not isinstance(self._name, future.utils.native_str): raise TypeError('method name must be a string') self._args = args[2:] self._kwargs = kwargs def __call__(self, obj): return getattr(obj, self._name)(*self._args, **self._kwargs) def __repr__(self): args = [repr(self._name)] args.extend(list(map(repr, self._args))) args.extend('%s=%r' % (k, v) for k, v in list(self._kwargs.items())) return '%s.%s(%s)' % (self.__class__.__module__, self.__class__.__name__, ', '.join(args)) def __reduce__(self): if not self._kwargs: return self.__class__, (self._name,) + self._args else: from functools import partial return partial(self.__class__, self._name, **self._kwargs), self._args class textnotify(object): """ Print a single, immediately flushed line to log the execution of a block. Prints 'done' at the end of the line (or 'ERROR' if an uncaught exception) Examples: >>> import time >>> with textnotify('starting to sleep'): >>> time.sleep(3) starting to sleep...done >>> with textnotify('raising an exception...'): >>> raise ValueError() raising an exception...error ValueError [...] """ def __init__(self, startmsg): if startmsg.strip()[-3:] != '...': startmsg = startmsg.strip() + '...' self.startmsg = startmsg def __enter__(self): printflush(self.startmsg, newline=False) def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: printflush('done') else: printflush('ERROR') class BaseTable(object): def __init__(self, categories, fileobj=None): self.categories = categories self.lines = [] self.fileobj = fileobj def add_line(self, obj): if hasattr(obj, 'keys'): newline = [obj.get(cat, '') for cat in self.categories] else: assert len(obj) == len(self.categories) newline = obj self.lines.append(newline) self.writeline(newline) def writeline(self, newline): raise NotImplementedError() def getstring(self): raise NotImplementedError() class MarkdownTable(BaseTable): def __init__(self, *categories): super().__init__(categories) def markdown(self, replace=None): if replace is None: replace = {} outlines = ['| ' + ' | '.join(self.categories) + ' |', '|-' + ''.join('|-' for x in self.categories) + '|'] for line in self.lines: nextline = [str(replace.get(val, val)) for val in line] outlines.append('| ' + ' | '.join(nextline) + ' |') return '\n'.join(outlines) def writeline(self, newline): pass def getstring(self): return self.markdown() def binomial_coefficient(n, k): # credit to http://stackoverflow.com/users/226086/nas-banov return int(reduce(operator.mul, (fractions.Fraction(n - i, i + 1) for i in range(k)), 1)) def pairwise_displacements(a): """ :type a: numpy.array from http://stackoverflow.com/questions/22390418/pairwise-displacement-vectors-among-set-of-points """ import numpy as np n = a.shape[0] d = a.shape[1] c = binomial_coefficient(n, 2) out = np.zeros((c, d)) l = 0 r = l + n - 1 for sl in range(1, n): # no point1 - point1! out[l:r] = a[:n - sl] - a[sl:] l = r r += n - (sl + 1) return out def is_printable(s): import string for c in s: if c not in string.printable: return False else: return True class _RedirectStream(object): """From python3.4 stdlib """ _stream = None def __init__(self, new_target): self._new_target = new_target # We use a list of old targets to make this CM re-entrant self._old_targets = [] def __enter__(self): self._old_targets.append(getattr(sys, self._stream)) setattr(sys, self._stream, self._new_target) return self._new_target def __exit__(self, exctype, excinst, exctb): setattr(sys, self._stream, self._old_targets.pop()) class redirect_stderr(_RedirectStream): """From python3.4 stdlib""" _stream = "stderr" GETFLOAT = re.compile(r'-?\d+(\.\d+)?(e[-+]?\d+)') # matches numbers, e.g. 1, -2.0, 3.5e50, 0.001e-10 def from_filepath(func, filelike): """Run func on a temporary *path* assigned to filelike""" if type(filelike) == str: return func(filelike) else: with tempfile.NamedTemporaryFile() as outfile: outfile.write(filelike.read().encode()) # hack - prob need to detect bytes outfile.flush() result = func(outfile.name) return result
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/json_extension.py
.py
1,405
42
# Copyright 2016 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import json from . import args_from # TODO: defined JSON types that we can serialize directly into MDT objects OR # use a JSON "pickling" library (only if there's more complexity than covered here already) class JsonEncoder(json.JSONEncoder): def default(self, obj): if hasattr(obj, 'to_json'): return obj.to_json() elif hasattr(obj, 'tolist'): return obj.tolist() else: raise TypeError('No seralizer for object "%s" (class: %s)' % (obj,obj.__class__.__name__)) @args_from(json.dump) def json_dump(*args, **kwargs): return json.dump(*args, cls=JsonEncoder, **kwargs) @args_from(json.dumps) def json_dumps(*args, **kwargs): return json.dumps(*args, cls=JsonEncoder, **kwargs)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/apply_copyright.sh
.sh
729
22
#!/bin/bash for file in `grep -L "Copyright 2016 Autodesk Inc." *.py`; do mv $file{.bak} cat > $file <<EOF # Copyright 2016 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. EOF cat $file.bak >> $file done
Shell
3D
Autodesk/molecular-design-toolkit
moldesign/utils/callsigs.py
.py
9,122
259
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import inspect import os from functools import wraps import collections import funcsigs from .utils import if_not_none from .docparsers import GoogleDocArgumentInjector def args_from(original_function, only=None, allexcept=None, inject_kwargs=None, inject_docs=None, wraps=None, update_docstring_args=False): """ Decorator to transfer call signatures - helps to hide ugly *args and **kwargs in delegated calls Args: original_function (callable): the function to take the call signature from only (List[str]): only transfer these arguments (incompatible with `allexcept`) wraps (bool): Transfer documentation and attributes from original_function to decorated_function, using functools.wraps (default: True if call signature is unchanged, False otherwise) allexcept (List[str]): transfer all except these arguments (incompatible with `only`) inject_kwargs (dict): Inject new kwargs into the call signature (of the form ``{argname: defaultvalue}``) inject_docs (dict): Add or modifies argument documentation (requires google-style docstrings) with a dict of the form `{argname: "(type): description"}` update_docstring_args (bool): Update "arguments" section of the docstring using the original function's documentation (requires google-style docstrings and wraps=False) Note: To use arguments from a classes' __init__ method, pass the class itself as ``original_function`` - this will also allow us to inject the documentation Returns: Decorator function """ # NEWFEATURE - verify arguments? if only and allexcept: raise ValueError('Error in keyword arguments - ' 'pass *either* "only" or "allexcept", not both') origname = get_qualified_name(original_function) if hasattr(original_function, '__signature__'): sig = original_function.__signature__.replace() else: sig = funcsigs.signature(original_function) # Modify the call signature if necessary if only or allexcept or inject_kwargs: wraps = if_not_none(wraps, False) newparams = [] if only: for param in only: newparams.append(sig.parameters[param]) elif allexcept: for name, param in sig.parameters.items(): if name not in allexcept: newparams.append(param) else: newparams = list(sig.parameters.values()) if inject_kwargs: for name, default in inject_kwargs.items(): newp = funcsigs.Parameter(name, funcsigs.Parameter.POSITIONAL_OR_KEYWORD, default=default) newparams.append(newp) newparams.sort(key=lambda param: param._kind) sig = sig.replace(parameters=newparams) else: wraps = if_not_none(wraps, True) # Get the docstring arguments if update_docstring_args: original_docs = GoogleDocArgumentInjector(original_function.__doc__) argument_docstrings = collections.OrderedDict((p.name, original_docs.args[p.name]) for p in newparams) def decorator(f): """Modify f's call signature (using the `__signature__` attribute)""" if wraps: fname = original_function.__name__ f = functools.wraps(original_function)(f) f.__name__ = fname # revert name change else: fname = f.__name__ f.__signature__ = sig if update_docstring_args or inject_kwargs: if not update_docstring_args: argument_docstrings = GoogleDocArgumentInjector(f.__doc__).args docs = GoogleDocArgumentInjector(f.__doc__) docs.args = argument_docstrings if not hasattr(f, '__orig_docs'): f.__orig_docs = [] f.__orig_docs.append(f.__doc__) f.__doc__ = docs.new_docstring() # Only for building sphinx documentation: if os.environ.get('SPHINX_IS_BUILDING_DOCS', ""): sigstring = '%s%s\n' % (fname, sig) if hasattr(f, '__doc__') and f.__doc__ is not None: f.__doc__ = sigstring + f.__doc__ else: f.__doc__ = sigstring return f return decorator def kwargs_from(reference_function, mod_docs=True): """ Replaces ``**kwargs`` in a call signature with keyword arguments from another function. Args: reference_function (function): function to get kwargs from mod_docs (bool): whether to modify the decorated function's docstring Note: ``mod_docs`` works ONLY for google-style docstrings """ refsig = funcsigs.signature(reference_function) origname = get_qualified_name(reference_function) kwparams = [] for name, param in refsig.parameters.items(): if param.default != param.empty or param.kind in (param.VAR_KEYWORD, param.KEYWORD_ONLY): if param.name[0] != '_': kwparams.append(param) if mod_docs: refdocs = GoogleDocArgumentInjector(reference_function.__doc__) def decorator(f): sig = funcsigs.signature(f) fparams = [] found_varkeyword = None for name, param in sig.parameters.items(): if param.kind == param.VAR_KEYWORD: fparams.extend(kwparams) found_varkeyword = name else: fparams.append(param) if not found_varkeyword: raise TypeError("Function has no **kwargs wildcard.") f.__signature__ = sig.replace(parameters=fparams) if mod_docs: docs = GoogleDocArgumentInjector(f.__doc__) new_args = collections.OrderedDict() for argname, doc in docs.args.items(): if argname == found_varkeyword: for param in kwparams: default_argdoc = '%s: argument for %s' % (param.name, origname) new_args[param.name] = refdocs.args.get(param.name, default_argdoc) else: new_args[argname] = doc docs.args = new_args if not hasattr(f, '__orig_docs'): f.__orig_docs = [] f.__orig_docs.append(f.__doc__) f.__doc__ = docs.new_docstring() return f return decorator def get_qualified_name(original_function): if inspect.ismethod(original_function): origname = '.'.join([original_function.__module__, original_function.__self__.__class__.__name__, original_function.__name__]) return ':meth:`%s`' % origname else: origname = original_function.__module__+'.'+original_function.__name__ return ':meth:`%s`' % origname class DocInherit(object): """ Allows methods to inherit docstrings from their superclasses FROM http://code.activestate.com/recipes/576862/ """ def __init__(self, mthd): self.mthd = mthd self.name = mthd.__name__ def __get__(self, obj, cls): if obj: return self.get_with_inst(obj, cls) else: return self.get_no_inst(cls) def get_with_inst(self, obj, cls): overridden = getattr(super(), self.name, None) @wraps(self.mthd, assigned=('__name__','__module__')) def f(*args, **kwargs): return self.mthd(obj, *args, **kwargs) return self.use_parent_doc(f, overridden) def get_no_inst(self, cls): for parent in cls.__mro__[1:]: overridden = getattr(parent, self.name, None) if overridden: break @wraps(self.mthd, assigned=('__name__','__module__')) def f(*args, **kwargs): return self.mthd(*args, **kwargs) return self.use_parent_doc(f, overridden) def use_parent_doc(self, func, source): if source is None: raise NameError("Can't find '%s' in parents"%self.name) func.__doc__ = source.__doc__ return func #idiomatic decorator name doc_inherit = DocInherit
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/docparsers/__init__.py
.py
46
2
from .google import GoogleDocArgumentInjector
Python
3D
Autodesk/molecular-design-toolkit
moldesign/utils/docparsers/google.py
.py
22,562
649
""" Routines for runtime docstring argument injection This file contains HEAVILY modified routines from sphinx.ext.napoleon, from version 1.4.4 This has been vendored into MDT because the modification makes use of private functions which have already changed in the dev branch. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2007-2016 by the Sphinx team, see sphinxlicense/AUTHORS. :license: BSD, see sphinxlicense/LICENSE for details. """ from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() from past.builtins import basestring import collections import re import sys _google_section_regex = re.compile(r'^(\s|\w)+:\s*$') _google_typed_arg_regex = re.compile(r'\s*(.+?)\s*\(\s*(.+?)\s*\)') _single_colon_regex = re.compile(r'(?<!:):(?!:)') _xref_regex = re.compile(r'(:\w+:\S+:`.+?`|:\S+:`.+?`|`.+?`)') _bullet_list_regex = re.compile(r'^(\*|\+|\-)(\s+\S|\s*$)') _enumerated_list_regex = re.compile( r'^(?P<paren>\()?' r'(\d+|#|[ivxlcdm]+|[IVXLCDM]+|[a-zA-Z])' r'(?(paren)\)|\.)(\s+\S|\s*$)') class GoogleDocArgumentInjector(object): SECTIONS = set('args arguments parameters'.split()) def __init__(self, docstring, prepare=True): # this routine has been modified - it's been streamlined for the current purpose if prepare: if docstring is None: self.docstring = [] else: self.docstring = prepare_docstring(docstring) elif isinstance(docstring, basestring): self.docstring = docstring.splitlines() else: self.docstring = docstring self.lines_before_args = [] self.arg_section = [] self.lines_after_args = [] self.args = collections.OrderedDict() self.arg_indent = None self.arg_section_name = 'Args' # default, can be overwritten by the actual section name self._what = 'function' self._lines = list(self.docstring) self._line_iter = modify_iter(self.docstring, modifier=lambda s: s.rstrip()) self._parsed_lines = [] self._is_in_section = False self._section_indent = 0 self._sections = { 'args': self._parse_parameters_section, 'arguments': self._parse_parameters_section, 'attributes': None, 'example': None, 'examples': None, 'keyword args': None, 'keyword arguments': None, 'methods': None, 'note': None, 'notes': None, 'other parameters': None, 'parameters': self._parse_parameters_section, 'return': None, 'returns': None, 'raises': None, 'references': None, 'see also': None, 'todo': None, 'warning': None, 'warnings': None, 'warns': None, 'yield': None, 'yields': None, } self.parse() def new_docstring(self): """ Create a new docstring with the current state of the argument list Returns: str: docstring with modified argument list """ newlines = list(self.lines_before_args) if self.args: newlines.append(' '*self.arg_indent + self.arg_section_name + ':') newlines.extend(self._indent(list(self.args.values()), self.arg_indent+4)) newlines.append('') newlines.extend(self.lines_after_args) return '\n'.join(newlines) def parse(self): """ This method is a modified version of GoogleDocstring._parse """ self._parsed_lines = self._consume_empty() found_args = lines_are_args = False while self._line_iter.has_next(): if self._is_section_header(): try: section = self._consume_section_header() self._is_in_section = True self._section_indent = self._get_current_indent() lines = [section + ':'] if section.lower() in self.SECTIONS: lines.extend(self._sections[section.lower()](section)) found_args = True lines_are_args = True else: lines.extend(self._consume_to_next_section()) finally: self._is_in_section = False self._section_indent = 0 else: if not self._parsed_lines: lines = self._consume_contiguous()+self._consume_empty() else: lines = self._consume_to_next_section() if lines_are_args: lines_are_args = False self.arg_section.extend(lines) elif found_args: self.lines_after_args.extend(lines) else: self.lines_before_args.extend(lines) self._parsed_lines.extend(lines) if self.arg_indent is None: self.arg_indent = self._get_current_indent() def _parse_parameters_section(self, section): """ This method was heavily modified to store information instead of formatting it for rst """ self.arg_section_name = section fields = self._consume_fields() num_indent = self._get_current_indent() self.arg_indent = num_indent lines = [] for _name, _type, _desc in fields: _desc = self._strip_empty(_desc) if isinstance(_desc, list): _desc = '\n '.join(_desc) if _type: line = '%s (%s): %s' % (_name, _type, _desc) else: line = '%s: %s' % (_name, _desc) self.args[_name.lstrip('\*')] = line lines.append(line) lines = self._indent(lines, num_indent+4) if lines[-1].strip(): lines.append('') return lines def _indent(self, lines, n=4): # MDT: modified to include breaks within lines sp = ' ' * n return [sp + line.replace('\n', '\n'+sp) for line in lines] ###################################################### ### All routines below are unmodified ### ###################################################### def lines(self): """Return the parsed lines of the docstring in reStructuredText format. Returns ------- :obj:`list` of :obj:`str` The lines of the docstring in a list. """ return self._parsed_lines def _consume_indented_block(self, indent=1): lines = [] line = self._line_iter.peek() while(not self._is_section_break() and (not line or self._is_indented(line, indent))): lines.append(next(self._line_iter)) line = self._line_iter.peek() return lines def _consume_contiguous(self): lines = [] while (self._line_iter.has_next() and self._line_iter.peek() and not self._is_section_header()): lines.append(next(self._line_iter)) return lines def _consume_empty(self): lines = [] line = self._line_iter.peek() while self._line_iter.has_next() and not line: lines.append(next(self._line_iter)) line = self._line_iter.peek() return lines def _consume_field(self, parse_type=True, prefer_type=False): line = next(self._line_iter) before, colon, after = self._partition_field_on_colon(line) _name, _type, _desc = before, '', after if parse_type: match = _google_typed_arg_regex.match(before) if match: _name = match.group(1) _type = match.group(2) _name = self._escape_args_and_kwargs(_name) if prefer_type and not _type: _type, _name = _name, _type indent = self._get_indent(line) + 1 _desc = [_desc] + self._dedent(self._consume_indented_block(indent)) _desc = self.__class__(_desc, prepare=False).lines() return _name, _type, _desc def _consume_fields(self, parse_type=True, prefer_type=False): self._consume_empty() fields = [] while not self._is_section_break(): _name, _type, _desc = self._consume_field(parse_type, prefer_type) if _name or _type or _desc: fields.append((_name, _type, _desc,)) return fields def _consume_section_header(self): section = next(self._line_iter) stripped_section = section.strip(':') if stripped_section.lower() in self._sections: section = stripped_section return section def _consume_to_end(self): lines = [] while self._line_iter.has_next(): lines.append(next(self._line_iter)) return lines def _consume_to_next_section(self): self._consume_empty() lines = [] while not self._is_section_break(): lines.append(next(self._line_iter)) return lines + self._consume_empty() def _dedent(self, lines, full=False): if full: return [line.lstrip() for line in lines] else: min_indent = self._get_min_indent(lines) return [line[min_indent:] for line in lines] def _escape_args_and_kwargs(self, name): if name[:2] == '**': return r'\*\*' + name[2:] elif name[:1] == '*': return r'\*' + name[1:] else: return name def _fix_field_desc(self, desc): if self._is_list(desc): desc = [''] + desc elif desc[0].endswith('::'): desc_block = desc[1:] indent = self._get_indent(desc[0]) block_indent = self._get_initial_indent(desc_block) if block_indent > indent: desc = [''] + desc else: desc = ['', desc[0]] + self._indent(desc_block, 4) return desc def _get_current_indent(self, peek_ahead=0): line = self._line_iter.peek(peek_ahead + 1)[peek_ahead] while line != self._line_iter.sentinel: if line: return self._get_indent(line) peek_ahead += 1 line = self._line_iter.peek(peek_ahead + 1)[peek_ahead] return 0 def _get_indent(self, line): for i, s in enumerate(line): if not s.isspace(): return i return len(line) def _get_initial_indent(self, lines): for line in lines: if line: return self._get_indent(line) return 0 def _get_min_indent(self, lines): min_indent = None for line in lines: if line: indent = self._get_indent(line) if min_indent is None: min_indent = indent elif indent < min_indent: min_indent = indent return min_indent or 0 def _is_indented(self, line, indent=1): for i, s in enumerate(line): if i >= indent: return True elif not s.isspace(): return False return False def _is_list(self, lines): if not lines: return False if _bullet_list_regex.match(lines[0]): return True if _enumerated_list_regex.match(lines[0]): return True if len(lines) < 2 or lines[0].endswith('::'): return False indent = self._get_indent(lines[0]) next_indent = indent for line in lines[1:]: if line: next_indent = self._get_indent(line) break return next_indent > indent def _is_section_header(self): section = self._line_iter.peek().lower() match = _google_section_regex.match(section) if match and section.strip(':') in self._sections: header_indent = self._get_indent(section) section_indent = self._get_current_indent(peek_ahead=1) return section_indent > header_indent return False def _is_section_break(self): line = self._line_iter.peek() return (not self._line_iter.has_next() or self._is_section_header() or (self._is_in_section and line and not self._is_indented(line, self._section_indent))) def _partition_field_on_colon(self, line): before_colon = [] after_colon = [] colon = '' found_colon = False for i, source in enumerate(_xref_regex.split(line)): if found_colon: after_colon.append(source) else: m = _single_colon_regex.search(source) if (i % 2) == 0 and m: found_colon = True colon = source[m.start(): m.end()] before_colon.append(source[:m.start()]) after_colon.append(source[m.end():]) else: before_colon.append(source) return ("".join(before_colon).strip(), colon, "".join(after_colon).strip()) def _strip_empty(self, lines): if lines: start = -1 for i, line in enumerate(lines): if line: start = i break if start == -1: lines = [] end = -1 for i in reversed(range(len(lines))): line = lines[i] if line: end = i break if start > 0 or end + 1 < len(lines): lines = lines[start:end + 1] return lines class peek_iter(object): """An iterator object that supports peeking ahead. Parameters ---------- o : iterable or callable `o` is interpreted very differently depending on the presence of `sentinel`. If `sentinel` is not given, then `o` must be a collection object which supports either the iteration protocol or the sequence protocol. If `sentinel` is given, then `o` must be a callable object. sentinel : any value, optional If given, the iterator will call `o` with no arguments for each call to its `next` method; if the value returned is equal to `sentinel`, :exc:`StopIteration` will be raised, otherwise the value will be returned. See Also -------- `peek_iter` can operate as a drop in replacement for the built-in `iter <https://docs.python.org/2/library/functions.html#iter>`_ function. Attributes ---------- sentinel The value used to indicate the iterator is exhausted. If `sentinel` was not given when the `peek_iter` was instantiated, then it will be set to a new object instance: ``object()``. """ def __init__(self, *args): """__init__(o, sentinel=None)""" self._iterable = iter(*args) self._cache = collections.deque() if len(args) == 2: self.sentinel = args[1] else: self.sentinel = object() def __iter__(self): return self def __next__(self, n=None): # note: prevent 2to3 to transform self.next() in next(self) which # causes an infinite loop ! return getattr(self, 'next')(n) def _fillcache(self, n): """Cache `n` items. If `n` is 0 or None, then 1 item is cached.""" if not n: n = 1 try: while len(self._cache) < n: self._cache.append(next(self._iterable)) except StopIteration: while len(self._cache) < n: self._cache.append(self.sentinel) def has_next(self): """Determine if iterator is exhausted. Returns ------- bool True if iterator has more items, False otherwise. Note ---- Will never raise :exc:`StopIteration`. """ return self.peek() != self.sentinel def next(self, n=None): """Get the next item or `n` items of the iterator. Parameters ---------- n : int or None The number of items to retrieve. Defaults to None. Returns ------- item or list of items The next item or `n` items of the iterator. If `n` is None, the item itself is returned. If `n` is an int, the items will be returned in a list. If `n` is 0, an empty list is returned. Raises ------ StopIteration Raised if the iterator is exhausted, even if `n` is 0. """ self._fillcache(n) if not n: if self._cache[0] == self.sentinel: raise StopIteration if n is None: result = self._cache.popleft() else: result = [] else: if self._cache[n - 1] == self.sentinel: raise StopIteration result = [self._cache.popleft() for i in range(n)] return result def peek(self, n=None): """Preview the next item or `n` items of the iterator. The iterator is not advanced when peek is called. Returns ------- item or list of items The next item or `n` items of the iterator. If `n` is None, the item itself is returned. If `n` is an int, the items will be returned in a list. If `n` is 0, an empty list is returned. If the iterator is exhausted, `peek_iter.sentinel` is returned, or placed as the last item in the returned list. Note ---- Will never raise :exc:`StopIteration`. """ self._fillcache(n) if n is None: result = self._cache[0] else: result = [self._cache[i] for i in range(n)] return result class modify_iter(peek_iter): """An iterator object that supports modifying items as they are returned. Parameters ---------- o : iterable or callable `o` is interpreted very differently depending on the presence of `sentinel`. If `sentinel` is not given, then `o` must be a collection object which supports either the iteration protocol or the sequence protocol. If `sentinel` is given, then `o` must be a callable object. sentinel : any value, optional If given, the iterator will call `o` with no arguments for each call to its `next` method; if the value returned is equal to `sentinel`, :exc:`StopIteration` will be raised, otherwise the value will be returned. modifier : callable, optional The function that will be used to modify each item returned by the iterator. `modifier` should take a single argument and return a single value. Defaults to ``lambda x: x``. If `sentinel` is not given, `modifier` must be passed as a keyword argument. Attributes ---------- modifier : callable `modifier` is called with each item in `o` as it is iterated. The return value of `modifier` is returned in lieu of the item. Values returned by `peek` as well as `next` are affected by `modifier`. However, `modify_iter.sentinel` is never passed through `modifier`; it will always be returned from `peek` unmodified. Example ------- >>> a = [" A list ", ... " of strings ", ... " with ", ... " extra ", ... " whitespace. "] >>> modifier = lambda s: s.strip().replace('with', 'without') >>> for s in modify_iter(a, modifier=modifier): ... print('"%s"' % s) "A list" "of strings" "without" "extra" "whitespace." """ def __init__(self, *args, **kwargs): """__init__(o, sentinel=None, modifier=lambda x: x)""" if 'modifier' in kwargs: self.modifier = kwargs['modifier'] elif len(args) > 2: self.modifier = args[2] args = args[:2] else: self.modifier = lambda x: x if not callable(self.modifier): raise TypeError('modify_iter(o, modifier): ' 'modifier must be callable') super().__init__(*args) def _fillcache(self, n): """Cache `n` modified items. If `n` is 0 or None, 1 item is cached. Each item returned by the iterator is passed through the `modify_iter.modified` function before being cached. """ if not n: n = 1 try: while len(self._cache) < n: self._cache.append(self.modifier(next(self._iterable))) except StopIteration: while len(self._cache) < n: self._cache.append(self.sentinel) def prepare_docstring(s, ignore=1): """Convert a docstring into lines of parseable reST. Remove common leading indentation, where the indentation of a given number of lines (usually just one) is ignored. Return the docstring as a list of lines usable for inserting into a docutils ViewList (used as argument of nested_parse().) An empty line is added to act as a separator between this docstring and following content. """ lines = s.expandtabs().splitlines() # Find minimum indentation of any non-blank lines after ignored lines. margin = sys.maxsize for line in lines[ignore:]: content = len(line.lstrip()) if content: indent = len(line) - content margin = min(margin, indent) # Remove indentation from ignored lines. for i in range(ignore): if i < len(lines): lines[i] = lines[i].lstrip() if margin < sys.maxsize: for i in range(ignore, len(lines)): lines[i] = lines[i][margin:] # Remove any leading blank lines. while lines and not lines[0]: lines.pop(0) # make sure there is an empty line at the end if lines and lines[-1]: lines.append('') return lines
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/ambertools.py
.py
6,291
161
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import moldesign as mdt from .. import compute, utils from ..compute import packages from .. import units as u from ..molecules import AtomicProperties @utils.kwargs_from(mdt.compute.run_job) def calc_am1_bcc_charges(mol, **kwargs): """Calculate am1 bcc charges Args: mol (moldesign.Molecule): assign partial charges to this molecule (they will be stored at ``mol.properties['am1-bcc']``) Note: This will implicity run an AM1 energy minimization before calculating the final partial charges. For more control over this process, use the ``moldesign.models.SQMPotential`` energy model to calculate the charges. Returns: Mapping[moldesign.Atom, units.Scalar[charge]]: AM1-BCC partial charges on each atom """ return _antechamber_calc_charges(mol, 'bcc', 'am1-bcc', kwargs) @utils.kwargs_from(mdt.compute.run_job) def calc_gasteiger_charges(mol, **kwargs): """Calculate gasteiger charges Args: mol (moldesign.Molecule): assign partial charges to this molecule Returns: Mapping[moldesign.Atom, units.Scalar[charge]]: gasteiger partial charges on each atom (they will be stored at ``mol.properties['gasteiger']``) """ return _antechamber_calc_charges(mol, 'gas', 'gasteiger', kwargs) def _antechamber_calc_charges(mol, ambname, chargename, kwargs): charge = utils.if_not_none(mol.charge, 0) command = 'antechamber -fi mol2 -i mol.mol2 -fo mol2 -o out.mol2 -c %s -an n'%ambname if charge != 0: command += ' -nc %d' % charge.value_in(u.q_e) def finish_job(job): """Callback to complete the job""" lines = iter(job.get_output('out.mol2').read().split('\n')) charges = {} line = next(lines) while line.strip()[:len('@<TRIPOS>ATOM')] != '@<TRIPOS>ATOM': line = next(lines) line = next(lines) while line.strip()[:len('@<TRIPOS>BOND')] != '@<TRIPOS>BOND': fields = line.split() idx = int(fields[0])-1 assert mol.atoms[idx].name == fields[1] charges[mol.atoms[idx]] = u.q_e*float(fields[-1]) line = next(lines) mol.properties[chargename] = AtomicProperties(charges) return charges job = packages.antechamber.make_job(command=command, name="%s, %s" % (chargename, mol.name), inputs={'mol.mol2': mol.write(format='mol2')}, when_finished=finish_job) return compute.run_job(job, _return_result=True, **kwargs) @utils.kwargs_from(mdt.compute.run_job) def build_bdna(sequence, **kwargs): """ Uses Ambertools' Nucleic Acid Builder to build a 3D double-helix B-DNA structure. Args: sequence (str): DNA sequence for one of the strands (a complementary sequence will automatically be created) **kwargs: arguments for :meth:`compute.run_job` Returns: moldesign.Molecule: B-DNA double helix """ print('DeprecationWarning: build_bdna is deprecated. ' "Use `build_dna_helix(sequence, helix_type='b')` instead") return build_dna_helix(sequence, helix_type='b', **kwargs) @utils.kwargs_from(mdt.compute.run_job) def build_dna_helix(sequence, helix_type='B', **kwargs): """ Uses Ambertools' Nucleic Acid Builder to build a 3D DNA double-helix. Args: sequence (str): DNA sequence for one of the strands (a complementary sequence will automatically be created) helix_type (str): Type of helix - 'A'=Arnott A-DNA 'B'=B-DNA (from standard templates and helical params), 'LB'=Langridge B-DNA, 'AB'=Arnott B-DNA, 'SB'=Sasisekharan left-handed B-DNA **kwargs: arguments for :meth:`compute.run_job` All helix types except 'B' are taken from fiber diffraction data (see the refernce for details) Returns: moldesign.Molecule: B-DNA double helix References: See NAB / AmberTools documentation: http://ambermd.org/doc12/Amber16.pdf, pg 771-2 """ infile = ['molecule m;'] if helix_type.lower() == 'b': infile.append('m = bdna( "%s" );' % sequence.lower()) else: infile.append('m = fd_helix( "%sdna", "%s", "dna" );' % (helix_type.lower(), sequence.lower())) infile.append('putpdb( "helix.pdb", m, "-wwpdb");\n') def finish_job(job): mol = mdt.fileio.read_pdb(job.get_output('helix.pdb').open(), assign_ccd_bonds=False) if mol.num_chains == 1: assert mol.num_residues % 2 == 0 oldchain = mol.chains[0] oldchain.name = oldchain.pdbindex = oldchain.pdbname = 'A' newchain = mdt.Chain('B') for residue in mol.residues[mol.num_residues//2:]: residue.chain = newchain mol = mdt.Molecule(mol) mdt.helpers.assign_biopolymer_bonds(mol) mol.name = '%s-DNA Helix: %s' % (helix_type.upper(), sequence) return mol job = packages.nab.make_job(command='nab -o buildbdna build.nab && ./buildbdna', inputs={'build.nab': '\n'.join(infile)}, name='NAB_build_dna', when_finished=finish_job) return mdt.compute.run_job(job, _return_result=True, **kwargs)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/opsin_interface.py
.py
1,509
44
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import moldesign as mdt from .. import utils from ..compute import packages @utils.kwargs_from(mdt.compute.run_job) def name_to_smiles(name, **kwargs): command = 'opsin -osmi input.txt output.txt' def finish_job(job): smistring = job.get_output('output.txt').read().strip() if not smistring: raise ValueError('Could not parse chemical name "%s"' % name) else: return smistring job = packages.opsin.make_job(command=command, name="opsin, %s" % name, inputs={'input.txt': name + '\n'}, when_finished=finish_job) return mdt.compute.run_job(job, _return_result=True, **kwargs)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/symmol_interface.py
.py
10,144
260
from __future__ import print_function, absolute_import, division from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re import numpy as np import moldesign as mdt from .. import units as u from .. import utils from ..compute import packages IMAGE = 'symmol' #@doi('10.1107/S0021889898002180') def run_symmol(mol, tolerance=0.1 * u.angstrom): import fortranformat line_writer = fortranformat.FortranRecordWriter('(a6,i2,6f9.5)') if mol.num_atoms == 2: return _get_twoatom_symmetry(mol) infile = ['1.0 1.0 1.0 90.0 90.0 90.0', # line 1: indicates XYZ coordinates # line 2: numbers indicate: mass weighted moment of inertia, # tolerance interpretation, tolerance value, # larger tolerance value (not used) '1 0 %f 0.0' % tolerance.value_in(u.angstrom)] for atom in mol.atoms: infile.append(line_writer.write((atom.element, 1, atom.x.value_in(u.angstrom), atom.y.value_in(u.angstrom), atom.z.value_in(u.angstrom), 0.0, 0.0, 0.0))) infile.append('') command = 'symmol < sym.in' inputs = {'sym.in': '\n'.join(infile)} job = packages.symmol.make_job(command=command, inputs=inputs, name="symmol, %s" % mol.name) job = mdt.compute.run_job(job) data = parse_output(mol, job.get_output('symmol.out')) _prune_symmetries(data) symm = mdt.geom.MolecularSymmetry( mol, data.symbol, data.rms, orientation=get_aligned_coords(mol, data), elems=data.elems, _job=job) return symm def _get_twoatom_symmetry(mol): """ Symmol doesn't deal with continuous symmetries, so this is hardcoded """ com_pos = mol.positions-mol.com ident = mdt.geom.SymmetryElement(mol, idx=0, symbol='C1', matrix=np.identity(3), csm=0.0*u.angstrom, max_diff=0.0*u.angstrom) # Note: for a continuous symmetry, so the 'matrix' should really be an infinitesimal transform. # This doesn't come up a lot practically, so we just put a small generator here instead. # The rotation is through an irrational angle so that it does in fact generate the full # symmetry group transmat = mdt.external.transformations.rotation_matrix(1/np.sqrt(20), com_pos[0]) axis_rot = mdt.geom.SymmetryElement(mol, idx=1, symbol='Cinf_v', matrix=transmat[:3,:3], csm=0.0*u.angstrom, max_diff=0.0*u.angstrom) elems = [ident, axis_rot] # This is for the mirror plane / inversion center between the two atoms if mol.atoms[0].atnum == mol.atoms[1].atnum and mol.atoms[0].mass == mol.atoms[1].mass: reflmat = mdt.external.transformations.reflection_matrix([0,0,0], com_pos[0]) elems.append(mdt.geom.SymmetryElement(mol, idx=2, symbol='Cs', matrix=reflmat[:3,:3], csm=0.0*u.default.length, max_diff=0.0*u.default.length)) elems.append(mdt.geom.SymmetryElement(mol, idx=2, symbol='Ci', matrix=-1 * np.identity(3), csm=0.0*u.default.length, max_diff=0.0*u.default.length)) term_symbol = 'Dinf_h' else: term_symbol = axis_rot.symbol symm = mdt.geom.MolecularSymmetry(mol, term_symbol, 0.0 * u.default.length, orientation=com_pos, elems=elems) return symm def _prune_symmetries(data): """ Remove identical symmetries """ found = {} for elem in data.elems: found.setdefault(elem.symbol, []) for otherelem in found[elem.symbol]: if (np.abs(elem.matrix.T - otherelem.matrix) < 1e-11).all(): break else: found[elem.symbol].append(elem) newelems = [] for val in found.values(): newelems.extend(val) data.elems = newelems MATRIXSTRING = 'ORTHOGONALIZATION MATRIX'.split() ELEMENTSTRING = 'Symmetry element its CSM and Max.Diff. Symmetry element its CSM and Max.Diff.'.split() TRANSFORMATIONSTRING = 'SYMMETRY GROUP MATRICES'.split() NOSYMM = 'NO SYMMETRY EXISTS WITHIN GIVEN TOLERANCE'.split() ELEMPARSER = re.compile('(\d+)\) \[(...)\]\s+(\S+)\s+([\-0-9\.]+)\s+([\-0-9\.]+)') # this regex parses '1) [E ] x,y,z 0.0000 0.0000' -> [1, 'E ', 'x,y,z','0.0000','0.0000'] MATRIXPARSER = re.compile('(\d+)\s+CSM =\s+([\d\.]+)\s+MAX. DIFF. \(Angstrom\)=([\d\.]+)\s+TYPE (\S+)') # this parses ' 4 CSM = 0.06 MAX. DIFF. (Angstrom)=0.0545 TYPE C3' -> [4, 0.06, 0.545, C3] def parse_output(mol, outfile): lines = iter(outfile) data = utils.DotDict() while True: l = next(lines) fields = l.split() if fields == NOSYMM: data.symbol = 'C1' data.rms = data.cms = 0.0 * u.angstrom data.elems = [] data.orthmat = np.identity(3) return data elif fields == MATRIXSTRING: # get coordinates along principal axes data.orthmat = np.zeros((3, 3)) for i in range(3): data.orthmat[i] = list(map(float, next(lines).split())) elif fields[:2] == 'Schoenflies symbol'.split(): data.symbol = fields[3] data.csm = float(fields[6]) * u.angstrom data.rms = float(fields[-1]) * u.angstrom elif fields == ELEMENTSTRING: data.elems = [] while True: try: l = next(lines) except StopIteration: break if l.strip() == '': break parsed = ELEMPARSER.findall(l) for p in parsed: elem = mdt.geom.SymmetryElement(mol, idx=int(p[0])-1, symbol=p[1].strip(), matrix=_string_to_matrix(p[2]), csm=float(p[3]), max_diff=float(p[4]) * u.angstrom) if elem.symbol == 'E': elem.symbol = 'C1' data.elems.append(elem) break elif fields == TRANSFORMATIONSTRING: data.elems = [] l = next(lines) while True: while l.strip() == '': try: l = next(lines) except StopIteration: return data eleminfo = MATRIXPARSER.findall(l) if not eleminfo: return data # we're done assert len(eleminfo) == 1 info = eleminfo[0] matrix = np.zeros((3, 3)) for i in range(3): l = next(lines) matrix[i, :] = list(map(float, l.split())) e = mdt.geom.SymmetryElement(mol, matrix=matrix, idx=int(info[0])-1, csm=float(info[1]) * u.angstrom, max_diff=float(info[2]) * u.angstrom, symbol=info[3]) if e.symbol == 'E': e.symbol = 'C1' e.matrix = matrix data.elems.append(e) l = next(lines) return data DIMNUMS = {'x': 0, 'y': 1, 'z': 2} TRANSFORM_PARSER = re.compile('([+\-]?)([0-9\.]*)([xyz])') # this regex transforms '3z-5.3x+y' -> [('','3','z'),('-','5.3','x'),('+','','y')] def _string_to_matrix(string): """ Symmol often returns a symmetry operation as something like "+x,-z,+y" This means that the x axis is mapped onto x, y axis is mapped onto -z, and +y is mapped onto z. We translate this into a transformation matrix here. :param string: A string representing axis mapping, of the form 'x,-z,x+y' :return: 3x3 transformation matrix """ mat = [] for dim in string.split(','): row = np.zeros(3) components = TRANSFORM_PARSER.findall(dim) for sign, factor, dimname in components: if factor.strip() == '': factor = '1' idim = DIMNUMS[dimname] row[idim] = float(sign + factor) row = row / np.sqrt(row.dot(row)) # normalize mat.append(row) return np.array(mat) def get_aligned_coords(mol, data): com = mol.com centerpos = mol.positions - com orthcoords = (centerpos.T.ldot(data.orthmat)).T return orthcoords
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/pdbfixer_interface.py
.py
11,774
312
from __future__ import print_function, absolute_import, division import string from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from past.builtins import basestring import io import re import numpy as np import moldesign as mdt from .. import units as u from ..compute import packages from ..utils import exports from . import openmm as opm @exports def mol_to_fixer(mol): import pdbfixer fixer = pdbfixer.PDBFixer(pdbfile=io.StringIO(mol.write(format='pdb'))) return fixer @exports def fixer_to_mol(f): return opm.topology_to_mol(f.topology, positions=f.positions) @packages.pdbfixer.runsremotely def mutate_residues(mol, residue_map): """ Create a mutant with point mutations (returns a copy - leaves the original unchanged) Mutations may be specified in one of two ways: 1) As a dictionary mapping residue objects to the 3-letter name of the amino acid they will be mutated into: ``{mol.residues[3]: 'ALA'}`` 2) As a list of mutation strings: ``['A43M', '332S', 'B.53N']`` (see below) Mutation strings have the form: ``[chain name .][initial amino acid code](residue index)(mutant amino acid code)`` If the chain name is omited, the mutation will be applied to all chains (if possible). The initial amino acid code may also be omitted. Examples: >>> mutate_residues(mol, {mol.residues[5]: 'ALA'}) # mutate residue 5 to ALA >>> mutate_residues(mol, 'A43M') # In all chains with ALA43 mutate it to MET43 >>> mutate_residues(mol, ['A.332S', 'B.120S']) # Mutate Chain A res 332 and B 120 to SER >>> mutate_residues(mol, ['B.C53N']) # Mutate Cysteine 53 in chain B to Asparagine Args: mol (moldesign.Molecule): molecule to create mutant from residue_map (Dict[moldesign.Residue:str] OR List[str]): list of mutations (see above for allowed formats) Returns: moldesign.Molecule: the mutant """ fixer = mol_to_fixer(mol) chain_mutations = {} mutation_strs = [] if not hasattr(residue_map, 'items'): residue_map = _mut_strs_to_map(mol, residue_map) if not residue_map: raise ValueError("No mutations specified!") for res, newres in residue_map.items(): chain_mutations.setdefault(res.chain.pdbname, {})[res] = residue_map[res] mutation_strs.append(_mutation_as_str(res, newres)) for chainid, mutations in chain_mutations.items(): mutstrings = ['%s-%d-%s' % (res.resname, res.pdbindex, newname) for res, newname in mutations.items()] fixer.applyMutations(mutstrings, chainid) temp_mutant = fixer_to_mol(fixer) _pdbfixer_chainnames_to_letter(temp_mutant) # PDBFixer reorders atoms, so to keep things consistent, we'll graft the mutated residues # into an MDT structure assert temp_mutant.num_residues == mol.num_residues # shouldn't change number of residues residues_to_copy = [] old_residue_map = {} for oldres, mutant_res in zip(mol.residues, temp_mutant.residues): if oldres in residue_map: residues_to_copy.append(mutant_res) mutant_res.mol = None mutant_res.chain = oldres.chain old_residue_map[oldres] = mutant_res else: residues_to_copy.append(oldres) # Bonds between original and mutated backbone atoms will be removed when # creating the new mutant molecule because the original and mutated atoms # reference different molecules. # # Make a list of bonds referencing atoms in the original molecule that # is used later to recreate bonds between original and mutated backbone # atoms. orig_bonds = [] for res in residues_to_copy: if not res.backbone: continue for atom in res.backbone: for bond_atom in atom.bond_graph: if bond_atom.residue in residue_map: mutant_res = old_residue_map[bond_atom.residue] mutant_atom = mutant_res.atoms[bond_atom.name] orig_bonds.append((atom,mutant_atom,atom.bond_graph[bond_atom])) metadata = {'origin': mol.metadata.copy(), 'mutations': mutation_strs} mutant_mol = mdt.Molecule(residues_to_copy, name='Mutant of "%s"' % mol, metadata=metadata) # Add bonds between the original and mutated backbone atoms. for atom,mut_atom,order in orig_bonds: chainID = atom.chain.name residues = mutant_mol.chains[chainID].residues new_atom = residues[atom.residue.name].atoms[atom.name] new_mut_atom = residues[mut_atom.residue.name].atoms[mut_atom.name] new_atom.bond_to(new_mut_atom, order) return mutant_mol def _pdbfixer_chainnames_to_letter(pdbfixermol): for chain in pdbfixermol.chains: try: if chain.name.isdigit(): chain.name = string.ascii_uppercase[int(chain.name)-1] except (ValueError, TypeError, IndexError): continue # not worth crashing over def _mutation_as_str(res, newres): """ Create mutation string for storage as metadata. Note that this will include the name of the chain, if available, as a prefix: Examples: >>> res = mdt.Residue(resname='ALA', pdbindex='23', chain=mdt.Chain(name=None)) >>> _mutation_as_str(res, 'TRP') 'A23W' >>> res = mdt.Residue(resname='ALA', pdbindex='23', chain=mdt.Chain(name='C')) >>> _mutation_as_str(res, 'TRP') 'C.A23W' Args: res (moldesign.Residue): residue to be mutated newres (str): 3-letter residue code for new amino acid Returns: str: mutation string References: Nomenclature for the description of sequence variations J.T. den Dunnen, S.E. Antonarakis: Hum Genet 109(1): 121-124, 2001 Online at http://www.hgmd.cf.ac.uk/docs/mut_nom.html#protein """ try: # tries to describe mutation using standard mutstr = '%s%s%s' % (res.code, res.pdbindex, mdt.data.RESIDUE_ONE_LETTER.get(newres, '?')) if res.chain.pdbname: mutstr = '%s.%s' % (res.chain.pdbname, mutstr) return mutstr except (TypeError, ValueError) as e: print('WARNING: failed to construct mutation code: %s' % e) return '%s -> %s' % (str(res), newres) MUT_RE = re.compile(r'(.*\.)?([^\d]*)(\d+)([^\d]+)') # parses mutation strings def _mut_strs_to_map(mol, strs): if isinstance(strs, basestring): strs = [strs] mutmap = {} for s in strs: match = MUT_RE.match(s) if match is None: raise ValueError("Failed to parse mutation string '%s'" % s) chainid, initialcode, residx, finalcode = match.groups() if chainid is not None: parent = mol.chains[chainid[:-1]] else: parent = mol # queries the whole molecule newresname = mdt.data.RESIDUE_CODE_TO_NAME[finalcode] query = {'pdbindex': int(residx)} if initialcode: query['code'] = initialcode residues = parent.get_residues(**query) if len(residues) == 0: raise ValueError("Mutation '%s' did not match any residues" % s) for res in residues: assert res not in mutmap, "Multiple mutations for %s" % res mutmap[res] = newresname return mutmap @packages.pdbfixer.runsremotely def add_water(mol, min_box_size=None, padding=None, ion_concentration=0.0, neutralize=True, positive_ion='Na+', negative_ion='Cl-'): """ Solvate a molecule in a water box with optional ions Args: mol (moldesign.Molecule): solute molecule min_box_size (u.Scalar[length] or u.Vector[length]): size of the water box - either a vector of x,y,z dimensions, or just a uniform cube length. Either this or ``padding`` (or both) must be passed padding (u.Scalar[length]): distance to edge of water box from the solute in each dimension neutralize (bool): add ions to neutralize solute charge (in addition to specified ion concentration) positive_ion (str): type of positive ions to add, if needed. Allowed values (from OpenMM modeller) are Cs, K, Li, Na (the default) and Rb negative_ion (str): type of negative ions to add, if needed. Allowed values (from OpenMM modeller) are Cl (the default), Br, F, and I ion_concentration (float or u.Scalar[molarity]): ionic concentration in addition to whatever is needed to neutralize the solute. (if float is passed, we assume the number is Molar) Returns: moldesign.Molecule: new Molecule object containing both solvent and solute """ import pdbfixer if padding is None and min_box_size is None: raise ValueError('Solvate arguments: must pass padding or min_box_size or both.') # add +s and -s to ion names if not already present if positive_ion[-1] != '+': assert positive_ion[-1] != '-' positive_ion += '+' if negative_ion[-1] != '-': assert negative_ion[-1] != '+' negative_ion += '-' ion_concentration = u.MdtQuantity(ion_concentration) if ion_concentration.dimensionless: ion_concentration *= u.molar ion_concentration = opm.pint2simtk(ion_concentration) # calculate box size - in each dimension, use the largest of min_box_size or # the calculated padding boxsize = np.zeros(3) * u.angstrom if min_box_size: boxsize[:] = min_box_size if padding: ranges = mol.positions.max(axis=0) - mol.positions.min(axis=0) for idim, r in enumerate(ranges): boxsize[idim] = max(boxsize[idim], r+padding) assert (boxsize >= 0.0).all() modeller = opm.mol_to_modeller(mol) # Creating my fixers directly from Topology objs ff = pdbfixer.PDBFixer.__dict__['_createForceField'](None, modeller.getTopology(), True) modeller.addSolvent(ff, boxSize=opm.pint2simtk(boxsize), positiveIon=positive_ion, negativeIon=negative_ion, ionicStrength=ion_concentration, neutralize=neutralize) solv_tempmol = opm.topology_to_mol(modeller.getTopology(), positions=modeller.getPositions(), name='%s with water box' % mol.name) _pdbfixer_chainnames_to_letter(solv_tempmol) # PDBFixer reorders atoms, so to keep things consistent, we'll graft the mutated residues # into an MDT structure newmol_atoms = [mol] for residue in solv_tempmol.residues[mol.num_residues:]: newmol_atoms.append(residue) newmol = mdt.Molecule(newmol_atoms, name="Solvated %s" % mol, metadata={'origin':mol.metadata}) assert newmol.num_atoms == solv_tempmol.num_atoms assert newmol.num_residues == solv_tempmol.num_residues return newmol
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/biopython_interface.py
.py
5,289
151
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import string import Bio.PDB import Bio.PDB.MMCIF2Dict import numpy as np import moldesign as mdt from moldesign import units as u from moldesign.helpers.pdb import BioAssembly from moldesign.utils import exports @exports def biopython_to_mol(struc): """Convert a biopython PDB structure to an MDT molecule. Note: Biopython doesn't deal with bond data, so no bonds will be present in the Molecule Args: struc (Bio.PDB.Structure.Structure): Biopython PDB structure to convert Returns: moldesign.Molecule: converted molecule """ # TODO: assign bonds using 1) CONECT records, 2) residue templates, 3) distance newatoms = [] backup_chain_names = list(string.ascii_uppercase) for chain in struc.get_chains(): tmp, pdbidx, pdbid = chain.get_full_id() if not pdbid.strip(): pdbid = backup_chain_names.pop() newchain = mdt.Chain(pdbname=pdbid.strip()) for residue in chain.get_residues(): newresidue = mdt.Residue(pdbname=residue.resname.strip(), pdbindex=residue.id[1]) newchain.add(newresidue) for atom in residue.get_atom(): elem = atom.element if len(elem) == 2: elem = elem[0] + elem[1].lower() newatom = mdt.Atom(element=elem, name=atom.get_name(), pdbname=atom.get_name(), pdbindex=atom.get_serial_number()) newatom.position = atom.coord * u.angstrom newresidue.add(newatom) newatoms.append(newatom) return mdt.Molecule(newatoms, name=struc.get_full_id()[0]) def get_mmcif_assemblies(fileobj=None, mmcdata=None): """Parse an mmCIF file, return biomolecular assembly specifications Args: fileobj (file-like): File-like object for the PDB file (this object will be rewound before returning) mmcdata (dict): dict version of complete mmCIF data structure (if passed, this will not be read again from fileobj) Returns: Mapping[str, BioAssembly]: dict mapping assembly ids to BioAssembly instances """ if mmcdata is None: mmcdata = get_mmcif_data(fileobj) if '_pdbx_struct_assembly.id' not in mmcdata: return {} # no assemblies present # Get assembly metadata ids = mmcdata['_pdbx_struct_assembly.id'] details = mmcdata['_pdbx_struct_assembly.details'] chains = mmcdata['_pdbx_struct_assembly_gen.asym_id_list'] opers = mmcdata['_pdbx_struct_assembly_gen.oper_expression'] transform_ids = mmcdata['_pdbx_struct_oper_list.id'] # Get matrix transformations tmat = np.zeros((4, 4)).tolist() for i in range(3): # construct displacement vector tmat[i][3] = mmcdata['_pdbx_struct_oper_list.vector[%d]' % (i+1)] for i, j in itertools.product(range(0, 3), range(0, 3)): # construct rotation matrix tmat[i][j] = mmcdata['_pdbx_struct_oper_list.matrix[%d][%d]' % (i+1, j+1)] transforms = _make_transform_dict(tmat, transform_ids) # Make sure it's a list if not isinstance(ids, list): ids = [ids] details = [details] chains = [chains] opers = [opers] # now create the assembly specifications assemblies = {} for id, detail, chainlist, operlist in zip(ids, details, chains, opers): assert id not in assemblies transforms = [transforms[i] for i in operlist.split(',')] assemblies[id] = BioAssembly(detail, chainlist.split(','), transforms) return assemblies def _make_transform_dict(tmat, transform_ids): if isinstance(transform_ids, list): for i, j in itertools.product(range(0, 3), range(0, 4)): tmat[i][j] = list(map(float, tmat[i][j])) tmat[3][3] = [1.0]*len(transform_ids) tmat[3][0] = tmat[3][1] = tmat[3][2] = [0.0]*len(transform_ids) tmat = np.array(tmat) transforms = {id: tmat[:, :, i] for i, id in enumerate(transform_ids)} else: for i, j in itertools.product(range(0, 4), range(0, 4)): tmat[i][j] = float(tmat[i][j]) tmat[3][3] = 1.0 tmat = np.array(tmat) transforms = {transform_ids: tmat} return transforms def get_mmcif_data(fileobj): mmcdata = Bio.PDB.MMCIF2Dict.MMCIF2Dict(fileobj) fileobj.seek(0) # rewind for future access return mmcdata
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/tleap_interface.py
.py
12,300
321
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from past.builtins import basestring import os import re import tempfile import moldesign as mdt from . import ambertools from .. import units as u from .. import compute from .. import utils from .. import forcefields from ..compute import packages IMAGE = 'ambertools' @utils.kwargs_from(mdt.compute.run_job) def create_ff_parameters(mol, charges='esp', baseff='gaff2', **kwargs): """Parameterize ``mol``, typically using GAFF parameters. This will both assign a forcefield to the molecule (at ``mol.ff``) and produce the parameters so that they can be used in other systems (e.g., so that this molecule can be simulated embedded in a larger protein) Note: 'am1-bcc' and 'gasteiger' partial charges will be automatically computed if necessary. Other charge types must be precomputed. Args: mol (moldesign.Molecule): charges (str or dict): what partial charges to use? Can be a dict (``{atom:charge}``) OR a string, in which case charges will be read from ``mol.properties.[charges name]``; typical values will be 'esp', 'mulliken', 'am1-bcc', etc. Use 'zero' to set all charges to 0 (for QM/MM and testing) baseff (str): Name of the gaff-like forcefield file (default: gaff2) Returns: TLeapForcefield: Forcefield object for this residue """ # Check that there's only 1 residue, give it a name assert mol.num_residues == 1 if mol.residues[0].resname is None: mol.residues[0].resname = 'UNL' print('Assigned residue name "UNL" to %s' % mol) resname = mol.residues[0].resname # check that atoms have unique names if len(set(atom.name for atom in mol.atoms)) != mol.num_atoms: raise ValueError('This molecule does not have uniquely named atoms, cannot assign FF') if charges == 'am1-bcc' and 'am1-bcc' not in mol.properties: ambertools.calc_am1_bcc_charges(mol) elif charges == 'gasteiger' and 'gasteiger' not in mol.properties: ambertools.calc_gasteiger_charges(mol) elif charges == 'esp' and 'esp' not in mol.properties: # TODO: use NWChem ESP to calculate raise NotImplementedError() if charges == 'zero': charge_array = [0.0 for atom in mol.atoms] elif isinstance(charges, basestring): charge_array = u.array([mol.properties[charges][atom] for atom in mol.atoms]) if not charge_array.dimensionless: # implicitly convert floats to fundamental charge units charge_array = charge_array.to(u.q_e).magnitude else: charge_array = [charges[atom] for atom in mol.atoms] inputs = {'mol.mol2': mol.write(format='mol2'), 'mol.charges': '\n'.join(map(str, charge_array))} cmds = ['antechamber -i mol.mol2 -fi mol2 -o mol_charged.mol2 ' ' -fo mol2 -c rc -cf mol.charges -rn %s' % resname, 'parmchk -i mol_charged.mol2 -f mol2 -o mol.frcmod', 'tleap -f leap.in', 'sed -e "s/tempresname/%s/g" mol_rename.lib > mol.lib' % resname] base_forcefield = forcefields.TLeapLib(baseff) inputs['leap.in'] = '\n'.join(["source leaprc.%s" % baseff, "tempresname = loadmol2 mol_charged.mol2", "fmod = loadamberparams mol.frcmod", "check tempresname", "saveoff tempresname mol_rename.lib", "saveamberparm tempresname mol.prmtop mol.inpcrd", "quit\n"]) def finish_job(j): leapcmds = ['source leaprc.gaff2'] files = {} for fname, f in j.glob_output("*.lib").items(): leapcmds.append('loadoff %s' % fname) files[fname] = f for fname, f in j.glob_output("*.frcmod").items(): leapcmds.append('loadAmberParams %s' % fname) files[fname] = f param = forcefields.TLeapForcefield(leapcmds, files) param.add_ff(base_forcefield) param.assign(mol) return param job = packages.tleap.make_job(command=' && '.join(cmds), inputs=inputs, when_finished=finish_job, name="GAFF assignment: %s" % mol.name) return mdt.compute.run_job(job, _return_result=True, **kwargs) class AmberParameters(object): """ Forcefield parameters for a system in amber ``prmtop`` format """ def __getstate__(self): state = self.__dict__.copy() state['job'] = None return state def __init__(self, prmtop, inpcrd, job=None): self.prmtop = prmtop self.inpcrd = inpcrd self.job = job def to_parmed(self): import parmed prmtoppath = os.path.join(tempfile.mkdtemp(), 'prmtop') self.prmtop.put(prmtoppath) pmd = parmed.load_file(prmtoppath) return pmd @utils.kwargs_from(compute.run_job) def _run_tleap_assignment(mol, leapcmds, files=None, **kwargs): """ Drives tleap to create a prmtop and inpcrd file. Specifically uses the AmberTools 16 tleap distribution. Defaults are as recommended in the ambertools manual. Args: mol (moldesign.Molecule): Molecule to set up leapcmds (List[str]): list of the commands to load the forcefields files (List[pyccc.FileReference]): (optional) list of additional files to send **kwargs: keyword arguments to :meth:`compute.run_job` References: Ambertools Manual, http://ambermd.org/doc12/Amber16.pdf. See page 33 for forcefield recommendations. """ leapstr = leapcmds[:] inputs = {} if files is not None: inputs.update(files) inputs['input.pdb'] = mol.write(format='pdb') leapstr.append('mol = loadpdb input.pdb\n' "check mol\n" "saveamberparm mol output.prmtop output.inpcrd\n" "savepdb mol output.pdb\n" "quit\n") inputs['input.leap'] = '\n'.join(leapstr) job = packages.tleap.make_job(command='tleap -f input.leap', inputs=inputs, name="tleap, %s" % mol.name) return compute.run_job(job, **kwargs) def _prep_for_tleap(mol): """ Returns a modified *copy* that's been modified for input to tleap Makes the following modifications: 1. Reassigns all residue IDs 2. Assigns tleap-appropriate cysteine resnames """ change = False clean = mdt.Molecule(mol.atoms) for residue in clean.residues: residue.pdbindex = residue.index+1 if residue.resname == 'CYS': # deal with cysteine states if 'SG' not in residue.atoms or 'HG' in residue.atoms: continue # sulfur's missing, we'll let tleap create it else: sulfur = residue.atoms['SG'] if sulfur.formal_charge == -1*u.q_e: residue.resname = 'CYM' change = True continue # check for a reasonable hybridization state if sulfur.formal_charge != 0 or sulfur.num_bonds not in (1, 2): raise ValueError("Unknown sulfur hybridization state for %s" % sulfur) # check for a disulfide bond for otheratom in sulfur.bonded_atoms: if otheratom.residue is not residue: if otheratom.name != 'SG' or otheratom.residue.resname not in ('CYS', 'CYX'): raise ValueError('Unknown bond from cysteine sulfur (%s)' % sulfur) # if we're here, this is a cystine with a disulfide bond print('INFO: disulfide bond detected. Renaming %s from CYS to CYX' % residue) sulfur.residue.resname = 'CYX' clean._rebuild_from_atoms() return clean ATOMSPEC = re.compile(r'\.R<(\S+) ([\-0-9]+)>\.A<(\S+) ([\-0-9]+)>') def _parse_tleap_errors(job, molin): # TODO: special messages for known problems (e.g. histidine) msg = [] unknown_res = set() # so we can print only one error per unkonwn residue lineiter = iter(job.stdout.split('\n')) offset = utils.if_not_none(molin.residues[0].pdbindex, 1) reslookup = {str(i+offset): r for i,r in enumerate(molin.residues)} def _atom_from_re(s): resname, residx, atomname, atomidx = s r = reslookup[residx] a = r[atomname] return a def unusual_bond(l): atomre1, atomre2 = ATOMSPEC.findall(l) try: a1, a2 = _atom_from_re(atomre1), _atom_from_re(atomre2) except KeyError: a1 = a2 = None r1 = reslookup[atomre1[1]] r2 = reslookup[atomre2[1]] return forcefields.errors.UnusualBond(l, (a1, a2), (r1, r2)) def _parse_tleap_logline(line): fields = line.split() if fields[0:2] == ['Unknown', 'residue:']: # EX: "Unknown residue: 3TE number: 499 type: Terminal/beginning" res = molin.residues[int(fields[4])] unknown_res.add(res) return forcefields.errors.UnknownResidue(line, res) elif fields[:4] == 'Warning: Close contact of'.split(): # EX: "Warning: Close contact of 1.028366 angstroms between .R<DC5 1>.A<HO5' 1> and .R<DC5 81>.A<P 9>" return unusual_bond(line) elif fields[:6] == 'WARNING: There is a bond of'.split(): # Matches two lines, EX: # "WARNING: There is a bond of 34.397700 angstroms between:" # "------- .R<DG 92>.A<O3' 33> and .R<DG 93>.A<P 1>" nextline = next(lineiter) return unusual_bond(line+nextline) elif fields[:5] == 'Created a new atom named:'.split(): # EX: "Created a new atom named: P within residue: .R<DC5 81>" residue = reslookup[fields[-1][:-1]] if residue in unknown_res: return None # suppress atoms from an unknown res ... atom = residue[fields[5]] return forcefields.errors.UnknownAtom(line, residue, atom) elif fields[:2] == ('FATAL:', 'Atom'): # EX: "FATAL: Atom .R<ARQ 1>.A<C30 6> does not have a type." assert fields[-5:] == "does not have a type.".split() atom = _atom_from_re(ATOMSPEC.findall(line)[0]) return forcefields.errors.UnknownAtom(line, atom.residue, atom) elif (fields[:5] == '** No torsion terms for'.split() or fields[:5] == 'Could not find angle parameter:'.split() or fields[:5] == 'Could not find bond parameter for:'.split()): # EX: " ** No torsion terms for ca-ce-c3-hc" # EX: "Could not find bond parameter for: -" # EX: "Could not find angle parameter: - -" return forcefields.errors.MissingTerms(line.strip()) else: # ignore this line return None while True: try: line = next(lineiter) except StopIteration: break try: errmsg = _parse_tleap_logline(line) except (KeyError, ValueError): print("WARNING: failed to process TLeap message '%s'" % line) msg.append(forcefields.errors.ForceFieldMessage(line)) else: if errmsg is not None: msg.append(errmsg) return msg
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/__init__.py
.py
571
20
from . import ambertools from . import biopython_interface from . import nbo_interface from . import openbabel from . import openmm from . import opsin_interface from . import parmed_interface from . import pdbfixer_interface from . import pyscf_interface from . import symmol_interface from . import tleap_interface # These statements only import functions for python object conversion, # i.e. mol_to_[pkg] and [pkg]_to_mol from .biopython_interface import * from .openbabel import * from .openmm import * from .pyscf_interface import * from .parmed_interface import *
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/nbo_interface.py
.py
9,611
265
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import moldesign as mdt from .. import units as u from .. import utils SIGMA_UTF = u"\u03C3" PI_UTF = u"\u03C0" def run_nbo(mol, requests=('nlmo', 'nbo'), image='nbo', engine=None): wfn = mol.wfn inputs = {'in.47': make_nbo_input_file(mol, requests)} command = 'gennbo.i4.exe in.47' engine = utils.if_not_none(engine, mdt.compute.config.get_engine()) imagename = mdt.compute.get_image_path(image) job = engine.launch(imagename, command, inputs=inputs, name="nbo, %s" % mol.name) mdt.helpers.display_log(job.get_display_object(), "nbo, %s"%mol.name) job.wait() parsed_data = parse_nbo(job.get_output('FILE.10'), len(mol.wfn.aobasis)) for orbtype, data in parsed_data.items(): if orbtype[0] == 'P': # copy data from the orthogonal orbitals orthdata = parsed_data[orbtype[1:]] for key in 'bond_names iatom jatom stars bondnums num_bonded_atoms'.split(): data[key] = orthdata[key] data.occupations = [None for orb in data.coeffs] add_orbitals(mol, wfn, data, orbtype) wfn._nbo_job = job def add_orbitals(mol, wfn, orbdata, orbtype): orbs = [] for i in range(len(orbdata.coeffs)): bond = None atoms = [mol.atoms[orbdata.iatom[i] - 1]] if orbdata.bond_names[i] == 'RY': bname = '%s Ryd*' % atoms[0].name nbotype = 'rydberg' utf_name = bname elif orbdata.bond_names[i] == 'LP': bname = '%s lone pair' % atoms[0].name nbotype = 'lone pair' utf_name = bname elif orbdata.bond_names[i] == 'LV': bname = '%s lone vacancy' % atoms[0].name nbotype = 'lone vacancy' utf_name = bname elif orbdata.num_bonded_atoms[i] == 1: bname = '%s Core' % atoms[0].name nbotype = 'core' utf_name = bname else: atoms.append(mol.atoms[orbdata.jatom[i] - 1]) bond = mdt.Bond(*atoms) if orbdata.bondnums[i] == 1: # THIS IS NOT CORRECT nbotype = 'sigma' utf_type = SIGMA_UTF else: nbotype = 'pi' utf_type = PI_UTF bname = '%s%s (%s - %s)' % (nbotype, orbdata.stars[i], atoms[0].name, atoms[1].name) utf_name = '%s%s (%s - %s)' % (utf_type, orbdata.stars[i], atoms[0].name, atoms[1].name) name = '%s %s' % (bname, orbtype) orbs.append(mdt.Orbital(orbdata.coeffs[i], wfn=wfn, occupation=orbdata.occupations[i], atoms=atoms, name=name, nbotype=nbotype, bond=bond, unicode_name=utf_name, _data=orbdata)) return wfn.add_orbitals(orbs, orbtype=orbtype) def make_nbo_input_file(mol, requests): """ :param mol: :type mol: moldesign.molecules.Molecule :return: """ # Units: angstroms, hartrees wfn = mol.wfn orbs = wfn.molecular_orbitals nbofile = [] # TODO: check for open shell wfn (OPEN keyword) # TODO: check normalization, orthogonalization nbofile.append(" $GENNBO BODM NATOMS=%d NBAS=%d $END" % (mol.num_atoms, len(wfn.aobasis))) commands = ['NBOSUM'] for r in requests: commands.append('AO%s=W10' % r.upper()) if r[0] != 'P': commands.append('%s' % r.upper()) nbofile.append('$NBO %s $END' % (' '.join(commands))) nbofile.append("$COORD\n %s" % mol.name) for iatom, atom in enumerate(mol.atoms): #TODO: deal with pseudopotential electrons x, y, z = list(map(repr, atom.position.value_in(u.angstrom))) nbofile.append("%d %d %s %s %s" % (atom.atnum, atom.atnum, x, y, z)) nbofile.append("$END") nbofile.append("$BASIS") nbofile.append(' CENTER = ' + ' '.join(str(1+bfn.atom.index) for bfn in wfn.aobasis)) nbofile.append(" LABEL = " + ' '.join(str(AOLABELS[bfn.orbtype]) for bfn in wfn.aobasis)) nbofile.append('$END') #TODO: deal with CI wavefunctions ($WF keyword) nbofile.append('$OVERLAP') append_matrix(nbofile, wfn.aobasis.overlaps) nbofile.append('$END') nbofile.append('$DENSITY') append_matrix(nbofile, wfn.density_matrix) nbofile.append('$END') return '\n '.join(nbofile) def parse_nbo(f, nbasis): lines = f.__iter__() parsed = {} while True: try: l = next(lines) except StopIteration: break fields = l.split() if fields[1:5] == 'in the AO basis:'.split(): orbname = fields[0] assert orbname[-1] == 's' orbname = orbname[:-1] next(lines) if orbname[0] == 'P': # these are pre-orthogonal orbitals, it only prints the coefficients coeffs = _parse_wrapped_matrix(lines, nbasis) parsed[orbname] = utils.DotDict(coeffs=np.array(coeffs)) else: # there's more complete information available parsed[orbname] = read_orbital_set(lines, nbasis) return parsed def read_orbital_set(lineiter, nbasis): # First, get the actual matrix mat = _parse_wrapped_matrix(lineiter, nbasis) # First, occupation numbers occupations = list(map(float,_get_wrapped_separated_vals(lineiter, nbasis))) # Next, a line of things that always appear to be ones (for spin orbitals maybe?) oneline = _get_wrapped_separated_vals(lineiter, nbasis) for x in oneline: assert x == '1' # next is number of atoms involved in the bond num_bonded_atoms = list(map(int, _get_wrapped_separated_vals(lineiter, nbasis))) bond_names = _get_wrapped_separated_vals(lineiter, nbasis) # Next indicates whether real or virtual stars = _get_wrapped_column_vals(lineiter, nbasis) for s in stars: assert (s == '' or s == '*') # number of bonds between this pair of atoms bondnums = list(map(int, _get_wrapped_separated_vals(lineiter, nbasis))) # first atom index (1-based) iatom = list(map(int, _get_wrapped_separated_vals(lineiter, nbasis))) jatom = list(map(int, _get_wrapped_separated_vals(lineiter, nbasis))) # The rest appears to be 0 most of the time ... return utils.DotDict(coeffs=np.array(mat), iatom=iatom, jatom=jatom, bondnums=bondnums, bond_names=bond_names, num_bonded_atoms=num_bonded_atoms, stars=stars, occupations=occupations) def _parse_wrapped_matrix(lineiter, nbasis): mat = [] for i in range(nbasis): currline = list(map(float, _get_wrapped_separated_vals(lineiter, nbasis))) assert len(currline) == nbasis mat.append(currline) return mat def _get_wrapped_separated_vals(lineiter, nbasis): vals = [] while True: l = next(lineiter) vals.extend(l.split()) if len(vals) == nbasis: break assert len(vals) < nbasis return vals def _get_wrapped_column_vals(lineiter, nbasis): vals = [] while True: l = next(lineiter.next)[1:] lenl = len(l) for i in range(20): if lenl <= 3*i + 1: break vals.append(l[3*i: 3*i + 3].strip()) if len(vals) == nbasis: break assert len(vals) < nbasis return vals def append_matrix(l, mat): for row in mat: icol = 0 while icol < len(row): l.append(' ' + ' '.join(map(repr, row[icol:icol + 6]))) icol += 6 AOLABELS = {'s': 1, 'px': 101, 'py': 102, 'pz': 103, "dxx": 201, "dxy": 202, "dxz": 203, "dyy": 204, "dyz": 205, "dzz": 206, "fxxx": 301, "fxxy": 302, "fxxz": 303, "fxyy": 304, "fxyz": 305, "fxzz": 306, "fyyy": 307, "fyyz": 308, "fyzz": 309, "fzzz": 310, "gxxxx": 401, "gxxxy": 402, "gxxxz": 403, "gxxyy": 404, "gxxyz": 405, "gxxzz": 406, "gxyyy": 407, "gxyyz": 408, "gxyzz": 409, "gxzzz": 410, "gyyyy": 411, "gyyyz": 412, "gyyzz": 413, "gyzzz": 414, "gzzzz": 415, # end of cartesian # start of spherical: 'p(x)': 151, 'p(y)': 152, 'p(z)': 153, "d(xy)": 251, "d(xz)": 252, "d(yz)": 253, "d(x2-y2)": 254, "d(z2)": 255, "f(z(5z2-3r2))": 351, "f(x(5z2-r2))": 352, "f(y(5z2-r2))": 353, "f(z(x2-y2))": 354, "f(xyz)": 355, "f(x(x2-3y2))": 356, "f(y(3x2-y2))": 357}
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/openbabel.py
.py
10,502
321
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import string import moldesign as mdt from ..compute import packages from .. import units as u from ..utils import exports def read_stream(filelike, format, name=None): """ Read a molecule from a file-like object Note: Currently only reads the first conformation in a file Args: filelike: a file-like object to read a file from format (str): File format: pdb, sdf, mol2, bbll, etc. name (str): name to assign to molecule Returns: moldesign.Molecule: parsed result """ molstring = str(filelike.read()) # openbabel chokes on unicode return read_string(molstring, format, name=name) @packages.openbabel.runsremotely def read_string(molstring, format, name=None): """ Read a molecule from a file-like object Note: Currently only reads the first conformation in a file Args: molstring (str): string containing file contents format (str): File format: pdb, sdf, mol2, bbll, etc. name (str): name to assign to molecule Returns: moldesign.Molecule: parsed result """ import pybel as pb pbmol = pb.readstring(format, molstring) mol = pybel_to_mol(pbmol, name=name) return mol @packages.openbabel.runsremotely def write_string(mol, format): """ Create a file from the passed molecule Args: mol (moldesign.Molecule): molecule to write format (str): File format: pdb, sdf, mol2, bbll, etc. Returns: str: contents of the file References: https://openbabel.org/docs/dev/FileFormats/Overview.html """ pbmol = mol_to_pybel(mol) if format == 'smi': # TODO: always kekulize, never aromatic outstr = pbmol.write(format=format).strip() else: outstr = pbmol.write(format=format) return str(outstr) @packages.openbabel.runsremotely def guess_bond_orders(mol): """Use OpenBabel to guess bond orders using geometry and functional group templates. Args: mol (moldesign.Molecule): Molecule to perceive the bonds of Returns: moldesign.Molecule: New molecule with assigned bonds """ # TODO: pH, formal charges pbmol = mol_to_pybel(mol) pbmol.OBMol.PerceiveBondOrders() newmol = pybel_to_mol(pbmol) return newmol @packages.openbabel.runsremotely def add_hydrogen(mol): """Add hydrogens to saturate atomic valences. Args: mol (moldesign.Molecule): Molecule to saturate Returns: moldesign.Molecule: New molecule with all valences saturated """ pbmol = mol_to_pybel(mol) pbmol.OBMol.AddHydrogens() newmol = pybel_to_mol(pbmol, reorder_atoms_by_residue=True) mdt.helpers.assign_unique_hydrogen_names(newmol) return newmol @exports def mol_to_pybel(mdtmol): """ Translate a moldesign molecule object into a pybel molecule object. Note: The focus is on translating topology and biomolecular structure - we don't translate any metadata. Args: mdtmol (moldesign.Molecule): molecule to translate Returns: pybel.Molecule: translated molecule """ import openbabel as ob import pybel as pb obmol = ob.OBMol() obmol.BeginModify() atommap = {} resmap = {} for atom in mdtmol.atoms: obatom = obmol.NewAtom() obatom.SetAtomicNum(atom.atnum) atommap[atom] = obatom pos = atom.position.value_in(u.angstrom) obatom.SetVector(*pos) if atom.residue and atom.residue not in resmap: obres = obmol.NewResidue() resmap[atom.residue] = obres obres.SetChain(str(atom.chain.pdbname)[0] if atom.chain.pdbname else 'Z') obres.SetName(str(atom.residue.pdbname) if atom.residue.pdbname else 'UNL') obres.SetNum(str(atom.residue.pdbindex) if atom.residue.pdbindex else 0) else: obres = resmap[atom.residue] obres.AddAtom(obatom) obres.SetHetAtom(obatom, not atom.residue.is_standard_residue) obres.SetAtomID(obatom, str(atom.name)) obres.SetSerialNum(obatom, mdt.utils.if_not_none(atom.pdbindex, atom.index+1)) for atom in mdtmol.bond_graph: a1 = atommap[atom] for nbr, order in mdtmol.bond_graph[atom].items(): a2 = atommap[nbr] if a1.GetIdx() > a2.GetIdx(): obmol.AddBond(a1.GetIdx(), a2.GetIdx(), order) obmol.EndModify() pbmol = pb.Molecule(obmol) for atom in atommap: idx = atommap[atom].GetIdx() obatom = obmol.GetAtom(idx) obatom.SetFormalCharge(int(atom.formal_charge.value_in(u.q_e))) return pbmol @exports def pybel_to_mol(pbmol, reorder_atoms_by_residue=False, primary_structure=True, **kwargs): """ Translate a pybel molecule object into a moldesign object. Note: The focus is on translating topology and biomolecular structure - we don't translate any metadata. Args: pbmol (pybel.Molecule): molecule to translate reorder_atoms_by_residue (bool): change atom order so that all atoms in a residue are stored contiguously primary_structure (bool): translate primary structure data as well as atomic data **kwargs (dict): keyword arguments to moldesign.Molecule __init__ method Returns: moldesign.Molecule: translated molecule """ newatom_map = {} newresidues = {} newchains = {} newatoms = mdt.AtomList([]) backup_chain_names = list(string.ascii_uppercase) for pybatom in pbmol.atoms: obres = pybatom.OBAtom.GetResidue() name = obres.GetAtomID(pybatom.OBAtom).strip() if pybatom.atomicnum == 67: print(("WARNING: openbabel parsed atom serial %d (name:%s) as Holmium; " "correcting to hydrogen. ") % (pybatom.OBAtom.GetIdx(), name)) atnum = 1 elif pybatom.atomicnum == 0: print("WARNING: openbabel failed to parse atom serial %d (name:%s); guessing %s. " % ( pybatom.OBAtom.GetIdx(), name, name[0])) atnum = mdt.data.ATOMIC_NUMBERS[name[0]] else: atnum = pybatom.atomicnum mdtatom = mdt.Atom(atnum=atnum, name=name, formal_charge=pybatom.formalcharge * u.q_e, pdbname=name, pdbindex=pybatom.OBAtom.GetIdx()) newatom_map[pybatom.OBAtom.GetIdx()] = mdtatom mdtatom.position = pybatom.coords * u.angstrom if primary_structure: obres = pybatom.OBAtom.GetResidue() resname = obres.GetName() residx = obres.GetIdx() chain_id = obres.GetChain() chain_id_num = obres.GetChainNum() if chain_id_num not in newchains: # create new chain if not mdt.utils.is_printable(chain_id.strip()) or not chain_id.strip(): chain_id = backup_chain_names.pop() print('WARNING: assigned name %s to unnamed chain object @ %s' % ( chain_id, hex(chain_id_num))) chn = mdt.Chain(pdbname=str(chain_id)) newchains[chain_id_num] = chn else: chn = newchains[chain_id_num] if residx not in newresidues: # Create new residue pdb_idx = obres.GetNum() res = mdt.Residue(pdbname=resname, pdbindex=pdb_idx) newresidues[residx] = res chn.add(res) res.chain = chn else: res = newresidues[residx] res.add(mdtatom) newatoms.append(mdtatom) for ibond in range(pbmol.OBMol.NumBonds()): obbond = pbmol.OBMol.GetBond(ibond) a1 = newatom_map[obbond.GetBeginAtomIdx()] a2 = newatom_map[obbond.GetEndAtomIdx()] order = obbond.GetBondOrder() bond = mdt.Bond(a1, a2) bond.order = order if reorder_atoms_by_residue and primary_structure: resorder = {} for atom in newatoms: resorder.setdefault(atom.residue, len(resorder)) newatoms.sort(key=lambda a: resorder[a.residue]) return mdt.Molecule(newatoms, **kwargs) def from_smiles(smi, name=None): """ Translate a smiles string to a 3D structure. This method uses OpenBabel to generate a plausible 3D conformation of the 2D SMILES topology. We only use the first result from the conformation generator. Args: smi (str): smiles string name (str): name to assign to molecule (default - the smiles string) Returns: moldesign.Molecule: the translated molecule """ return _string_to_3d_mol(smi, 'smi', name) def from_inchi(inchi, name=None): """ Translate an INCHI string to a 3D structure. This method uses OpenBabel to generate a plausible 3D conformation of the 2D SMILES topology. We only use the first result from the conformation generator. Args: smi (str): smiles string name (str): name to assign to molecule (default - the smiles string) Returns: moldesign.Molecule: the translated molecule """ return _string_to_3d_mol(inchi, 'inchi', name) @packages.openbabel.runsremotely def _string_to_3d_mol(s, fmt, name): import pybel as pb if name is None: name = s pbmol = pb.readstring(fmt, str(s)) # avoid passing unicode by casting to str pbmol.addh() pbmol.make3D() mol = pybel_to_mol(pbmol, name=name, primary_structure=False) mdt.helpers.atom_name_check(mol) return mol
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/pyscf_interface.py
.py
4,498
127
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import future.utils import numpy as np import moldesign.units as u from .. import compute from ..utils import if_not_none, redirect_stderr from .. import orbitals from ..utils import exports from ..compute import packages if future.utils.PY2: from cStringIO import StringIO else: from io import StringIO @exports def mol_to_pyscf(mol, basis, symmetry=None, charge=0, positions=None): """Convert an MDT molecule to a PySCF "Mole" object""" from pyscf import gto pyscfmol = gto.Mole() positions = if_not_none(positions, mol.positions) pyscfmol.atom = [[atom.elem, pos.value_in(u.angstrom)] for atom, pos in zip(mol.atoms, positions)] pyscfmol.basis = basis pyscfmol.charge = charge if symmetry is not None: pyscfmol.symmetry = symmetry with redirect_stderr(StringIO()) as builderr: pyscfmol.build() builderr.seek(0) for line in builderr: if line.strip() == 'Warn: Ipython shell catchs sys.args': continue else: print('PYSCF: ' + line) return pyscfmol # PYSCF appears to have weird names for spherical components? SPHERICAL_NAMES = {'y^3': (3, -3), 'xyz': (3, -2), 'yz^2': (3, -1), 'z^3': (3, 0), 'xz^2': (3, 1), 'zx^2': (3, 2), 'x^3': (3, 3), 'x2-y2': (2, 2)} SPHERICAL_NAMES.update(orbitals.ANGULAR_NAME_TO_COMPONENT) # TODO: need to handle parameters for max iterations, # level shifts, requiring convergence, restarts, initial guesses class StatusLogger(object): LEN = 15 def __init__(self, description, columns, logger): self.logger = logger self.description = description self.columns = columns self._init = False self._row_format = ("{:<%d}" % self.LEN) + ("{:>%d}" % self.LEN) * (len(columns) - 1) def __call__(self, info): if not self._init: self.logger.status('Starting energy model calculation: %s' % self.description) self.logger.status(self._row_format.format(*self.columns)) self.logger.status(self._row_format.format(*['-' * (self.LEN - 2) for i in self.columns])) self._init = True self.logger.status(self._row_format.format(*[info.get(c, 'n/a') for c in self.columns])) @packages.pyscf.runsremotely def get_eris_in_basis(basis, orbs): """ Get electron repulsion integrals transformed into this basis (in form eri[i,j,k,l] = (ij|kl)) """ from pyscf import ao2mo pmol = mol_to_pyscf(basis.wfn.mol, basis=basis.basisname) eri = ao2mo.full(pmol, orbs.T, compact=True) * u.hartree eri.defunits_inplace() return orbitals.ERI4FoldTensor(eri, orbs) @packages.pyscf.runsremotely def basis_values(mol, basis, coords, coeffs=None, positions=None): """ Calculate the orbital's value at a position in space Args: mol (moldesign.Molecule): Molecule to attach basis set to basis (moldesign.orbitals.BasisSet): set of basis functions coords (Array[length]): List of coordinates (with shape ``(len(coords), 3)``) coeffs (Vector): List of ao coefficients (optional; if not passed, all basis fn values are returned) Returns: Array[length**(-1.5)]: if ``coeffs`` is not passed, an array of basis fn values at each coordinate. Otherwise, a list of orbital values at each coordinate """ from pyscf.dft import numint # TODO: more than just create the basis by name ... pmol = mol_to_pyscf(mol, basis=basis.basisname, positions=positions) aovals = numint.eval_ao(pmol, np.ascontiguousarray(coords.value_in(u.bohr))) * (u.a0**-1.5) if coeffs is None: return aovals else: return aovals.dot(coeffs.T)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/parmed_interface.py
.py
9,298
302
from __future__ import print_function, absolute_import, division import io from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from past.builtins import basestring import collections import itertools import future.utils import moldesign as mdt from .. import units as u from .. import utils if future.utils.PY2: from cStringIO import StringIO else: from io import StringIO def read_mmcif(f, reassign_chains=True): """Parse an mmCIF file (using the parmEd parser) and return a molecule Args: f (file): file-like object containing the mmCIF file reassign_chains (bool): reassign chain IDs from ``auth_asym_id`` to ``label_asym_id`` Returns: moldesign.Molecule: parsed molecule """ import parmed parmedmol = parmed.read_CIF(f) mol = parmed_to_mdt(parmedmol) if reassign_chains: f.seek(0) mol = _reassign_chains(f, mol) mdt.helpers.assign_biopolymer_bonds(mol) return mol def read_pdb(f): """Parse an mmCIF file (using the parmEd parser) and return a molecule Args: f (file): file-like object containing the mmCIF file Returns: moldesign.Molecule: parsed molecule """ import parmed parmedmol = parmed.read_PDB(f) mol = parmed_to_mdt(parmedmol) return mol def write_pdb(mol, fileobj): """ Write a PDB file to a buffer Args: mol (moldesign.Molecule): molecule to write as pdb fileobj (io.IOBase): buffer to write to - bytes and text interfaces are acceptable """ pmedmol = mol_to_parmed(mol) tempfile = StringIO() pmedmol.write_pdb(tempfile, renumber=False) if not isinstance(fileobj, io.TextIOBase) or 'b' in getattr(fileobj, 'mode', ''): binaryobj = fileobj fileobj = io.TextIOWrapper(binaryobj) wrapped = True else: wrapped = False _insert_conect_records(mol, pmedmol, tempfile, write_to=fileobj) if wrapped: fileobj.flush() fileobj.detach() CONECT = 'CONECT %4d' def _insert_conect_records(mol, pmdmol, pdbfile, write_to=None): """ Inserts TER records to indicate the end of the biopolymeric part of a chain Put CONECT records at the end of a pdb file that doesn't have them Args: mol (moldesign.Molecule): the MDT version of the molecule that pdbfile describes pdbfile (TextIO OR str): pdb file (file-like or string) Returns: TextIO OR str: copy of the pdb file with added TER records - it will be returned as the same type passed (i.e., as a filelike buffer or as a string) """ conect_bonds = mdt.helpers.get_conect_pairs(mol) def get_atomseq(atom): return pmdmol.atoms[atom.index].number pairs = collections.OrderedDict() for atom, nbrs in conect_bonds.items(): pairs[get_atomseq(atom)] = list(map(get_atomseq, nbrs)) if isinstance(pdbfile, basestring): pdbfile = StringIO(pdbfile) if write_to is None: newf = StringIO() else: newf = write_to pdbfile.seek(0) for line in pdbfile: if line.split() == ['END']: for a1idx in pairs: for istart in range(0, len(pairs[a1idx]), 4): pairindices = ''.join(("%5d" % idx) for idx in pairs[a1idx][istart:istart+4]) newf.write(str(CONECT % a1idx + pairindices + '\n')) newf.write(str(line)) def write_mmcif(mol, fileobj): mol_to_parmed(mol).write_cif(fileobj) @utils.exports def parmed_to_mdt(pmdmol): """ Convert parmed Structure to MDT Structure Args: pmdmol (parmed.Structure): parmed structure to convert Returns: mdt.Molecule: converted molecule """ atoms = collections.OrderedDict() residues = {} chains = {} masses = [pa.mass for pa in pmdmol.atoms] * u.dalton positions = [[pa.xx, pa.xy, pa.xz] for pa in pmdmol.atoms] * u.angstrom for iatom, patm in enumerate(pmdmol.atoms): if patm.residue.chain not in chains: chains[patm.residue.chain] = mdt.Chain(pdbname=patm.residue.chain) chain = chains[patm.residue.chain] if patm.residue not in residues: residues[patm.residue] = mdt.Residue(resname=patm.residue.name, pdbindex=patm.residue.number) residues[patm.residue].chain = chain chain.add(residues[patm.residue]) residue = residues[patm.residue] atom = mdt.Atom(name=patm.name, atnum=patm.atomic_number, pdbindex=patm.number, mass=masses[iatom]) atom.position = positions[iatom] atom.residue = residue residue.add(atom) assert patm not in atoms atoms[patm] = atom for pbnd in pmdmol.bonds: atoms[pbnd.atom1].bond_to(atoms[pbnd.atom2], int(pbnd.order)) mol = mdt.Molecule(list(atoms.values()), metadata=_get_pdb_metadata(pmdmol)) return mol def _get_pdb_metadata(pmdmol): metadata = utils.DotDict(description=pmdmol.title) authors = getattr(pmdmol, 'journal_authors', None) if authors: metadata.pdb_authors = authors experimental = getattr(pmdmol, 'experimental', None) if experimental: metadata.pdb_experimental = experimental box_vectors = getattr(pmdmol, 'box_vectors', None) if box_vectors: metadata.pdb_box_vectors = box_vectors doi = getattr(pmdmol, 'doi', None) if doi: metadata.pdb_doi = doi metadata.url = "http://dx.doi.org/%s" % doi return metadata @utils.exports def mol_to_parmed(mol): """ Convert MDT Molecule to parmed Structure Args: mol (moldesign.Molecule): Returns: parmed.Structure """ import parmed struc = parmed.Structure() struc.title = mol.name pmedatoms = [] for atom in mol.atoms: pmedatm = parmed.Atom(atomic_number=atom.atomic_number, name=atom.name, mass=atom.mass.value_in(u.dalton), number=utils.if_not_none(atom.pdbindex, -1)) pmedatm.xx, pmedatm.xy, pmedatm.xz = atom.position.value_in(u.angstrom) pmedatoms.append(pmedatm) struc.add_atom(pmedatm, resname=utils.if_not_none(atom.residue.resname, 'UNL'), resnum=utils.if_not_none(atom.residue.pdbindex, -1), chain=utils.if_not_none(atom.chain.name, '')) for bond in mol.bonds: struc.bonds.append(parmed.Bond(pmedatoms[bond.a1.index], pmedatoms[bond.a2.index], order=bond.order)) return struc def _reassign_chains(f, mol): """ Change chain ID assignments to the mmCIF standard (parmed uses author assignments) If the required fields don't exist, a copy of the molecule is returned unchanged. Args: f (file): mmcif file/stream mol (moldesign.Molecule): molecule with default parmed assignemnts Returns: moldesign.Molecule: new molecule with reassigned chains """ data = mdt.interfaces.biopython_interface.get_mmcif_data(f) f.seek(0) try: poly_seq_ids = _aslist(data['_pdbx_poly_seq_scheme.asym_id']) nonpoly_ids = _aslist(data['_pdbx_nonpoly_scheme.asym_id']) except KeyError: return mol.copy(name=mol.name) newchain_names = set(poly_seq_ids + nonpoly_ids) newchains = {name: mdt.Chain(name) for name in newchain_names} residue_iterator = itertools.chain( zip(_aslist(data['_pdbx_poly_seq_scheme.mon_id']), _aslist(data['_pdbx_poly_seq_scheme.pdb_seq_num']), _aslist(data['_pdbx_poly_seq_scheme.pdb_strand_id']), _aslist(data['_pdbx_poly_seq_scheme.asym_id'])), zip(_aslist(data['_pdbx_nonpoly_scheme.mon_id']), _aslist(data['_pdbx_nonpoly_scheme.pdb_seq_num']), _aslist(data['_pdbx_nonpoly_scheme.pdb_strand_id']), _aslist(data['_pdbx_nonpoly_scheme.asym_id']))) reschains = {(rname, ridx, rchain): newchains[chainid] for rname, ridx, rchain, chainid in residue_iterator} for residue in mol.residues: newchain = reschains[residue.resname, str(residue.pdbindex), residue.chain.name] residue.chain = newchain return mdt.Molecule(mol.atoms, name=mol.name, metadata=mol.metadata) def _aslist(l): if isinstance(l, list): return l else: return [l]
Python
3D
Autodesk/molecular-design-toolkit
moldesign/interfaces/openmm.py
.py
12,178
349
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import numpy as np import pyccc import moldesign as mdt from ..compute import packages from ..utils import from_filepath from .. import units as u from ..utils import exports class OpenMMPickleMixin(object): def __getstate__(self): mystate = self.__dict__.copy() if 'sim' in mystate: assert 'sim_args' not in mystate sim = mystate.pop('sim') mystate['sim_args'] = (sim.topology, sim.system, sim.integrator) return mystate def __setstate__(self, state): from simtk.openmm import app if 'sim_args' in state: assert 'sim' not in state args = state.pop('sim_args') state['sim'] = app.Simulation(*args) self.__dict__.update(state) # This is a factory for the MdtReporter class. It's here so that we don't have to import # simtk.openmm.app at the module level def MdtReporter(mol, report_interval): from simtk.openmm.app import StateDataReporter class MdtReporter(StateDataReporter): """ We'll use this class to capture all the information we need about a trajectory It's pretty basic - the assumption is that there will be more processing on the client side """ def __init__(self, mol, report_interval): self.mol = mol self.report_interval = report_interval self.trajectory = mdt.Trajectory(mol) self.annotation = None self.last_report_time = None self.logger = mdt.helpers.DynamicsLog() def __del__(self): try: super().__del__() except AttributeError: pass # suppress irritating error msgs def report_from_mol(self, **kwargs): self.mol.calculate() if self.annotation is not None: kwargs.setdefault('annotation', self.annotation) self.report(self.mol.energy_model.sim, self.mol.energy_model.sim.context.getState(getEnergy=True, getForces=True, getPositions=True, getVelocities=True), settime=self.mol.time) def report(self, simulation, state, settime=None): """ Callback for dynamics after the specified interval Args: simulation (simtk.openmm.app.Simulation): simulation to report on state (simtk.openmm.State): state of the simulation """ # TODO: make sure openmm masses are the same as MDT masses settime = settime if settime is not None else simtk2pint(state.getTime()) report = dict( positions=simtk2pint(state.getPositions()), momenta=simtk2pint(state.getVelocities())*self.mol.dim_masses, forces=simtk2pint(state.getForces()), time=settime, vectors=simtk2pint(state.getPeriodicBoxVectors()), potential_energy=simtk2pint(state.getPotentialEnergy())) if self.annotation is not None: report['annotation'] = self.annotation if settime: self.last_report_time = report['time'] self.trajectory.new_frame(properties=report) self.logger.print_step(self.mol, properties=report) def describeNextReport(self, simulation): """ Returns: tuple: A five element tuple. The first element is the number of steps until the next report. The remaining elements specify whether that report will require positions, velocities, forces, and energies respectively. """ steps = self.report_interval - simulation.currentStep % self.report_interval return (steps, True, True, True, True) return MdtReporter(mol, report_interval) PINT_NAMES = {'mole': u.avogadro, 'degree': u.degrees, 'radian': u.radians, 'elementary charge': u.q_e} @exports def simtk2pint(quantity, flat=False): """ Converts a quantity from the simtk unit system to the internal unit system Args: quantity (simtk.unit.quantity.Quantity): quantity to convert flat (bool): if True, flatten 3xN arrays to 3N Returns: mdt.units.MdtQuantity: converted to MDT unit system """ from simtk import unit as stku mag = np.array(quantity._value) if quantity.unit == stku.radian: return mag * u.radians if quantity.unit == stku.degree: return mag * u.degrees for dim, exp in itertools.chain(quantity.unit.iter_scaled_units(), quantity.unit.iter_top_base_units()): if dim.name in PINT_NAMES: pintunit = PINT_NAMES[dim.name] else: pintunit = u.ureg.parse_expression(dim.name) mag = mag * (pintunit**exp) if flat: mag = np.reshape(mag, (np.product(mag.shape),)) return u.default.convert(mag) @exports def pint2simtk(quantity): """ Converts a quantity from the pint to simtk unit system. Note SimTK has a less extensive collection that pint. May need to have pint convert to SI first """ from simtk import unit as stku SIMTK_NAMES = {'ang': stku.angstrom, 'fs': stku.femtosecond, 'nm': stku.nanometer, 'ps': stku.picosecond} newvar = quantity._magnitude for dim, exp in quantity._units.items(): if dim in SIMTK_NAMES: stkunit = SIMTK_NAMES[dim] else: stkunit = getattr(stku, dim) newvar = newvar * stkunit ** exp return newvar @packages.openmm.runsremotely def _amber_to_mol(prmtop_file, inpcrd_file): """ Convert an amber prmtop and inpcrd file to an MDT molecule Args: prmtop_file (file-like): topology file in amber prmtop format inpcrd_file (file-like): coordinate file in amber crd format Returns: moldesign.Molecule: Molecule parsed from amber output """ from simtk.openmm import app prmtop = from_filepath(app.AmberPrmtopFile, prmtop_file) inpcrd = from_filepath(app.AmberInpcrdFile, inpcrd_file) mol = topology_to_mol(prmtop.topology, positions=inpcrd.positions, velocities=inpcrd.velocities) return mol if packages.openmm.is_installed(): def amber_to_mol(prmtop_file, inpcrd_file): if not isinstance(prmtop_file, pyccc.FileContainer): prmtop_file = pyccc.LocalFile(prmtop_file) if not isinstance(inpcrd_file, pyccc.FileContainer): inpcrd_file = pyccc.LocalFile(inpcrd_file) return _amber_to_mol(prmtop_file, inpcrd_file) else: amber_to_mol = _amber_to_mol exports(amber_to_mol) @exports def topology_to_mol(topo, name=None, positions=None, velocities=None, assign_bond_orders=True): """ Convert an OpenMM topology object into an MDT molecule. Args: topo (simtk.openmm.app.topology.Topology): topology to convert name (str): name to assign to molecule positions (list): simtk list of atomic positions velocities (list): simtk list of atomic velocities assign_bond_orders (bool): assign bond orders from templates (simtk topologies do not store bond orders) """ from simtk import unit as stku # Atoms atommap = {} newatoms = [] masses = u.amu*[atom.element.mass.value_in_unit(stku.amu) for atom in topo.atoms()] for atom,mass in zip(topo.atoms(), masses): newatom = mdt.Atom(atnum=atom.element.atomic_number, name=atom.name, mass=mass) atommap[atom] = newatom newatoms.append(newatom) # Coordinates if positions is not None: poslist = np.array([p.value_in_unit(stku.nanometer) for p in positions]) * u.nm poslist.ito(u.default.length) for newatom, position in zip(newatoms, poslist): newatom.position = position if velocities is not None: velolist = np.array([v.value_in_unit(stku.nanometer/stku.femtosecond) for v in velocities]) * u.nm/u.fs velolist = u.default.convert(velolist) for newatom, velocity in zip(newatoms, velolist): newatom.momentum = newatom.mass * simtk2pint(velocity) # Biounits chains = {} for chain in topo.chains(): if chain.id not in chains: chains[chain.id] = mdt.Chain(name=chain.id, index=chain.index) newchain = chains[chain.id] for residue in chain.residues(): newresidue = mdt.Residue(name='%s%d' % (residue.name, residue.index), chain=newchain, pdbindex=int(residue.id), pdbname=residue.name) newchain.add(newresidue) for atom in residue.atoms(): newatom = atommap[atom] newatom.residue = newresidue newresidue.add(newatom) # Bonds bonds = {} for bond in topo.bonds(): a1, a2 = bond na1, na2 = atommap[a1], atommap[a2] if na1 not in bonds: bonds[na1] = {} if na2 not in bonds: bonds[na2] = {} b = mdt.Bond(na1, na2) b.order = 1 if name is None: name = 'Unnamed molecule from OpenMM' newmol = mdt.Molecule(newatoms, name=name) if assign_bond_orders: for residue in newmol.residues: try: residue.assign_template_bonds() except (KeyError, ValueError): pass return newmol @exports def mol_to_topology(mol): """ Create an openmm topology object from an MDT molecule Args: mol (moldesign.Molecule): molecule to copy topology from Returns: simtk.openmm.app.Topology: topology of the molecule """ from simtk.openmm import app top = app.Topology() chainmap = {chain: top.addChain(chain.name) for chain in mol.chains} resmap = {res: top.addResidue(res.resname, chainmap[res.chain], str(res.pdbindex)) for res in mol.residues} atommap = {atom: top.addAtom(atom.name, app.Element.getBySymbol(atom.element), resmap[atom.residue], id=str(atom.pdbindex)) for atom in mol.atoms} for bond in mol.bonds: top.addBond(atommap[bond.a1], atommap[bond.a2]) return top @exports def mol_to_modeller(mol): from simtk.openmm import app if mol.is_small_molecule: if not mol.residues[0].resname: mol.residues[0].resname = 'UNL' mol.residues[0].pdbindex = 1 if not mol.chains[0].pdbname: mol.chains[0].pdbname = 'A' return app.Modeller(mol_to_topology(mol), pint2simtk(mol.positions)) def list_openmmplatforms(): from simtk import openmm return [openmm.Platform.getPlatform(ip).getName() for ip in range(openmm.Platform.getNumPlatforms())]
Python
3D
Autodesk/molecular-design-toolkit
moldesign/units/tools.py
.py
7,651
245
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .. import utils from .quantity import * def unitsum(iterable): """ Faster method to compute sums of iterables if they're all in the right units Args: iterable (Iter[MdtQuantity]): iterable to sum over Returns: MdtQuantity: the sum """ g0 = next(iterable).copy() for item in iterable: if item.units == g0.units: g0._magnitude += item._magnitude else: g0 += item return g0 def dot(a1, a2): """ Dot product that respects units Args: a1 (MdtQuantity or np.ndarray): First term in dot product a2 (MdtQuantity or np.ndarray): Second term in dot product Returns: MdtQuantity or np.ndarray: dot product (MdtQuantity if either input has units, ndarray else) """ if isinstance(a2, MdtQuantity): return a2.ldot(a1) else: # this will work whether or not a1 has units return a1.dot(a2) @utils.args_from(np.linspace) def linspace(start, stop, **kwargs): u1 = getattr(start, 'units', ureg.dimensionless) u2 = getattr(stop, 'units', ureg.dimensionless) if u1 == u2 == ureg.dimensionless: return np.linspace(start, stop, **kwargs) else: q1mag = start.magnitude q2mag = stop.value_in(start.units) return np.linspace(q1mag, q2mag, **kwargs) * start.units def arrays_almost_equal(a1, a2): """ Return true if arrays are almost equal up to numerical noise Note: This is assumes that absolute differences less than 1e-12 are insignificant. It is therefore more likely to return "True" for very small numbers and "False" for very big numbers. Caveat emptor. Args: a1 (MdtQuantity or np.ndarray): first array a2 (MdtQuantity or np.ndarray): second array Returns: bool: True if arrays differ by no more than numerical noise in any element Raises: DimensionalityError: if the arrays have incompatible units """ a1units = False if isinstance(a1, MdtQuantity): if a1.dimensionless: a1mag = a1.value_in(ureg.dimensionless) else: a1units = True a1mag = a1.magnitude else: a1mag = a1 if isinstance(a2, MdtQuantity): if a2.dimensionless: if a1units: raise DimensionalityError(a1.units, ureg.dimensionless, "Cannot compare objects") else: a2mag = a2.value_in(ureg.dimensionless) elif not a1units: raise DimensionalityError(ureg.dimensionless, a2.units, "Cannot compare objects") else: a2mag = a2.value_in(a1.units) else: if a1units: raise DimensionalityError(a1.units, ureg.dimensionless, "Cannot compare objects") else: a2mag = a2 return np.allclose(a1mag, a2mag, atol=1e-12) def from_json(j): """ Convert a JSON description to a quantity. This is the inverse of :meth:`moldesign.units.quantity.MDTQuantity.to_json` Args: j (dict): ``{value: <float>, units: <str>}`` Returns: moldesign.units.quantity.MDTQuantity """ return j['value'] * ureg(j['units']) def get_units(q): """ Return the base unit system of an quantity or arbitrarily-nested iterables of quantities Note: This routine will dive on the first element of iterables until a quantity with units until the units can be determined. It will not check the remaining elements of the iterable for consistency Examples: >>> from moldesign import units >>> units.get_units(1.0 * units.angstrom) <Unit('angstrom')> >>> units.get_units(np.array([1.0, 2, 3.0])) <Unit('dimensionless')> >>> # We dive on the first element of each iterable until we can determine a unit system: >>> units.get_units([[1.0 * u.dalton, 3.0 * u.eV], ['a'], 'gorilla']) <Unit('amu')> Args: q (MdtQuantity or numeric): quantity to test Returns: MdtUnit: the quantity's units """ if isinstance(q, MdtUnit): return q x = q while True: try: x = next(x.__iter__()) except (AttributeError, TypeError): break else: if isinstance(x, str): raise TypeError('Found string data while trying to determine units') q = MdtQuantity(x) if q.dimensionless: return ureg.dimensionless else: return q.units def array(qlist, defunits=False, _baseunit=None): """ Facilitates creating an array with units - like numpy.array, but it also checks units for all components of the array. Note: Unlike numpy.array, these arrays must have numeric type - this routine will raise a ValueError if a non-square array is passed. Args: qlist (List[MdtQuantity]): List-like object of quantity objects defunits (bool): if True, convert the array to the default units Returns: MdtQuantity: ndarray-like object with standardized units Raises: DimensionalityError: if the array has inconsistent units ValueError: if the array could not be converted to a square numpy array """ from . import default if hasattr(qlist, 'units') and hasattr(qlist, 'magnitude'): return MdtQuantity(qlist) if _baseunit is None: _baseunit = get_units(qlist) if _baseunit.dimensionless: return _make_nparray(qlist) if defunits: _baseunit = default.get_default(_baseunit) if hasattr(qlist, 'to'): # if already a quantity, just convert and return return qlist.to(_baseunit) try: # try to create a quantity return _baseunit * [array(item, _baseunit=_baseunit).value_in(_baseunit) for item in qlist] except TypeError: # if here, one or more objects cannot be converted to quantities raise DimensionalityError(_baseunit, ureg.dimensionless, extra_msg='Object "%s" does not have units' % qlist) def _make_nparray(q): """ Turns a list of dimensionless numbers into a numpy array. Does not permit object arrays """ if hasattr(q, 'units'): return q.value_in(ureg.dimensionless) try: arr = np.array([_make_nparray(x) for x in q]) if arr.dtype == 'O': raise ValueError("Could not create numpy array of numeric data - is your input square?") else: return arr except TypeError: return q #@utils.args_from(np.broadcast_to) def broadcast_to(arr, *args, **kwargs): units = arr.units newarr = np.zeros(2) * units tmp = np.broadcast_to(arr, *args, **kwargs) newarr._magnitude = tmp return newarr
Python
3D
Autodesk/molecular-design-toolkit
moldesign/units/quantity.py
.py
11,689
361
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from past.builtins import basestring import operator import copy from os.path import join, abspath, dirname import numpy as np from pint import UnitRegistry, set_application_registry, DimensionalityError, UndefinedUnitError from ..utils import ResizableArray # Set up pint's unit definitions ureg = UnitRegistry() unit_def_file = join(abspath(dirname(__file__)), '..', '_static_data','pint_atomic_units.txt') ureg.load_definitions(unit_def_file) ureg.default_system = 'nano' set_application_registry(ureg) class MdtUnit(ureg.Unit): """ Pickleable version of pint's Unit class. """ def __reduce__(self): return _get_unit, (str(self),) @property def units(self): return self def convert(self, value): """ Returns quantity converted to these units Args: value (MdtQuantity or Numeric): value to convert Returns: MdtQuantity: converted value Raises: DimensionalityError: if the quantity does not have these units' dimensionality """ if hasattr(value, 'to'): return value.to(self) elif self.dimensionless: return value * self else: raise DimensionalityError('Cannot convert "%s" to units of "%s"' % (value, self)) def value_of(self, value): """ Returns numeric value of the quantity in these units Args: value (MdtQuantity or Numeric): value to convert Returns: Numeric: value in this object's units Raises: DimensionalityError: if the quantity does not have these units' dimensionality """ v = self.convert(value) return v.magnitude def _get_unit(unitname): """pickle helper for deserializing MdtUnit objects""" return getattr(ureg, unitname) class MdtQuantity(ureg.Quantity): """ This is a 'patched' version of pint's quantities that can be pickled (slightly hacky) and supports more numpy operations. Users should never need to instantiate this directly - instead, construct MDT quantities by multiplying numbers/arrays with the pre-defined units Examples: >>> 5.0 * units.femtoseconds >>> [1.0,2.0,3.0] * units.eV """ # Patching some ufunc intercepts - these don't all necessarily work _Quantity__prod_units = ureg.Quantity._Quantity__prod_units.copy() _Quantity__prod_units['dot'] = 'mul' _Quantity__prod_units['cross'] = 'mul' _Quantity__copy_units = ureg.Quantity._Quantity__copy_units[:] _Quantity__copy_units.extend(('diagonal', 'append', '_broadcast_to')) _Quantity__handled = ureg.Quantity._Quantity__handled + ('diagonal', 'append', 'dot') # For pickling - prevent delegation to the built-in types' __getnewargs__ methods: def __getattr__(self, item): if item == '__getnewargs__': raise AttributeError('__getnewargs__ not accessible in this class') else: return super(MdtQuantity, self).__getattr__(item) def __reduce__(self): replacer = list(super(MdtQuantity, self).__reduce__()) replacer[0] = MdtQuantity return tuple(replacer) def __deepcopy__(self, memo): result = copy.deepcopy(self.magnitude, memo) * self.get_units() memo[id(self)] = result return result def __hash__(self): m = self._magnitude if isinstance(m, np.ndarray) and m.shape == (): m = float(m) return hash((m, str(self.units))) def __setitem__(self, key, value): from . import array as quantityarray try: # Speed up item assignment by overriding pint's implementation if self.units == value.units: self.magnitude[key] = value._magnitude else: self.magnitude[key] = value.value_in(self.units) except AttributeError: if isinstance(value, basestring): raise TypeError("Cannot assign units to a string ('%s')"%value) try: # fallback to pint's implementation super().__setitem__(key, value) except (TypeError, ValueError): # one last ditch effort to create a more well-behaved object super().__setitem__(key, quantityarray(value)) def __eq__(self, other): return self.compare(other, operator.eq) @property def shape(self): return self.magnitude.shape @shape.setter def shape(self, value): self.magnitude.shape = value def compare(self, other, op): """ Augments the :class:`pint._Quantity` method with the following features: - Comparisons to dimensionless 0 can proceed without unit checking """ other = MdtQuantity(other) try: iszero = other.magnitude == 0.0 and other.dimensionless except ValueError: iszero = False if iszero: return op(self.magnitude, other.magnitude) else: return op(self.magnitude, other.value_in(self.units)) def get_units(self): """ Return the base unit system of an quantity """ x = self while True: try: x = next(x.__iter__()) except (AttributeError, TypeError): break try: y = 1.0 * x y._magnitude = 1.0 return y except AttributeError: return 1.0 def norm(self): """L2-norm of this object including units Returns: Scalar: L2-norm """ units = self.get_units() return units * np.linalg.norm(self._magnitude) def normalized(self): """ Normalizes a vector or matrix Returns: np.ndarray: L2-normalized copy of this array (no units) """ from ..mathutils import normalized return normalized(self.magnitude) def dot(self, other): """ Dot product that correctly multiplies units Returns: Array """ if hasattr(other, 'get_units'): units = self.get_units() * other.get_units() else: units = self.get_units() return units * np.dot(self, other) def cross(self, other): """ Cross product that correctly multiplies units Returns: Array """ if hasattr(other, 'get_units'): units = self.get_units() * other.get_units() else: units = self.get_units() return units * np.cross(self, other) def ldot(self, other): """ Left-multiplication version of dot that correctly multiplies units This is mathematically equivalent to ``other.dot(self)``, but preserves units even if ``other`` is a plain numpy array Args: other (MdtQuantity or np.ndarray): quantity to take the dot product with Examples: >>> mat1 = np.ones((3,2)) >>> vec1 = np.array([-3.0,2.0]) * u.angstrom >>> vec1.ldot(mat1) <Quantity([-1. -1. -1.], 'ang')> >>> # This won't work because "mat1", a numpy array, doesn't respect units >>> mat1.dot(vec1) """ if hasattr(other, 'get_units'): units = self.get_units() * other.get_units() else: units = self.get_units() return units * np.dot(other, self) def __mod__(self, other): my_units = self.get_units() s_mag = self.magnitude o_mag = other.value_in(my_units) m = s_mag % o_mag return m * my_units # backwards-compatible name value_in = ureg.Quantity.m_as def defunits_value(self): return self.defunits().magnitude # defunits = ureg.Quantity.to_base_units # replacing this with the new pint implementation def defunits(self): """Return this quantity in moldesign's default unit system (as specified in moldesign.units.default)""" from . import default return default.convert(self) # defunits_inplace = ureg.Quantity.ito_base_units # replacing this with the new pint implementation def defunits_inplace(self): """Internally convert quantity to default units""" from . import default newunit = default.get_baseunit(self) return self.ito(newunit) def to_simtk(self): """ Return a SimTK quantity object """ from moldesign.interfaces.openmm import pint2simtk return pint2simtk(self) def to_json(self): """ Convert to a simple JSON format Returns: dict: ``{value: <float>, units: <str>}`` Examples: >>> from moldesign.units import angstrom >>> q = 1.0 * angstrom >>> q.to_json() {'units':'angstrom', value: 1.0} """ mag = self.magnitude if isinstance(mag, np.ndarray): mag = mag.tolist() return {'value': mag, 'units': str(self.units)} def make_resizable(self): self._magnitude = ResizableArray(self._magnitude) def append(self, item): from .tools import array try: mag = item.value_in(self.units) except AttributeError: # handles lists of quantities mag = array(item).value_in(self.units) self._magnitude.append(mag) def extend(self, items): from . import array mags = array(items).value_in(self.units) self._magnitude.append(mags) # monkeypatch pint's unit registry to return BuckyballQuantities ureg.Quantity = MdtQuantity ureg.Unit = MdtUnit # These synonyms are here solely so that we can write descriptive docstrings # TODO: use typing module to turn these into real abstract types, with dimensional parameterization class Scalar(MdtQuantity): """ A scalar quantity (i.e., a single floating point number) with attached units """ def __init__(self, *args): raise NotImplementedError('This is an abstract class - use MdtQuantity instead') class Vector(MdtQuantity): """ A vector quantity (i.e., a list of floats) with attached units that behaves like a 1-dimensional numpy array with units """ def __init__(self, *args): raise NotImplementedError('This is an abstract class - use MdtQuantity instead') class Array(MdtQuantity): """ A matrix quantity (i.e., a matrix of floats) with attached units that behaves like a 2-dimensional numpy array with units """ def __init__(self, *args): raise NotImplementedError('This is an abstract class - use MdtQuantity instead') class Tensor(MdtQuantity): """ A multidimensional array of floats with attached units that behaves like a multidimensional numpy array with units """ def __init__(self, *args): raise NotImplementedError('This is an abstract class - use MdtQuantity instead')
Python
3D
Autodesk/molecular-design-toolkit
moldesign/units/__init__.py
.py
95
4
from .quantity import * from .constants import * from .tools import * from .unitsystem import *
Python
3D
Autodesk/molecular-design-toolkit
moldesign/units/constants.py
.py
1,972
69
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .quantity import * dimensionless = ureg.dimensionless # Constants unity = ureg.angstrom / ureg.angstrom imi = 1.0j pi = np.pi sqrtpi = np.sqrt(np.pi) sqrt2 = np.sqrt(2.0) epsilon_0 = ureg.epsilon_0 c = ureg.speed_of_light alpha = ureg.fine_structure_constant hbar = ureg.hbar boltz = boltzmann_constant = k_b = ureg.boltzmann_constant avogadro = (1.0 * ureg.mole * ureg.avogadro_number).to(unity).magnitude # atomic units hartree = ureg.hartree a0 = bohr = ureg.bohr atomic_time = t0 = ureg.t0 electron_mass = m_e = ureg.electron_mass electron_charge = q_e = ureg.elementary_charge # useful units fs = femtoseconds = ureg.femtosecond ps = picoseconds = ureg.picosecond ns = nanoseconds = ureg.nanosecond eV = electronvolts = ureg.eV kcalpermol = ureg.kcalpermol gpermol = ureg.gpermol kjpermol = ureg.kjpermol radians = radian = rad = ureg.rad degrees = degree = deg = ureg.degrees amu = da = dalton = ureg.amu kelvin = ureg.kelvin nm = ureg.nanometers angstrom = ureg.angstrom molar = ureg.mole / ureg.liter debye = ureg.debye # sets default unit systems def_length = angstrom def_time = fs def_vel = angstrom / fs def_mass = amu def_momentum = def_mass * def_vel def_force = def_momentum / def_time def_energy = eV
Python
3D
Autodesk/molecular-design-toolkit
moldesign/units/unitsystem.py
.py
6,681
190
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .constants import * class UnitSystem(object): """ Class for standardizing units - specifies preferred units for length, mass, energy etc. In MDT, many methods will automatically convert output using the UnitSystem at ``moldesign.units.default`` Args: length (MdtUnit): length units mass (MdtUnit): mass units time (MdtUnit): time units energy (MdtUnit): energy units temperature (MdtUnit): temperature units (default: kelvin) force (MdtUnit): force units (default: energy/length) momentum (MdtUnit): momentum units (default: mass * length / time) angle (MdtUnit): angle units (default: radians) charge (MdtUnit): charge units (default: fundamental charge) """ def __init__(self, length, mass, time, energy, temperature=kelvin, force=None, momentum=None, angle=radians, charge=q_e): self.length = length self.mass = mass self.time = time self.energy = energy self.temperature = temperature self.force = force self.momentum = momentum self.angle = angle self.charge = charge def __getitem__(self, item): """ For convenience when using pint dimensionality descriptions. This aliases self['item'] = self['[item]'] = self.item, e.g. self['length'] = self['[length]'] = self.length """ itemname = item.lstrip('[').rstrip(']') return getattr(self, itemname) @property def force(self): if self._force is None: return self.energy / self.length else: return self._force @force.setter def force(self, f): self._force = f @property def momentum(self): if self._momentum is None: return self.mass * self.length / self.time else: return self._momentum @momentum.setter def momentum(self, f): self._momentum = f def convert(self, quantity): """ Convert a quantity into this unit system. Args: quantity (MdtQuantity or MdtUnit): quantity to convert """ baseunit = self.get_baseunit(quantity) if baseunit == ureg.dimensionless: return quantity * ureg.dimensionless else: result = quantity.to(baseunit) return result def get_default(self, q): """ Return the default unit system for objects with these dimensions Args: q (MdtQuantity or MdtUnit): quantity to get default units for Returns: MdtUnit: Proper units for this quantity """ return self.get_baseunit(1.0 * q).units def convert_if_possible(self, quantity): if isinstance(quantity, MdtQuantity): return self.convert(quantity) else: return quantity def get_baseunit(self, quantity): """ Get units of a quantity, list or array Args: quantity (Any): any number or list-like object with units Raises: TypeError: if the passed object cannot have units (e.g., it's a string or ``None``) Returns: MdtUnit: units found in the passed object """ try: dims = dict(quantity.dimensionality) except AttributeError: try: q = quantity[0] except (TypeError, StopIteration): if isinstance(quantity, (int, float, complex)): return ureg.dimensionless raise TypeError('This type of object cannot have physical units') if isinstance(q, str): raise TypeError('This type of object cannot have physical units') try: return self.get_baseunit(q) except (IndexError, TypeError): # Assume dimensionless return ureg.dimensionless baseunit = ureg.dimensionless # Factor out force units if self._force: if '[length]' in dims and '[mass]' in dims and '[time]' in dims: while dims['[length]'] >= 1 and dims['[mass]'] >= 1 and dims['[time]'] <= -2: baseunit *= self['force'] dims['[length]'] -= 1 dims['[mass]'] -= 1 dims['[time]'] += 2 # Factor out energy units if '[length]' in dims and '[mass]' in dims and '[time]' in dims: while dims['[length]'] >= 1 and dims['[mass]'] >= 1 and dims['[time]'] <= -2: baseunit *= self['energy'] dims['[length]'] -= 2 dims['[mass]'] -= 1 dims['[time]'] += 2 # Factor out momentum units if self._momentum: if '[length]' in dims and '[mass]' in dims and '[time]' in dims: while dims['[length]'] >= 1 and dims['[mass]'] >= 1 and dims['[time]'] <= -1: baseunit *= self['momentum'] dims['[length]'] -= 1 dims['[mass]'] -= 1 dims['[time]'] += 1 if '[current]' in dims: dims.setdefault('[charge]', 0) dims.setdefault('[time]', 0) dims['[charge]'] += dims['[current]'] dims['[time]'] -= dims['[current]'] dims.pop('[current]') # Otherwise, just use the units for unit in dims: if dims[unit] == 0: continue try: baseunit *= self[unit]**dims[unit] except AttributeError: baseunit *= ureg[unit]**dims[unit] return baseunit.units default = UnitSystem(length=angstrom, mass=amu, time=fs, energy=eV) atomic_units = UnitSystem(length=a0, mass=m_e, time=t0, energy=hartree) nano_si = UnitSystem(length=nm, mass=dalton, time=fs, energy=kjpermol)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/tools/__init__.py
.py
120
8
def toplevel(o): __all__.append(o.__name__) return o __all__ = [] from .topology import * from .build import *
Python
3D
Autodesk/molecular-design-toolkit
moldesign/tools/topology.py
.py
7,884
223
""" This module contains various utility functions that are exposed to API users """ from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import moldesign as mdt from moldesign import units as u from . import toplevel, __all__ as _pkgall from moldesign.interfaces.openbabel import add_hydrogen, guess_bond_orders from moldesign.interfaces.pdbfixer_interface import mutate_residues, add_water from moldesign.interfaces.tleap_interface import create_ff_parameters from moldesign.interfaces.ambertools import calc_am1_bcc_charges, calc_gasteiger_charges _pkgall.extend(('add_hydrogen guess_bond_orders mutate_residues add_water' ' create_ff_parameters calc_am1_bcc_charges calc_gasteiger_charges ').split()) ATNUM_VALENCE_CHARGE = {6: {3: -1, 4: 0}, 7: {2: -1, 3: 0, 4: 1}, 8: {1: -1, 2: 0, 3: 1}, 9: {1: 0, 2: 1}} ION_CHARGE = {1: 1, # H 11: 1, # Na+ 19: 1, # K+ 12: 2, # Mg 2+ 20: 2, # Ca 2+ 9: -1, # F- 17: -1, # Cl- 35: -1, # Br- 53: -1} # I- @toplevel def assign_formal_charges(mol, ignore_nonzero=True): """ Assign formal charges to C,N,O,F atoms in this molecule based on valence Args: mol (moldesign.Molecule): Molecule to assign formal charges to. The formal charges of its atoms and its total charge will be adjusted in place. ignore_nonzero (bool): If formal charge is already set to a nonzero value, ignore this atom Note: This method ONLY applies to C,N, O and F, based on a simple valence model. These results should be manually inspected for consistency. Raises: UnhandledValenceError: for cases not handled by the simple valence model References: These assignments are illustrated by the formal charge patterns in http://www.chem.ucla.edu/~harding/tutorials/formalcharge.pdf """ from moldesign.exceptions import UnhandledValenceError # TODO: scrape formal charge data from the PDB chem comp dictionary # cache these values in case we fail to assign charges totalcharge = mol.charge oldcharges = [atom.formal_charge for atom in mol.atoms] for atom in mol.atoms: if ignore_nonzero and atom.formal_charge != 0: continue v = atom.valence newcharge = None if atom.atnum in ATNUM_VALENCE_CHARGE: if v in ATNUM_VALENCE_CHARGE[atom.atnum]: newcharge = ATNUM_VALENCE_CHARGE[atom.atnum][v] else: for oldcharge, a in zip(oldcharges, mol.atoms): a.oldcharge = oldcharge mol.charge = totalcharge raise UnhandledValenceError(atom) elif atom in ION_CHARGE and v == 0: newcharge = ION_CHARGE[atom.atnum] if newcharge is not None: mol.charge += newcharge * u.q_e - atom.formal_charge atom.formal_charge = newcharge * u.q_e @toplevel def set_hybridization_and_saturate(mol): """ Assign bond orders, saturate with hydrogens, and assign formal charges Specifically, this is a convenience function that runs: ``mdt.guess_bond_orders``, ``mdt.add_hydrogen``, and ``mdt.assign_formal_charges`` Note: This does NOT add missing residues to biochemical structures. This functionality will be available as :meth:`moldesign.add_missing_residues` Args: mol (moldesign.Molecule): molecule to clean Returns: moldesign.Molecule: cleaned version of the molecule """ m1 = mdt.guess_bond_orders(mol) m2 = mdt.add_hydrogen(m1) assign_formal_charges(m2) return m2 @toplevel def guess_histidine_states(mol): """ Attempt to assign protonation states to histidine residues. Note: This function is highly unlikely to give accurate results! It is intended for convenience when histidine states can easily be guessed from already-present hydrogens or when they are judged to be relatively unimportant. This can be done simply by renaming HIS residues: 1. If HE2 and HD1 are present, the residue is renamed to HIP 2. If only HE2 is present, the residue is renamed to HIE 3. Otherwise, the residue is renamed to HID (the most common form) Args: mol (moldesign.Molecule): molecule to change (in place) """ for residue in mol.residues: if residue.resname == 'HIS': oldname = str(residue) if 'HE2' in residue and 'HD1' in residue: residue.resname = 'HIP' elif 'HE2' in residue: residue.resname = 'HIE' else: residue.resname = 'HID' print('Renaming %s from HIS to %s' % (oldname, residue.resname)) @toplevel def split_chains(mol, distance_threshold=1.75*u.angstrom): """ Split a molecule's chains into unbroken biopolymers and groups of non-polymers This function is non-destructive - the passed molecule will not be modified. Specifically, this function will: - Split any chain with non-contiguous biopolymeric pieces into single, contiguous polymers - Remove any solvent molecules from a chain into their own chain - Isolate ligands from each chain into their own chains Args: mol (mdt.Molecule): Input molecule distance_threshold (u.Scalar[length]): if not ``None``, the maximum distance between adjacent residues for which we consider them "contiguous". For PDB data, values greater than 1.4 Angstrom are eminently reasonable; the default threshold of 1.75 Angstrom is purposefully set to be extremely cautious (and still much lower than the distance to the *next* nearest neighbor, generally around 2.5 Angstrom) Returns: mdt.Molecule: molecule with separated chains """ tempmol = mol.copy() def bonded(r1, r2): if r2 not in r1.bonded_residues: return False if distance_threshold is not None and r1.distance(r2) > distance_threshold: return False return True def addto(chain, res): res.chain = None chain.add(res) allchains = [mdt.Chain(tempmol.chains[0].name)] for chain in tempmol.chains: chaintype = chain.residues[0].type solventchain = mdt.Chain(None) ligandchain = mdt.Chain(None) for ires, residue in enumerate(chain.residues): if residue.type == 'unknown': thischain = ligandchain elif residue.type in ('water', 'solvent', 'ion'): thischain = solventchain else: assert residue.type == chaintype if ires != 0 and not bonded(residue.prev_residue, residue): allchains.append(mdt.Chain(None)) thischain = allchains[-1] addto(thischain, residue) for c in (solventchain, ligandchain): if c.num_atoms > 0: allchains.append(c) return mdt.Molecule(allchains)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/tools/build.py
.py
3,448
86
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import string import moldesign as mdt import moldesign.molecules from moldesign.interfaces.ambertools import build_bdna, build_dna_helix from . import toplevel, __all__ as _pkgall _pkgall.extend(['build_bdna', 'build_dna_helix']) @toplevel def build_assembly(mol, assembly_name): """ Create biological assembly using a bioassembly specification. This routine builds a biomolecular assembly using the specification from a PDB header (if present, this data can be found in the "REMARK 350" lines in the PDB file). Assemblies are author-assigned structures created by copying, translating, and rotating a subset of the chains in the PDB file. See Also: http://pdb101.rcsb.org/learn/guide-to-understanding-pdb-data/biological-assemblies Args: mol (moldesign.Molecule): Molecule with assembly data (assembly data will be created by the PDB parser at ``molecule.properties.bioassembly``) assembly_name (str OR int): id of the biomolecular assembly to build. Returns: mol (moldesign.Molecule): molecule containing the complete assembly Raises: AttributeError: If the molecule does not contain any biomolecular assembly data KeyError: If the specified assembly is not present """ if isinstance(assembly_name, int): assembly_name = str(assembly_name) if 'bioassemblies' not in mol.properties: raise AttributeError('This molecule does not contain any biomolecular assembly data') try: asm = mol.properties.bioassemblies[assembly_name] except KeyError: raise KeyError(('The specified assembly name ("%s") was not found. The following ' 'assemblies are present: %s') % (assembly_name, ', '.join(list(mol.properties.bioassemblies.keys())))) # Make sure each chain gets a unique name - up to all the letters in the alphabet, anyway used_chain_names = set() alpha = iter(string.ascii_uppercase) # Create the new molecule by copying, transforming, and renaming the original chains all_atoms = moldesign.molecules.atomcollections.AtomList() for i, t in enumerate(asm.transforms): for chain_name in asm.chains: chain = mol.chains[chain_name].copy() chain.transform(t) while chain.name in used_chain_names: chain.name = next(alpha) used_chain_names.add(chain.name) chain.pdbname = chain.pdbindex = chain.name all_atoms.extend(chain.atoms) newmol = mdt.Molecule(all_atoms, name="%s (bioassembly %s)" % (mol.name, assembly_name)) return newmol
Python
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Tutorial 2. Biochemical basics.ipynb
.ipynb
6,849
264
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<span style=\"float:right\"><a href=\"http://moldesign.bionano.autodesk.com/\" target=\"_blank\" title=\"About\">About</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"https://github.com/autodesk/molecular-design-toolkit/issues\" target=\"_blank\" title=\"Issues\">Issues</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://bionano.autodesk.com/MolecularDesignToolkit/explore.html\" target=\"_blank\" title=\"Tutorials\">Tutorials</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://autodesk.github.io/molecular-design-toolkit/\" target=\"_blank\" title=\"Documentation\">Documentation</a></span>\n", "</span>\n", "![Molecular Design Toolkit](img/Top.png)\n", "<br>\n", "\n", "\n", "<center><h1>Tutorial 2: Playing with proteins</h1></center>\n", "\n", "Here, you'll see how to build, visualize, and simulate a protein structure from the PDB." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# First, import MDT\n", "import moldesign as mdt\n", "from moldesign import units as u\n", "\n", "# This sets up your notebook to draw inline plots:\n", "%matplotlib inline\n", "import numpy as np\n", "from matplotlib.pylab import *\n", "\n", "try: import seaborn\n", "except ImportError: pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contents\n", "=======\n", "---\n", " - [1. Download from PDB](#1.-Download-from-PDB)\n", " - [2. Strip water and assign forcefield](#2.-Strip-water-and-assign-forcefield)\n", " - [3. Set up energy model and minimize](#3.-Set-up-energy-model-and-minimize)\n", " - [4. Add integrator and run dynamics](#4.-Add-integrator-and-run-dynamics)\n", " - [5. Some simple analysis](#5.-Some-simple-analysis)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Download from PDB\n", "In this example, we'll look at `1YU8`, a crystal structure of the Villin Headpiece." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "one_yu8 = mdt.read('data/1yu8.pdb')\n", "one_yu8.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By evaluating the `one_yu8` variable, you can get some basic biochemical information, including metadata about missing residues in this crystal structure (hover over the amino acid sequence to get more information)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "one_yu8" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. Strip water and assign forcefield\n", "\n", "Next, we isolate the protein and prepare it using the default Amber forcefield parameters." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "headpiece = mdt.Molecule([res for res in one_yu8.residues if res.type == 'protein'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ff = mdt.forcefields.DefaultAmber()\n", "protein = ff.create_prepped_molecule(headpiece)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. Set up energy model and minimize\n", "\n", "Next, we'll set up a full molecular mechanics model using OpenMM, then run a minimization and visualize it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "protein.set_energy_model(mdt.models.OpenMMPotential)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "protein.configure_methods()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mintraj = protein.minimize()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mintraj.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. Add integrator and run dynamics" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "protein.set_integrator(mdt.integrators.OpenMMLangevin,\n", " temperature=300*u.kelvin,\n", " timestep=2.0*u.fs,\n", " frame_interval=2.0*u.ps)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "traj = protein.run(20*u.ps)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "traj.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 5. Some simple analysis\n", "As in tutorial 1, tutorial objects permit a range of timeseries-based analyses." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot kinetic energy vs. time\n", "plot(traj.time, traj.kinetic_energy)\n", "xlabel('time / %s' % u.default.time); ylabel('energy / %s' % u.default.energy)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot time evolution of PHE47's sidechain rotation\n", "residue = protein.chains[0].residues['PHE47']\n", "plot(traj.time, traj.dihedral(residue['CA'], residue['CB']).to(u.degrees))\n", "\n", "title('sidechain rotation vs time')\n", "xlabel('time / %s' % u.default.time); ylabel(u'angle / º')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot distance between C-terminus and N-terminus\n", "chain = protein.chains[0]\n", "plot(traj.time, traj.distance(chain.n_terminal.atoms['N'],\n", " chain.c_terminal.atoms['C']))\n", "\n", "plt.title('bond length vs time')\n", "xlabel('time / %s' % u.default.time); ylabel('distance / %s' % u.default.length)" ] } ], "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" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb
.ipynb
10,729
350
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<span style=\"float:right\"><a href=\"http://moldesign.bionano.autodesk.com/\" target=\"_blank\" title=\"About\">About</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"https://github.com/autodesk/molecular-design-toolkit/issues\" target=\"_blank\" title=\"Issues\">Issues</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://bionano.autodesk.com/MolecularDesignToolkit/explore.html\" target=\"_blank\" title=\"Tutorials\">Tutorials</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://autodesk.github.io/molecular-design-toolkit/\" target=\"_blank\" title=\"Documentation\">Documentation</a></span>\n", "</span>\n", "![Molecular Design Toolkit](img/Top.png)\n", "<br>\n", "\n", "<center><h1>Example 4: The Dynamics of HIV Protease bound to a small molecule </h1> </center>\n", "\n", "This notebook prepares a co-crystallized protein / small molecule ligand structure from [the PDB database](http://www.rcsb.org/pdb/home/home.do) and prepares it for molecular dynamics simulation. \n", "\n", " - _Author_: [Aaron Virshup](https://github.com/avirshup), Autodesk Research<br>\n", " - _Created on_: August 9, 2016\n", " - _Tags_: HIV Protease, small molecule, ligand, drug, PDB, MD" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import moldesign as mdt\n", "import moldesign.units as u" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contents\n", "=======\n", "---\n", " - [I. The crystal structure](#I.-The-crystal-structure)\n", " - [A. Download and visualize](#A.-Download-and-visualize)\n", " - [B. Try assigning a forcefield](#B.-Try-assigning-a-forcefield)\n", " - [II. Parameterizing a small molecule](#II.-Parameterizing-a-small-molecule)\n", " - [A. Isolate the ligand](#A.-Isolate-the-ligand)\n", " - [B. Assign bond orders and hydrogens](#B.-Assign-bond-orders-and-hydrogens)\n", " - [C. Generate forcefield parameters](#C.-Generate-forcefield-parameters)\n", " - [III. Prepping the protein](#III.-Prepping-the-protein)\n", " - [A. Strip waters](#A.-Strip-waters)\n", " - [B. Histidine](#B.-Histidine)\n", " - [IV. Prep for dynamics](#IV.-Prep-for-dynamics)\n", " - [A. Assign the forcefield](#A.-Assign-the-forcefield)\n", " - [B. Attach and configure simulation methods](#B.-Attach-and-configure-simulation-methods)\n", " - [D. Equilibrate the protein](#D.-Equilibrate-the-protein)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## I. The crystal structure\n", "\n", "First, we'll download and investigate the [3AID crystal structure](http://www.rcsb.org/pdb/explore.do?structureId=3aid).\n", "\n", "### A. Download and visualize" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "protease = mdt.from_pdb('3AID')\n", "protease" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "protease.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### B. Try assigning a forcefield" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This structure is not ready for MD - this command will raise a `ParameterizationError` Exception. After running this calculation, click on the **Errors/Warnings** tab to see why." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "amber_ff = mdt.forcefields.DefaultAmber()\n", "newmol = amber_ff.create_prepped_molecule(protease)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You should see 3 errors: \n", " 1. The residue name `ARQ` not recognized\n", " 1. Atom `HD1` in residue `HIS69`, chain `A` was not recognized\n", " 1. Atom `HD1` in residue `HIS69`, chain `B` was not recognized\n", " \n", "(There's also a warning about bond distances, but these can be generally be fixed with an energy minimization before running dynamics)\n", "\n", "We'll start by tackling the small molecule \"ARQ\"." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## II. Parameterizing a small molecule\n", "We'll use the GAFF (generalized Amber force field) to create force field parameters for the small ligand.\n", "\n", "### A. Isolate the ligand\n", "Click on the ligand to select it, then we'll use that selection to create a new molecule." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sel = mdt.widgets.ResidueSelector(protease)\n", "sel" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "drugres = mdt.Molecule(sel.selected_residues[0])\n", "drugres.draw2d(width=700, show_hydrogens=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### B. Assign bond orders and hydrogens\n", "A PDB file provides only limited information; they often don't provide indicate bond orders, hydrogen locations, or formal charges. These can be added, however, with the `add_missing_pdb_data` tool:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "drugmol = mdt.tools.set_hybridization_and_saturate(drugres)\n", "drugmol.draw(width=500)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "drugmol.draw2d(width=700, show_hydrogens=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### C. Generate forcefield parameters\n", "\n", "We'll next generate forcefield parameters using this ready-to-simulate structure.\n", "\n", "**NOTE**: for computational speed, we use the `gasteiger` charge model. This is not advisable for production work! `am1-bcc` or `esp` are far likelier to produce sensible results." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "drug_parameters = mdt.create_ff_parameters(drugmol, charges='gasteiger')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## III. Prepping the protein\n", "\n", "Section II. dealt with getting forcefield parameters for an unknown small molecule. Next, we'll prep the other part of the structure.\n", "\n", "### A. Strip waters\n", "\n", "Waters in crystal structures are usually stripped from a simulation as artifacts of the crystallization process. Here, we'll remove the waters from the protein structure." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dehydrated = mdt.Molecule([atom for atom in protease.atoms if atom.residue.type != 'water'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### B. Histidine\n", "Histidine is notoriously tricky, because it exists in no less than three different protonation states at biological pH (7.4) - the \"delta-protonated\" form, referred to with residue name `HID`; the \"epsilon-protonated\" form aka `HIE`; and the doubly-protonated form `HIP`, which has a +1 charge. Unfortunately, crystallography isn't usually able to resolve the difference between these three.\n", "\n", "Luckily, these histidines are pretty far from the ligand binding site, so their protonation is unlikely to affect the dynamics. We'll therefore use the `guess_histidine_states` function to assign a reasonable starting guess." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mdt.guess_histidine_states(dehydrated)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## IV. Prep for dynamics\n", "\n", "With these problems fixed, we can succesfully assigne a forcefield and set up the simulation.\n", "\n", "### A. Assign the forcefield\n", "Now that we have parameters for the drug and have dealt with histidine, the forcefield assignment will succeed:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "amber_ff = mdt.forcefields.DefaultAmber()\n", "amber_ff.add_ff(drug_parameters)\n", "sim_mol = amber_ff.create_prepped_molecule(dehydrated)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### B. Attach and configure simulation methods\n", "\n", "Armed with the forcefield parameters, we can connect an energy model to compute energies and forces, and an integrator to create trajectories:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sim_mol.set_energy_model(mdt.models.OpenMMPotential, implicit_solvent='obc', cutoff=8.0*u.angstrom)\n", "sim_mol.set_integrator(mdt.integrators.OpenMMLangevin, timestep=2.0*u.fs)\n", "sim_mol.configure_methods()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### C. Equilibrate the protein\n", "The next series of cells first minimize the crystal structure to remove clashes, then heats the system to 300K." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mintraj = sim_mol.minimize()\n", "mintraj.draw()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "traj = sim_mol.run(20*u.ps)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "viewer = traj.draw(display=True)\n", "viewer.autostyle()" ] }, { "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" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Getting Started.ipynb
.ipynb
2,498
80
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "![Molecular Design Toolkit](img/Header.png)\n", "\n", "<br>\n", "\n", "# Get started \n", "\n", "Get started with these step-by-step demonstration notebooks. Check out the accompanying [video tutorials](https://www.youtube.com/channel/UCRmzThLOYJ3Tx1e81fXRfOA).\n", "\n", "* [Tutorial 1. Making a molecule](Tutorial 1. Making a molecule.ipynb)\n", "* [Tutorial 2. Biochemical basics](Tutorial 2. Biochemical basics.ipynb)\n", "* [Tutorial 3. Quantum Chemistry](Tutorial 3. Quantum Chemistry.ipynb)\n", "\n", "\n", "# Keep going\n", "\n", "* [Example 1. Build and simulate DNA](Example 1. Build and simulate DNA.ipynb)\n", "* [Example 2. UV-vis absorption spectra](Example 2. UV-vis absorption spectra.ipynb)\n", "* [Example 3. Simulating a crystal structure](Example 3. Simulating a crystal structure.ipynb)\n", "* [Example 4. HIV Protease bound to an inhibitor](Example 4. HIV Protease bound to an inhibitor.ipynb)\n", "* [Example 5. Enthalpic barriers](Example 5. Enthalpic barriers.ipynb)\n", "\n", "\n", "# Read the docs\n", "* [Molecular Design Toolkit Documentation](http://autodesk.github.io/molecular-design-toolkit/)\n", "* [Using Jupyter Notebooks](http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html \"Title\")\n", "\n", "\n", "# Get in touch\n", " * [Learn more](http://lifesciences.autodesk.com/) about Life Sciences at Autodesk.\n", "\n", "\n", "# Get help\n", " * [File a bug report](https://github.com/autodesk/molecular-design-toolkit/issues)\n", " * [Contact us](mailto:moleculardesigntoolkit@autodesk.com)\n", "\n", "Contact us at moleculardesigntoolkit@autodesk.com\n", "\n", "\n", "![Molecular Design Toolkit](img/Molecules.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "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.6.1" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Tutorial 3. Quantum Chemistry.ipynb
.ipynb
10,473
415
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<span style=\"float:right\"><a href=\"http://moldesign.bionano.autodesk.com/\" target=\"_blank\" title=\"About\">About</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"https://github.com/autodesk/molecular-design-toolkit/issues\" target=\"_blank\" title=\"Issues\">Issues</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://bionano.autodesk.com/MolecularDesignToolkit/explore.html\" target=\"_blank\" title=\"Tutorials\">Tutorials</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://autodesk.github.io/molecular-design-toolkit/\" target=\"_blank\" title=\"Documentation\">Documentation</a></span>\n", "</span>\n", "![Molecular Design Toolkit](img/Top.png)\n", "<br>\n", "\n", "\n", "<center><h1>Tutorial 3: Intro to Quantum Chemistry </h1> </center>\n", "---\n", "\n", "This tutorial shows how to select a quantum chemistry method, visualize orbitals, and analyze the electronic wavefunction." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import numpy as np\n", "from matplotlib.pylab import *\n", "try: import seaborn #optional, makes plots look nicer\n", "except ImportError: pass\n", "\n", "import moldesign as mdt\n", "from moldesign import units as u" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## I. Build and minimize minimal basis set hydrogen\n", "\n", "### A. Build the molecule\n", "This cell builds H<sub>2</sub> by creating the two atoms, and explicitly setting their positions.\n", "\n", "**Try editing this cell to**:\n", " * Create HeH<sup>+</sup>\n", " * Create H<sub>3</sub><sup>+</sup>\n", " * Change the atoms' initial positions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "atom1 = mdt.Atom('H')\n", "atom2 = mdt.Atom('H')\n", "atom1.bond_to(atom2,1)\n", "atom2.x = 2.0 * u.angstrom\n", "\n", "h2 = mdt.Molecule([atom1,atom2], name='H2', charge=0)\n", "h2.draw(height=300)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### B. Run a hartree-fock calculation\n", "The next cell adds the RHF energy model to our molecule, then triggers a calculation.\n", "\n", "**Try editing this cell to**:\n", " * Change the atomic basis\n", " * Get a list of other available energy models (type `mdt.models.` and then hit the `[tab]` key)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "h2.set_energy_model(mdt.models.RHF, basis='3-21g')\n", "h2.calculate()\n", "\n", "print('Calculated properties:', h2.properties.keys())\n", "\n", "print('Potential energy:', h2.potential_energy)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### C. Visualize the orbitals\n", "After running the calculation, we have enough information to visualize the molecular orbitals." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "h2.draw_orbitals()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### D. Minimize the energy\n", "Here, we'll run a quick energy minimization then visualize how the hydrogen nuclei AND the atomic wavefunctions changed." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "minimization = h2.minimize(frame_interval=1, nsteps=10)\n", "minimization.draw_orbitals()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# II. Analyzing the wavefunction\n", "\n", "The wavefunction created during QM calculations will be stored as an easy-to-analyze python object:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "wfn = h2.wfn\n", "wfn" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A. Molecular orbital data\n", "First, let's examine the molecular orbitals. The overlaps, fock matrix, coefficents, and density matrix are all available as 2D numpy arrays (with units where applicable).\n", "\n", "We'll specifically look at the \"canonical\" orbitals that result from Hartree-Fock calculations." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mos = wfn.orbitals.canonical\n", "mos" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "MOs are, of course, a linear combination of AOs:\n", "\n", "\\begin{equation} \\left| \\text{MO}_i \\right \\rangle = \\sum_j c_{ij} \\left| \\text{AO}_j \\right\\rangle \\end{equation}\n", "\n", "The coefficient $c_{ij}$ is stored at `mos.coeffs[i,j]`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mos.coeffs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Most MO sets are orthogonal; their overlaps will often be the identity matrix (plus some small numerical noise)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mos.overlaps" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By definition, the fock matrix should be orthogonal as well; the orbital energies are on its diagonal." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "matshow(mos.fock.value_in(u.eV), cmap=cm.seismic)\n", "colorbar(label='fock element/eV')\n", "title('Fock matrix')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `MolecularOrbitals` class also offers several methods to transform operators into different bases. For instance, the `overlap` method creates an overlap matrix between the AOs and MOs, where `olap[i,j]` is the overlap between MO _i_ and AO _j_:\n", "\\begin{equation}\n", "\\text{olap[i,j]} = \\left\\langle MO_i \\middle| AO_j \\right \\rangle\n", "\\end{equation}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "olap = mos.overlap(wfn.aobasis)\n", "olap" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Various other matrices are available from this this object, such as the two-electron Hamiltonian terms:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "matshow(mos.h2e.value_in(u.eV), cmap=cm.inferno)\n", "colorbar(label='2-electron hamiltonian term / eV')\n", "title('2-electron hamiltonian')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## B. Individual orbitals\n", "\n", "You can work with inidividual orbitals as well. For instance, to get a list (in order) of our four atomic orbitals (i.e., the basis functions):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "aos = wfn.orbitals.atomic\n", "aos[:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's grab the lowest orbital and examine some of its properties:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "orb = aos[0]\n", "print('Name:', orb.name)\n", "print('Energy:', orb.energy)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Orbital objects also give you access to various matrix elements:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ha_1s = aos[0]\n", "hb_1s = aos[3]\n", "\n", "print('Overlap between 1s orbitals: ', ha_1s.overlap(hb_1s))\n", "print('Fock element between 1s orbitals', ha_1s.fock_element(hb_1s))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## C. Basis functions\n", "\n", "An object representing the wavefunction's basis functions is available at `wfn.aobasis`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "wfn.aobasis" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It stores a list of `AtomicBasisFunction` objects:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "basis_function = wfn.aobasis[0]\n", "print('Name:', basis_function.name)\n", "print('Angular quantum number:', basis_function.l)\n", "print('Azimuthal quantum number:', basis_function.m)\n", "print('Centered at:', basis_function.center)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each basis function is defined as a linear combination of \"primitive\" 3D Gaussian functions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "basis_function.primitives" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And these primitives can themselves be examined:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "primitive = basis_function.primitives[0]\n", "print(primitive)\n", "print(\"Coeff:\", primitive.coeff)\n", "print(\"Alpha:\", primitive.alpha)" ] }, { "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" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Example 1. Build and simulate DNA.ipynb
.ipynb
9,215
330
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<span style=\"float:right\"><a href=\"http://moldesign.bionano.autodesk.com/\" target=\"_blank\" title=\"About\">About</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"https://github.com/autodesk/molecular-design-toolkit/issues\" target=\"_blank\" title=\"Issues\">Issues</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://bionano.autodesk.com/MolecularDesignToolkit/explore.html\" target=\"_blank\" title=\"Tutorials\">Tutorials</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://autodesk.github.io/molecular-design-toolkit/\" target=\"_blank\" title=\"Documentation\">Documentation</a></span>\n", "</span>\n", "![Molecular Design Toolkit](img/Top.png)\n", "<br>\n", "\n", "<center><h1>Example 1: Build and simulate DNA </h1> </center>\n", "---\n", "\n", "\n", "This notebook builds a small DNA double helix, assigns a forcefield to it, and runs a molecular dynamics simulation.\n", "\n", " - _Author_: [Aaron Virshup](https://github.com/avirshup), Autodesk Research<br>\n", " - _Created on_: July 1, 2016\n", " - _Tags_: DNA, molecular dynamics\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import moldesign as mdt\n", "from moldesign import units as u\n", "\n", "%matplotlib inline\n", "from matplotlib.pyplot import *\n", "\n", "# seaborn is optional -- it makes plots nicer\n", "try: import seaborn \n", "except ImportError: pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contents\n", "=======\n", "---\n", " - [1. Create a DNA helix](#1.-Create-a-DNA-helix)\n", " - [2. Forcefield](#2.-Forcefield)\n", " - [3. Constraints](#3.-Constraints)\n", " - [4. MD Setup](#4.-MD-Setup)\n", " - [5. Minimization](#5.-Minimization)\n", " - [6. Dynamics](#6.-Dynamics)\n", " - [7. Analysis](#7.-Analysis)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Create a DNA helix" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dna_structure = mdt.build_dna_helix('ACTGACTG', helix_type='b')\n", "dna_structure.draw()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dna_structure" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Forcefield\n", "The cell below adds forcefield parameters to the molecule.\n", "\n", "**NOTE:** This molecule because is not missing expected atoms. If your molecule _is_ missing atoms (e.g., it's missing its hydrogens), use the `Forcefield.create_prepped_molecule` method instead of `Forcefield.assign`.\n", "\n", "**Click on the ERRORS/WARNING tab** to see any warnings raised during assignment." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ff = mdt.forcefields.DefaultAmber()\n", "ff.assign(dna_structure)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Constraints\n", "This section uses an interactive selection to constrain parts of the DNA.\n", "\n", "After executing the following cells, **click on the 3' and 5' bases:**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rs = mdt.widgets.ResidueSelector(dna_structure)\n", "rs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if len(rs.selected_residues) == 0:\n", " raise ValueError(\"You didn't click on anything!\")\n", " \n", "rs.selected_residues" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for residue in rs.selected_residues:\n", " print('Constraining position for residue %s' % residue)\n", " \n", " for atom in residue.atoms:\n", " dna_structure.constrain_atom(atom)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, fixing the positions of the terminal base pairs is a fairly extreme step. For extra credit, see if you can find a less heavy-handed keep the terminal base pairs bonded. (Try using tab-completion to see what other constraint methods are available)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. MD Setup\n", "This section adds an OpenMM energy model and a Langevin integrator to the DNA." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dna_structure.set_energy_model(mdt.models.OpenMMPotential,\n", " implicit_solvent='obc')\n", "\n", "dna_structure.set_integrator(mdt.integrators.OpenMMLangevin,\n", " timestep=2.0*u.fs,\n", " temperature=300.0*u.kelvin,\n", " frame_interval=1.0*u.ps)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can interactively configure these methods:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dna_structure.configure_methods()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Minimization\n", "\n", "Nearly every MD simulation should be preceded by an energy minimization, especially for crystal structure data. This will remove any energetically catastrophic clashes between atoms and prevent our simulation from blowing up." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trajectory = dna_structure.minimize(nsteps=200)\n", "trajectory.draw()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot(trajectory.potential_energy)\n", "\n", "xlabel('steps');ylabel('energy / %s' % trajectory.unit_system.energy)\n", "title('Energy relaxation'); grid('on')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Dynamics\n", "We're ready to run 25 picoseconds of dynamics at room temperature (that's 300º Kelvin). This will probably take a few minutes - if you're on an especially pokey computer, you might want to reduce the length of the simulation." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "traj = dna_structure.run(run_for=25.0*u.ps)\n", "traj.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Analysis\n", "The trajectory object (named `traj`) gives direct access to the timeseries data:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot(traj.time, traj.kinetic_energy, label='kinetic energy')\n", "plot(traj.time, traj.potential_energy - traj.potential_energy[0], label='potential_energy')\n", "xlabel('time / {time.units}'.format(time=traj.time))\n", "ylabel('energy / {energy.units}'.format(energy=traj.kinetic_energy))\n", "title('Energy vs. time'); legend(); grid('on')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Using the trajectory's 'plot' method will autogenerate axes labels with the appropriate units\n", "traj.plot('time','kinetic_temperature')\n", "title('Temperature'); grid('on')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This cell sets up an widget that plots the RMSDs of any selected group of atoms.\n", "**Select a group of atoms, then click \"Run plot_rmsd\" to generate a plot**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from ipywidgets import interact_manual\n", "from IPython.display import display\n", "\n", "rs = mdt.widgets.ResidueSelector(dna_structure)\n", "def plot_rmsd(): \n", " plot(traj.time, traj.rmsd(rs.selected_atoms))\n", " xlabel('time / fs'); ylabel(u'RMSD / Å')\n", "interact_manual(plot_rmsd, description='plot rmsd')\n", "rs" ] }, { "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" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Tutorial 1. Making a molecule.ipynb
.ipynb
7,813
289
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<span style=\"float:right\"><a href=\"http://moldesign.bionano.autodesk.com/\" target=\"_blank\" title=\"About\">About</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"https://github.com/autodesk/molecular-design-toolkit/issues\" target=\"_blank\" title=\"Issues\">Issues</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://bionano.autodesk.com/MolecularDesignToolkit/explore.html\" target=\"_blank\" title=\"Tutorials\">Tutorials</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://autodesk.github.io/molecular-design-toolkit/\" target=\"_blank\" title=\"Documentation\">Documentation</a></span>\n", "</span>\n", "![Molecular Design Toolkit](img/Top.png)\n", "<br>\n", "\n", "<center><h1>Tutorial 1: Making a molecule</h1></center>\n", "\n", "This notebook gets you started with MDT - you'll build a small molecule, visualize it, and run a basic calculation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contents\n", "=======\n", "---\n", " - [1. Import the toolkit](#1.-Import-the-toolkit)\n", " - [A. Optional: Set up your computing backend](#A.-Optional:-Set-up-your-computing-backend)\n", " - [2. Build it](#2.-Read-in-the-molecule)\n", " - [3. View it](#3.-Visualize-it)\n", " - [4. Simulate it](#4.-Simulate-it)\n", " - [5. Minimize it](#5.-Minimize-it)\n", " - [6. Write it](#6.-Write-it)\n", " - [7. Examine it](#7.-Examine-it)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Import the toolkit\n", "This cell loads the toolkit and its unit system. To execute a cell, click on it, then press <kbd>shift</kbd> + <kbd>enter</kbd>. (If you're new to the notebook environment, you may want to check out [this helpful cheat sheet](https://nbviewer.jupyter.org/github/jupyter/notebook/blob/master/docs/source/examples/Notebook/Notebook%20Basics.ipynb))." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import moldesign as mdt\n", "import moldesign.units as u" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Optional: configuration options\n", "If you'd like to set some basic MDT configuration options, you can execute the following cell to create a GUI configuration editor:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mdt.configure()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Read in a molecular structure\n", "\n", "Let's get started by reading in a molecular structure file.\n", "\n", "When you execute this cell, you'll use `mdt.read` function to parse an XYZ-format file to create an MDT molecule object named, appropriately enough, `molecule`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "molecule = mdt.read('data/butane.xyz')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Jupyter notebooks will automatically print out the value of the last statement in any cell. When you evaluate a `Molecule`, as in the cell below, you'll get some quick summary data:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "molecule" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Visualize it\n", "MDT molecules have three built-in visualization methods - `draw`, `draw2d`, and `draw3d`. Try them out!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "viewer = molecule.draw()\n", "viewer # we tell Jupyter to draw the viewer by putting it on the last line of the cell" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try clicking on some of the atoms in the visualization you've just created.\n", "\n", "Afterwards, you can retrieve a list of the Python objects representing the atoms you clicked on:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(viewer.selected_atoms)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Simulate it\n", "\n", "So far, we've created a 3D molecular structure and visualized it right in the notebook.\n", "\n", "If you sat through [VSEPR theory](https://en.wikipedia.org/wiki/VSEPR_theory) in P. Chem, you might notice this molecule (butane) is looking decidedly non-optimal. Luckily, we can use simulation to predict a better structure.\n", "\n", "We're specifically going to run a basic type of Quantum Chemistry calculation called \"Hartree-Fock\", which will give us information about the molecule's orbitals and energy." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "molecule.set_energy_model(mdt.models.RHF, basis='sto-3g')\n", "properties = molecule.calculate()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(properties.keys())\n", "print('Energy: ', properties['potential_energy'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "molecule.draw_orbitals()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Minimize it\n", "\n", "Next, an energy minimization - that is, we're going to move the atoms around in order to find a minimum energy conformation. This is a great way to start cleaning up the messy structure we started with. The calculation might take a second or two ..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mintraj = molecule.minimize()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mintraj.draw_orbitals()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Write it" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "molecule.write('my_first_molecule.xyz')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mintraj.write('my_first_minimization.P.gz')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Play with it\n", "There are any number of directions to go from here. See how badly you can distort the geometry:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mdt.widgets.GeometryBuilder(molecule)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "molecule.calculate_potential_energy()" ] }, { "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" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Example 5. Enthalpic barriers.ipynb
.ipynb
9,049
308
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<span style=\"float:right\"><a href=\"http://moldesign.bionano.autodesk.com/\" target=\"_blank\" title=\"About\">About</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"https://github.com/autodesk/molecular-design-toolkit/issues\" target=\"_blank\" title=\"Issues\">Issues</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://bionano.autodesk.com/MolecularDesignToolkit/explore.html\" target=\"_blank\" title=\"Tutorials\">Tutorials</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://autodesk.github.io/molecular-design-toolkit/\" target=\"_blank\" title=\"Documentation\">Documentation</a></span>\n", "</span>\n", "![Molecular Design Toolkit](img/Top.png)\n", "<br>\n", "\n", "<center><h1>Example 5: Calculating torsional barriers with relaxation </h1> </center>\n", "\n", "---\n", "\n", "This workflow calculates the enthalpic barrier of a small alkane.\n", "\n", " - _Author_: [Aaron Virshup](https://github.com/avirshup), Autodesk Research<br>\n", " - _Created on_: September 23, 2016\n", " - _Tags_: reaction path, constrained minimization, torsion, enthalpic\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import moldesign as mdt\n", "from moldesign import units as u\n", "\n", "%matplotlib notebook\n", "from matplotlib.pyplot import *\n", "try: import seaborn # optional, makes graphs look better\n", "except ImportError: pass\n", "\n", "u.default.energy = u.kcalpermol # use kcal/mol for energy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contents\n", "=======\n", "---\n", " - [I. Create and minimize the molecule](#I.-Create-and-minimize-the-molecule)\n", " - [II. Select the torsional bond](#II.-Select-the-torsional-bond)\n", " - [III. Rigid rotation scan](#III.-Rigid-rotation-scan)\n", " - [IV. Relaxed rotation scan](#IV.-Relaxed-rotation-scan)\n", " - [V. Plot the potential energy surfaces](#V.-Plot-the-potential-energy-surfaces)\n", " - [VI. Investigate conformational changes](#VI.-Investigate-conformational-changes)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# I. Create and minimize the molecule" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mol = mdt.from_smiles('CCCC')\n", "mol.draw()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mol.set_energy_model(mdt.models.GaffSmallMolecule)\n", "mol.energy_model.configure()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "minimization = mol.minimize(nsteps=40)\n", "minimization.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# II. Select the torsional bond\n", "\n", "Next, we use the `BondSelector` to pick the bond that we'll rotate around." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bs = mdt.widgets.BondSelector(mol)\n", "bs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "twist = mdt.DihedralMonitor(bs.selected_bonds[0])\n", "twist" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# III. Rigid rotation scan\n", "\n", "First, we'll perform a simple energy scan, simply by rotating around the bond and calculating the energy at each point.\n", "\n", "This gives us only an _upper bound_ on the enthalpic rotation barrier. This is because we keep the molecule rigid, except for the single rotating bond." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "angles = np.arange(-150, 210, 5) * u.degree" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rigid = mdt.Trajectory(mol)\n", "for angle in angles:\n", " twist.value = angle\n", " mol.calculate()\n", " rigid.new_frame(annotation='angle: %s, energy: %s' % (twist.value.to(u.degrees), mol.potential_energy))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rigid.draw()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "figure()\n", "plot(angles, rigid.potential_energy)\n", "xlabel(u'dihedral / º'); ylabel('energy / kcal/mol')\n", "xticks(np.arange(-120,211,30))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# IV. Relaxed rotation scan\n", "\n", "Next, we'll get the *right* barrier (up to the accuracy of the energy model).\n", "\n", "Here, we'll rotate around the bond, but then perform a _constrained minimization_ at each rotation point. This will allow all other degrees of freedom to relax, thus finding lower energies at each point along the path. \n", "\n", "_Note_: In order to break any spurious symmetries, this loop also adds a little bit of random noise to each structure before performing the minimization." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "constraint = twist.constrain()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "relaxed = mdt.Trajectory(mol)\n", "for angle in angles:\n", " print(angle,':')\n", " \n", " #add random noise to break symmetry\n", " mol.positions += np.random.random(mol.positions.shape) * 0.01*u.angstrom\n", " mol.positions -= mol.center_of_mass\n", " \n", " twist.value = angle\n", " constraint.value = angle\n", " \n", " t = mol.minimize(nsteps=100)\n", " relaxed.new_frame(annotation='angle: %s, energy: %s' % (twist.value.to(u.degrees), mol.potential_energy))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "relaxed.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# V. Plot the potential energy surfaces\n", "\n", "If you plotted butane's rotation around its central bond, you'll see [three stable points](https://en.wikipedia.org/wiki/Alkane_stereochemistry#Conformation): two at about ±60º (the _gauche_ conformations), and one at 180º (the _anti_ conformation).\n", "\n", "You will likely see a large differences in the energetics of the relaxed and rigid scans; depending on the exact starting conformation, the rigid scan can overestimate the rotation barrier by as much as 5 kcal/mol!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "figure()\n", "plot(angles, rigid.potential_energy, label='rigid')\n", "plot(angles, relaxed.potential_energy, label='relaxed')\n", "plot(angles, abs(rigid.potential_energy - relaxed.potential_energy), label='error')\n", "xlabel(u'dihedral / º'); ylabel('energy / kcal/mol'); legend()\n", "xticks(np.arange(-120,211,30))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# VI. Investigate conformational changes\n", "\n", "This cell illustrates a simple interactive \"app\" - select the bonds you're interested in, then click the \"show_dihedral\" button to show their relaxed angles as a function of the central twist during the `relaxed` scan." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from ipywidgets import interact_manual\n", "\n", "bs = mdt.widgets.BondSelector(mol)\n", "def show_dihedral():\n", " figure()\n", " for bond in bs.selected_bonds:\n", " dihemon = mdt.DihedralMonitor(bond)\n", " plot(angles, dihemon(relaxed).to(u.degrees), label=str(bond))\n", " legend(); xlabel(u'central twist / º'); ylabel(u'bond twist / º')\n", "interact_manual(show_dihedral)\n", "bs" ] }, { "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" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Example 3. Simulating a crystal structure.ipynb
.ipynb
10,039
382
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<span style=\"float:right\"><a href=\"http://moldesign.bionano.autodesk.com/\" target=\"_blank\" title=\"About\">About</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"https://github.com/autodesk/molecular-design-toolkit/issues\" target=\"_blank\" title=\"Issues\">Issues</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://bionano.autodesk.com/MolecularDesignToolkit/explore.html\" target=\"_blank\" title=\"Tutorials\">Tutorials</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://autodesk.github.io/molecular-design-toolkit/\" target=\"_blank\" title=\"Documentation\">Documentation</a></span>\n", "</span>\n", "![Molecular Design Toolkit](img/Top.png)\n", "<br>\n", "\n", "<center><h1>Example 3: Simulating a Holliday Junction PDB assembly </h1> </center>\n", "\n", "---\n", "\n", "This notebook takes a crystal structure from the PDB and prepares it for simulation.\n", "\n", " - _Author_: [Aaron Virshup](https://github.com/avirshup), Autodesk Research\n", " - _Created on_: July 1, 2016\n", " - _Tags_: DNA, holliday junction, assembly, PDB, MD" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "from matplotlib.pyplot import *\n", "\n", "import moldesign as mdt\n", "from moldesign import units as u" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contents\n", "=======\n", "---\n", " - [A. View the crystal structure](#A.-View-the-crystal-structure)\n", " - [B. Build the biomolecular assembly](#B.-Build-the-biomolecular-assembly)\n", " - [C. Isolate the DNA](#C.-Isolate-the-DNA)\n", " - [D. Prep for simulation](#D.-Prep-for-simulation)\n", " - [E. Dynamics - equilibration](#E.-Dynamics---equilibration)\n", " - [F. Dynamics - production](#F.-Dynamics---production)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A. View the crystal structure\n", "\n", "We start by downloading the [1KBU](http://www.rcsb.org/pdb/explore.do?structureId=1kbu) crystal structure.\n", "\n", "It will generate several warnings. Especially note that it contains [biomolecular \"assembly\"](http://pdb101.rcsb.org/learn/guide-to-understanding-pdb-data/biological-assemblies) information. This means that the file from PDB doesn't contain the complete structure, but we can generate the missing parts using symmetry operations." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xtal = mdt.from_pdb('1kbu')\n", "xtal.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## B. Build the biomolecular assembly\n", "\n", "As you can read in the warning, 1KBU only has one biomolecular assembly, conveniently named `'1'`. This cell builds and views it:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "assembly = mdt.build_assembly(xtal, 1)\n", "assembly.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By evaulating the `assembly` object (it's a normal instance of the `moldesign.Molecule` class), we can get some information about it's content:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "assembly" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because we're only interested in DNA, we'll create a new molecule using only the DNA residues, and then assign a forcefield to it." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## C. Isolate the DNA\n", "\n", "This example will focus only on the DNA components of this structure, so we'll isolate the DNA atoms and create a new molecule from them.\n", "\n", "We could do this with a list comprehension, e.g.\n", "`mdt.Molecule([atom for atom in assembly.atoms if atom.residue.type == 'dna'])`\n", "\n", "Here, however we'll use a shortcut for this - the `molecule.get_atoms` method, which allows you to run queries on the atoms:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dna_atoms = assembly.get_atoms('dna')\n", "dna_only = mdt.Molecule(dna_atoms)\n", "dna_only.draw3d(display=True)\n", "dna_only" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## D. Prep for simulation\n", "Next, we'll assign a forcefield and energy model, then minimize the structure." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ff = mdt.forcefields.DefaultAmber()\n", "dna = ff.create_prepped_molecule(dna_only)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dna.set_energy_model(mdt.models.OpenMMPotential, implicit_solvent='obc')\n", "dna.configure_methods()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "minimization = dna.minimize()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "minimization.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## E. Dynamics - equilibration\n", "The structure is ready. We'll associate an integrator with the molecule, then do a 2 step equilibration - first freezing the peptide backbone and running 300K dynamics, then unfreezing and continuing dyanmics." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Freeze the backbone:\n", "for residue in dna.residues:\n", " for atom in residue.backbone:\n", " dna.constrain_atom(atom)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dna.set_integrator(mdt.integrators.OpenMMLangevin,\n", " timestep=2.0*u.fs,\n", " frame_interval=1.0*u.ps,\n", " remove_rotation=True)\n", "dna.integrator.configure()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now we run it. This is may take a while, depending on your hardware." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "equil1 = dna.run(20.0*u.ps)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "equil1.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Next**, we'll remove the constraints and do full dynamics:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dna.clear_constraints()\n", "equil2 = dna.run(20.0*u.ps)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "equil = equil1 + equil2\n", "equil.draw()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot(equil2.time, equil2.rmsd())\n", "xlabel('time / fs'); ylabel(u'rmsd / Å'); grid()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**NOTE:** THIS IS NOT A SUFFICIENT EQUILIBRATION FOR PRODUCTION MOLECULAR DYNAMICS! \n", "\n", "In practice, before going to \"production\", we would *at least* want to run dynamics until the RMSD and thermodynamic observabled have converged. A variety of equilibration protocols are used in practice, including slow heating, reduced coupling, multiple constraints, etc." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## F. Dynamics - production\n", "\n", "Assuming that we're satisfied with our system's equilibration, we now gather data for \"production\". This will take a while." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trajectory = dna.run(40.0*u.ps)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trajectory.draw()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## G. Save your results\n", "Any MDT object can be saved to disk. We recommend saving objects with the \"Pickle\" format to make sure that all the data is preserved.\n", "\n", "This cell saves the final trajectory to disk as a compressed pickle file:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trajectory.write('holliday_traj.P.gz')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To load the saved object, use:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "traj = mdt.read('holliday_traj.P.gz')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "traj.draw()" ] } ], "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" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/Example 2. UV-vis absorption spectra.ipynb
.ipynb
7,656
243
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<span style=\"float:right\"><a href=\"http://moldesign.bionano.autodesk.com/\" target=\"_blank\" title=\"About\">About</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"https://github.com/autodesk/molecular-design-toolkit/issues\" target=\"_blank\" title=\"Issues\">Issues</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://bionano.autodesk.com/MolecularDesignToolkit/explore.html\" target=\"_blank\" title=\"Tutorials\">Tutorials</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://autodesk.github.io/molecular-design-toolkit/\" target=\"_blank\" title=\"Documentation\">Documentation</a></span>\n", "</span>\n", "![Molecular Design Toolkit](img/Top.png)\n", "<br>\n", "\n", "<center><h1>Example 2: Using MD sampling to calculate UV-Vis spectra</h1> </center>\n", "\n", "---\n", "\n", "This notebook uses basic quantum chemical calculations to calculate the absorption spectra of a small molecule.\n", "\n", " - _Author_: [Aaron Virshup](https://github.com/avirshup), Autodesk Research<br>\n", " - _Created on_: September 23, 2016\n", " - _Tags_: excited states, CASSCF, absorption, sampling\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import numpy as np\n", "from matplotlib.pylab import *\n", "\n", "try: import seaborn #optional, makes plots look nicer\n", "except ImportError: pass\n", "\n", "import moldesign as mdt\n", "from moldesign import units as u" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contents\n", "=======\n", "---\n", " - [Single point](#Single-point)\n", " - [Sampling](#Sampling)\n", " - [Post-processing](#Post-processing)\n", " - [Create spectrum](#Create-spectrum)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Single point\n", "\n", "Let's start with calculating the vertical excitation energy and oscillator strengths at the ground state minimum (aka Franck-Condon) geometry.\n", "\n", "Note that the active space and number of included states here is system-specific." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "qmmol = mdt.from_name('benzene')\n", "qmmol.set_energy_model(mdt.models.CASSCF, active_electrons=6,\n", " active_orbitals=6, state_average=6, basis='sto-3g')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "properties = qmmol.calculate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This cell print a summary of the possible transitions. \n", "\n", "Note: you can convert excitation energies directly to nanometers using [Pint](https://pint.readthedocs.io) by calling `energy.to('nm', 'spectroscopy')`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for fstate in range(1, len(qmmol.properties.state_energies)):\n", " excitation_energy = properties.state_energies[fstate] - properties.state_energies[0]\n", " \n", " print('--- Transition from S0 to S%d ---' % fstate ) \n", " print('Excitation wavelength: %s' % excitation_energy.to('nm', 'spectroscopy'))\n", " print('Oscillator strength: %s' % qmmol.properties.oscillator_strengths[0,fstate])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sampling\n", "\n", "Of course, molecular spectra aren't just a set of discrete lines - they're broadened by several mechanisms. We'll treat vibrations here by sampling the molecule's motion on the ground state at 300 Kelvin.\n", "\n", "To do this, we'll sample its geometries as it moves on the ground state by:\n", " 1. Create a copy of the molecule\n", " 2. Assign a forcefield (GAFF2/AM1-BCC)\n", " 3. Run dynamics for 5 ps, taking a snapshot every 250 fs, for a total of 20 separate geometries." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mdmol = mdt.Molecule(qmmol)\n", "mdmol.set_energy_model(mdt.models.GaffSmallMolecule)\n", "mdmol.minimize()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mdmol.set_integrator(mdt.integrators.OpenMMLangevin, frame_interval=250*u.fs,\n", " timestep=0.5*u.fs, constrain_hbonds=False, remove_rotation=True,\n", " remove_translation=True, constrain_water=False)\n", "mdtraj = mdmol.run(5.0 * u.ps)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Post-processing\n", "\n", "Next, we calculate the spectrum at each sampled geometry. Depending on your computer speed and if PySCF is installed locally, this may take up to several minutes to run." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "post_traj = mdt.Trajectory(qmmol)\n", "for frame in mdtraj:\n", " qmmol.positions = frame.positions\n", " qmmol.calculate()\n", " post_traj.new_frame()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This cell plots the results - wavelength vs. oscillator strength at each geometry for each transition:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "wavelengths_to_state = []\n", "oscillators_to_state = []\n", "\n", "for i in range(1, len(qmmol.properties.state_energies)):\n", " wavelengths_to_state.append(\n", " (post_traj.state_energies[:,i] - post_traj.potential_energy).to('nm', 'spectroscopy'))\n", " oscillators_to_state.append([o[0,i] for o in post_traj.oscillator_strengths])\n", " \n", "for istate, (w,o) in enumerate(zip(wavelengths_to_state, oscillators_to_state)):\n", " plot(w,o, label='S0 -> S%d'%(istate+1),\n", " marker='o', linestyle='none')\n", "xlabel('wavelength / nm'); ylabel('oscillator strength'); legend()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create spectrum\n", "\n", "We're finally ready to calculate a spectrum - we'll create a histogram of all calculated transition wavelengths over all states, weighted by the oscillator strengths." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from itertools import chain\n", "all_wavelengths = u.array(list(chain(*wavelengths_to_state)))\n", "all_oscs = u.array(list(chain(*oscillators_to_state)))\n", "hist(all_wavelengths, weights=all_oscs, bins=50)\n", "xlabel('wavelength / nm')" ] }, { "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" } }, "nbformat": 4, "nbformat_minor": 1 }
Unknown
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/nbscripts/strip_nb_output.py
.py
1,747
55
#!/usr/bin/env python """strip outputs from an IPython Notebook Opens a notebook, strips its output, and writes the outputless version to the original file. Useful mainly as a git pre-commit hook for users who don't want to track output in VCS. This does mostly the same thing as the `Clear All Output` command in the notebook UI. Adapted from rom https://gist.github.com/minrk/6176788 to work with git filter driver FROM https://github.com/cfriedline/ipynb_template/blob/master/nbstripout """ import sys from future.utils import PY2 from nbformat import v4 def strip_output(nb): """strip the outputs from a notebook object""" # set metadata explicitly as python 3 nb.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"}} for cell in nb.cells: if 'outputs' in cell: cell['outputs'] = [] if 'execution_count' in cell: cell['execution_count'] = None if 'metadata' in cell: cell['metadata'] = {} return nb if __name__ == '__main__': nb = v4.reads(sys.stdin.read()) nb = strip_output(nb) output = v4.writes(nb) if type(output) == str and PY2: output = output.encode('utf-8') sys.stdout.write(output)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/nbscripts/gen_example_md.py
.py
237
13
#!/usr/bin/env python from __future__ import print_function import glob for f in glob.glob('Example*.ipynb'): print('* [%s](%s)' % (f[:-6], f)) print() for f in glob.glob('Tutorial*.ipynb'): print('* [%s](%s)' % (f[:-6], f))
Python
3D
Autodesk/molecular-design-toolkit
moldesign/_notebooks/nbscripts/gen_toc.py
.py
817
42
#!/usr/bin/env python from __future__ import print_function import sys, os from nbformat import v4 def parse_line(line): if not line.startswith('#'): return None ilevel = 0 for char in line: if char == '#': ilevel += 1 else: break name = line[ilevel:].strip() return ilevel, name if __name__ == '__main__': with open(sys.argv[1], 'r') as nbfile: nb = v4.reads(nbfile.read()) print('Contents\n=======\n---') for cell in nb.cells: if cell['cell_type'] == 'markdown': for line in cell['source'].splitlines(): header = parse_line(line) if header is None: continue ilevel, name = header print(' '*(ilevel-1) + ' - [%s](#%s)'%(name, name.replace(' ','-')))
Python
3D
Autodesk/molecular-design-toolkit
moldesign/external/__init__.py
.py
29
1
from . import transformations
Python
3D
Autodesk/molecular-design-toolkit
moldesign/external/pathlib.py
.py
1,191
40
# Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Exposes the correct version of pathlib, with some compatibility help for python 2 """ from __future__ import absolute_import from future.utils import PY2 as _PY2 if _PY2: from pathlib2 import * try: import pathlib as _backportpathlib except ImportError: _backportpathlib = None if _backportpathlib: def _backport_pathlib_fixup(p): if isinstance(p, _backportpathlib.Path): return Path(str(p)) else: return p else: def _backport_pathlib_fixup(p): return p else: from pathlib import *
Python
3D
Autodesk/molecular-design-toolkit
moldesign/external/transformations.py
.py
66,070
1,922
# -*- coding: utf-8 -*- # transformations.py # Copyright (c) 2006-2015, Christoph Gohlke # Copyright (c) 2006-2015, The Regents of the University of California # Produced at the Laboratory for Fluorescence Dynamics # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holders nor the names of any # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Homogeneous Transformation Matrices and Quaternions. A library for calculating 4x4 matrices for translating, rotating, reflecting, scaling, shearing, projecting, orthogonalizing, and superimposing arrays of 3D homogeneous coordinates as well as for converting between rotation matrices, Euler angles, and quaternions. Also includes an Arcball control object and functions to decompose transformation matrices. :Author: `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_ :Organization: Laboratory for Fluorescence Dynamics, University of California, Irvine :Version: 2015.07.18 Requirements ------------ * `CPython 2.7 or 3.4 <http://www.python.org>`_ * `Numpy 1.9 <http://www.numpy.org>`_ * `Transformations.c 2015.07.18 <http://www.lfd.uci.edu/~gohlke/>`_ (recommended for speedup of some functions) Notes ----- The API is not stable yet and is expected to change between revisions. This Python code is not optimized for speed. Refer to the transformations.c module for a faster implementation of some functions. Documentation in HTML format can be generated with epydoc. Matrices (M) can be inverted using numpy.linalg.inv(M), be concatenated using numpy.dot(M0, M1), or transform homogeneous coordinate arrays (v) using numpy.dot(M, v) for shape (4, \*) column vectors, respectively numpy.dot(v, M.T) for shape (\*, 4) row vectors ("array of points"). This module follows the "column vectors on the right" and "row major storage" (C contiguous) conventions. The translation components are in the right column of the transformation matrix, i.e. M[:3, 3]. The transpose of the transformation matrices may have to be used to interface with other graphics systems, e.g. with OpenGL's glMultMatrixd(). See also [16]. Calculations are carried out with numpy.float64 precision. Vector, point, quaternion, and matrix function arguments are expected to be "array like", i.e. tuple, list, or numpy arrays. Return types are numpy arrays unless specified otherwise. Angles are in radians unless specified otherwise. Quaternions w+ix+jy+kz are represented as [w, x, y, z]. A triple of Euler angles can be applied/interpreted in 24 ways, which can be specified using a 4 character string or encoded 4-tuple: *Axes 4-string*: e.g. 'sxyz' or 'ryxy' - first character : rotations are applied to 's'tatic or 'r'otating frame - remaining characters : successive rotation axis 'x', 'y', or 'z' *Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1) - inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix. - parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed by 'z', or 'z' is followed by 'x'. Otherwise odd (1). - repetition : first and last axis are same (1) or different (0). - frame : rotations are applied to static (0) or rotating (1) frame. Other Python packages and modules for 3D transformations and quaternions: * `Transforms3d <https://pypi.python.org/pypi/transforms3d>`_ includes most code of this module. * `Blender.mathutils <http://www.blender.org/api/blender_python_api>`_ * `numpy-dtypes <https://github.com/numpy/numpy-dtypes>`_ References ---------- (1) Matrices and transformations. Ronald Goldman. In "Graphics Gems I", pp 472-475. Morgan Kaufmann, 1990. (2) More matrices and transformations: shear and pseudo-perspective. Ronald Goldman. In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991. (3) Decomposing a matrix into simple transformations. Spencer Thomas. In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991. (4) Recovering the data from the transformation matrix. Ronald Goldman. In "Graphics Gems II", pp 324-331. Morgan Kaufmann, 1991. (5) Euler angle conversion. Ken Shoemake. In "Graphics Gems IV", pp 222-229. Morgan Kaufmann, 1994. (6) Arcball rotation control. Ken Shoemake. In "Graphics Gems IV", pp 175-192. Morgan Kaufmann, 1994. (7) Representing attitude: Euler angles, unit quaternions, and rotation vectors. James Diebel. 2006. (8) A discussion of the solution for the best rotation to relate two sets of vectors. W Kabsch. Acta Cryst. 1978. A34, 827-828. (9) Closed-form solution of absolute orientation using unit quaternions. BKP Horn. J Opt Soc Am A. 1987. 4(4):629-642. (10) Quaternions. Ken Shoemake. http://www.sfu.ca/~jwa3/cmpt461/files/quatut.pdf (11) From quaternion to matrix and back. JMP van Waveren. 2005. http://www.intel.com/cd/ids/developer/asmo-na/eng/293748.htm (12) Uniform random rotations. Ken Shoemake. In "Graphics Gems III", pp 124-132. Morgan Kaufmann, 1992. (13) Quaternion in molecular modeling. CFF Karney. J Mol Graph Mod, 25(5):595-604 (14) New method for extracting the quaternion from a rotation matrix. Itzhack Y Bar-Itzhack, J Guid Contr Dynam. 2000. 23(6): 1085-1087. (15) Multiple View Geometry in Computer Vision. Hartley and Zissermann. Cambridge University Press; 2nd Ed. 2004. Chapter 4, Algorithm 4.7, p 130. (16) Column Vectors vs. Row Vectors. http://steve.hollasch.net/cgindex/math/matrix/column-vec.html Examples -------- >>> alpha, beta, gamma = 0.123, -1.234, 2.345 >>> origin, xaxis, yaxis, zaxis = [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1] >>> I = identity_matrix() >>> Rx = rotation_matrix(alpha, xaxis) >>> Ry = rotation_matrix(beta, yaxis) >>> Rz = rotation_matrix(gamma, zaxis) >>> R = concatenate_matrices(Rx, Ry, Rz) >>> euler = euler_from_matrix(R, 'rxyz') >>> numpy.allclose([alpha, beta, gamma], euler) True >>> Re = euler_matrix(alpha, beta, gamma, 'rxyz') >>> is_same_transform(R, Re) True >>> al, be, ga = euler_from_matrix(Re, 'rxyz') >>> is_same_transform(Re, euler_matrix(al, be, ga, 'rxyz')) True >>> qx = quaternion_about_axis(alpha, xaxis) >>> qy = quaternion_about_axis(beta, yaxis) >>> qz = quaternion_about_axis(gamma, zaxis) >>> q = quaternion_multiply(qx, qy) >>> q = quaternion_multiply(q, qz) >>> Rq = quaternion_matrix(q) >>> is_same_transform(R, Rq) True >>> S = scale_matrix(1.23, origin) >>> T = translation_matrix([1, 2, 3]) >>> Z = shear_matrix(beta, xaxis, origin, zaxis) >>> R = random_rotation_matrix(numpy.random.rand(3)) >>> M = concatenate_matrices(T, R, Z, S) >>> scale, shear, angles, trans, persp = decompose_matrix(M) >>> numpy.allclose(scale, 1.23) True >>> numpy.allclose(trans, [1, 2, 3]) True >>> numpy.allclose(shear, [0, math.tan(beta), 0]) True >>> is_same_transform(R, euler_matrix(axes='sxyz', *angles)) True >>> M1 = compose_matrix(scale, shear, angles, trans, persp) >>> is_same_transform(M, M1) True >>> v0, v1 = random_vector(3), random_vector(3) >>> M = rotation_matrix(angle_between_vectors(v0, v1), vector_product(v0, v1)) >>> v2 = numpy.dot(v0, M[:3,:3].T) >>> numpy.allclose(unit_vector(v1), unit_vector(v2)) True """ from __future__ import division, print_function from builtins import object import math import numpy __version__ = '2015.07.18' __docformat__ = 'restructuredtext en' __all__ = () def identity_matrix(): """Return 4x4 identity/unit matrix. >>> I = identity_matrix() >>> numpy.allclose(I, numpy.dot(I, I)) True >>> numpy.sum(I), numpy.trace(I) (4.0, 4.0) >>> numpy.allclose(I, numpy.identity(4)) True """ return numpy.identity(4) def translation_matrix(direction): """Return matrix to translate by direction vector. >>> v = numpy.random.random(3) - 0.5 >>> numpy.allclose(v, translation_matrix(v)[:3, 3]) True """ M = numpy.identity(4) M[:3, 3] = direction[:3] return M def translation_from_matrix(matrix): """Return translation vector from translation matrix. >>> v0 = numpy.random.random(3) - 0.5 >>> v1 = translation_from_matrix(translation_matrix(v0)) >>> numpy.allclose(v0, v1) True """ return numpy.array(matrix, copy=False)[:3, 3].copy() def reflection_matrix(point, normal): """Return matrix to mirror at plane defined by point and normal vector. >>> v0 = numpy.random.random(4) - 0.5 >>> v0[3] = 1. >>> v1 = numpy.random.random(3) - 0.5 >>> R = reflection_matrix(v0, v1) >>> numpy.allclose(2, numpy.trace(R)) True >>> numpy.allclose(v0, numpy.dot(R, v0)) True >>> v2 = v0.copy() >>> v2[:3] += v1 >>> v3 = v0.copy() >>> v2[:3] -= v1 >>> numpy.allclose(v2, numpy.dot(R, v3)) True """ normal = unit_vector(normal[:3]) M = numpy.identity(4) M[:3, :3] -= 2.0 * numpy.outer(normal, normal) M[:3, 3] = (2.0 * numpy.dot(point[:3], normal)) * normal return M def reflection_from_matrix(matrix): """Return mirror plane point and normal vector from reflection matrix. >>> v0 = numpy.random.random(3) - 0.5 >>> v1 = numpy.random.random(3) - 0.5 >>> M0 = reflection_matrix(v0, v1) >>> point, normal = reflection_from_matrix(M0) >>> M1 = reflection_matrix(point, normal) >>> is_same_transform(M0, M1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=False) # normal: unit eigenvector corresponding to eigenvalue -1 w, V = numpy.linalg.eig(M[:3, :3]) i = numpy.where(abs(numpy.real(w) + 1.0) < 1e-8)[0] if not len(i): raise ValueError("no unit eigenvector corresponding to eigenvalue -1") normal = numpy.real(V[:, i[0]]).squeeze() # point: any unit eigenvector corresponding to eigenvalue 1 w, V = numpy.linalg.eig(M) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no unit eigenvector corresponding to eigenvalue 1") point = numpy.real(V[:, i[-1]]).squeeze() point /= point[3] return point, normal def rotation_matrix(angle, direction, point=None): """Return matrix to rotate about axis defined by point and direction. >>> R = rotation_matrix(math.pi/2, [0, 0, 1], [1, 0, 0]) >>> numpy.allclose(numpy.dot(R, [0, 0, 0, 1]), [1, -1, 0, 1]) True >>> angle = (random.random() - 0.5) * (2*math.pi) >>> direc = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> R0 = rotation_matrix(angle, direc, point) >>> R1 = rotation_matrix(angle-2*math.pi, direc, point) >>> is_same_transform(R0, R1) True >>> R0 = rotation_matrix(angle, direc, point) >>> R1 = rotation_matrix(-angle, -direc, point) >>> is_same_transform(R0, R1) True >>> I = numpy.identity(4, numpy.float64) >>> numpy.allclose(I, rotation_matrix(math.pi*2, direc)) True >>> numpy.allclose(2, numpy.trace(rotation_matrix(math.pi/2, ... direc, point))) True """ sina = math.sin(angle) cosa = math.cos(angle) direction = unit_vector(direction[:3]) # rotation matrix around unit vector R = numpy.diag([cosa, cosa, cosa]) R += numpy.outer(direction, direction) * (1.0 - cosa) direction *= sina R += numpy.array([[ 0.0, -direction[2], direction[1]], [ direction[2], 0.0, -direction[0]], [-direction[1], direction[0], 0.0]]) M = numpy.identity(4) M[:3, :3] = R if point is not None: # rotation not around origin point = numpy.array(point[:3], dtype=numpy.float64, copy=False) M[:3, 3] = point - numpy.dot(R, point) return M def rotation_from_matrix(matrix): """Return rotation angle and axis from rotation matrix. >>> angle = (random.random() - 0.5) * (2*math.pi) >>> direc = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> R0 = rotation_matrix(angle, direc, point) >>> angle, direc, point = rotation_from_matrix(R0) >>> R1 = rotation_matrix(angle, direc, point) >>> is_same_transform(R0, R1) True """ R = numpy.array(matrix, dtype=numpy.float64, copy=False) R33 = R[:3, :3] # direction: unit eigenvector of R33 corresponding to eigenvalue of 1 w, W = numpy.linalg.eig(R33.T) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no unit eigenvector corresponding to eigenvalue 1") direction = numpy.real(W[:, i[-1]]).squeeze() # point: unit eigenvector of R33 corresponding to eigenvalue of 1 w, Q = numpy.linalg.eig(R) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no unit eigenvector corresponding to eigenvalue 1") point = numpy.real(Q[:, i[-1]]).squeeze() point /= point[3] # rotation angle depending on direction cosa = (numpy.trace(R33) - 1.0) / 2.0 if abs(direction[2]) > 1e-8: sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2] elif abs(direction[1]) > 1e-8: sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1] else: sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0] angle = math.atan2(sina, cosa) return angle, direction, point def scale_matrix(factor, origin=None, direction=None): """Return matrix to scale by factor around origin in direction. Use factor -1 for point symmetry. >>> v = (numpy.random.rand(4, 5) - 0.5) * 20 >>> v[3] = 1 >>> S = scale_matrix(-1.234) >>> numpy.allclose(numpy.dot(S, v)[:3], -1.234*v[:3]) True >>> factor = random.random() * 10 - 5 >>> origin = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> S = scale_matrix(factor, origin) >>> S = scale_matrix(factor, origin, direct) """ if direction is None: # uniform scaling M = numpy.diag([factor, factor, factor, 1.0]) if origin is not None: M[:3, 3] = origin[:3] M[:3, 3] *= 1.0 - factor else: # nonuniform scaling direction = unit_vector(direction[:3]) factor = 1.0 - factor M = numpy.identity(4) M[:3, :3] -= factor * numpy.outer(direction, direction) if origin is not None: M[:3, 3] = (factor * numpy.dot(origin[:3], direction)) * direction return M def scale_from_matrix(matrix): """Return scaling factor, origin and direction from scaling matrix. >>> factor = random.random() * 10 - 5 >>> origin = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> S0 = scale_matrix(factor, origin) >>> factor, origin, direction = scale_from_matrix(S0) >>> S1 = scale_matrix(factor, origin, direction) >>> is_same_transform(S0, S1) True >>> S0 = scale_matrix(factor, origin, direct) >>> factor, origin, direction = scale_from_matrix(S0) >>> S1 = scale_matrix(factor, origin, direction) >>> is_same_transform(S0, S1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=False) M33 = M[:3, :3] factor = numpy.trace(M33) - 2.0 try: # direction: unit eigenvector corresponding to eigenvalue factor w, V = numpy.linalg.eig(M33) i = numpy.where(abs(numpy.real(w) - factor) < 1e-8)[0][0] direction = numpy.real(V[:, i]).squeeze() direction /= vector_norm(direction) except IndexError: # uniform scaling factor = (factor + 2.0) / 3.0 direction = None # origin: any eigenvector corresponding to eigenvalue 1 w, V = numpy.linalg.eig(M) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no eigenvector corresponding to eigenvalue 1") origin = numpy.real(V[:, i[-1]]).squeeze() origin /= origin[3] return factor, origin, direction def projection_matrix(point, normal, direction=None, perspective=None, pseudo=False): """Return matrix to project onto plane defined by point and normal. Using either perspective point, projection direction, or none of both. If pseudo is True, perspective projections will preserve relative depth such that Perspective = dot(Orthogonal, PseudoPerspective). >>> P = projection_matrix([0, 0, 0], [1, 0, 0]) >>> numpy.allclose(P[1:, 1:], numpy.identity(4)[1:, 1:]) True >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(3) - 0.5 >>> P0 = projection_matrix(point, normal) >>> P1 = projection_matrix(point, normal, direction=direct) >>> P2 = projection_matrix(point, normal, perspective=persp) >>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True) >>> is_same_transform(P2, numpy.dot(P0, P3)) True >>> P = projection_matrix([3, 0, 0], [1, 1, 0], [1, 0, 0]) >>> v0 = (numpy.random.rand(4, 5) - 0.5) * 20 >>> v0[3] = 1 >>> v1 = numpy.dot(P, v0) >>> numpy.allclose(v1[1], v0[1]) True >>> numpy.allclose(v1[0], 3-v1[1]) True """ M = numpy.identity(4) point = numpy.array(point[:3], dtype=numpy.float64, copy=False) normal = unit_vector(normal[:3]) if perspective is not None: # perspective projection perspective = numpy.array(perspective[:3], dtype=numpy.float64, copy=False) M[0, 0] = M[1, 1] = M[2, 2] = numpy.dot(perspective-point, normal) M[:3, :3] -= numpy.outer(perspective, normal) if pseudo: # preserve relative depth M[:3, :3] -= numpy.outer(normal, normal) M[:3, 3] = numpy.dot(point, normal) * (perspective+normal) else: M[:3, 3] = numpy.dot(point, normal) * perspective M[3, :3] = -normal M[3, 3] = numpy.dot(perspective, normal) elif direction is not None: # parallel projection direction = numpy.array(direction[:3], dtype=numpy.float64, copy=False) scale = numpy.dot(direction, normal) M[:3, :3] -= numpy.outer(direction, normal) / scale M[:3, 3] = direction * (numpy.dot(point, normal) / scale) else: # orthogonal projection M[:3, :3] -= numpy.outer(normal, normal) M[:3, 3] = numpy.dot(point, normal) * normal return M def projection_from_matrix(matrix, pseudo=False): """Return projection plane and perspective point from projection matrix. Return values are same as arguments for projection_matrix function: point, normal, direction, perspective, and pseudo. >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(3) - 0.5 >>> P0 = projection_matrix(point, normal) >>> result = projection_from_matrix(P0) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, direct) >>> result = projection_from_matrix(P0) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=False) >>> result = projection_from_matrix(P0, pseudo=False) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=True) >>> result = projection_from_matrix(P0, pseudo=True) >>> P1 = projection_matrix(*result) >>> is_same_transform(P0, P1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=False) M33 = M[:3, :3] w, V = numpy.linalg.eig(M) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not pseudo and len(i): # point: any eigenvector corresponding to eigenvalue 1 point = numpy.real(V[:, i[-1]]).squeeze() point /= point[3] # direction: unit eigenvector corresponding to eigenvalue 0 w, V = numpy.linalg.eig(M33) i = numpy.where(abs(numpy.real(w)) < 1e-8)[0] if not len(i): raise ValueError("no eigenvector corresponding to eigenvalue 0") direction = numpy.real(V[:, i[0]]).squeeze() direction /= vector_norm(direction) # normal: unit eigenvector of M33.T corresponding to eigenvalue 0 w, V = numpy.linalg.eig(M33.T) i = numpy.where(abs(numpy.real(w)) < 1e-8)[0] if len(i): # parallel projection normal = numpy.real(V[:, i[0]]).squeeze() normal /= vector_norm(normal) return point, normal, direction, None, False else: # orthogonal projection, where normal equals direction vector return point, direction, None, None, False else: # perspective projection i = numpy.where(abs(numpy.real(w)) > 1e-8)[0] if not len(i): raise ValueError( "no eigenvector not corresponding to eigenvalue 0") point = numpy.real(V[:, i[-1]]).squeeze() point /= point[3] normal = - M[3, :3] perspective = M[:3, 3] / numpy.dot(point[:3], normal) if pseudo: perspective -= normal return point, normal, None, perspective, pseudo def clip_matrix(left, right, bottom, top, near, far, perspective=False): """Return matrix to obtain normalized device coordinates from frustum. The frustum bounds are axis-aligned along x (left, right), y (bottom, top) and z (near, far). Normalized device coordinates are in range [-1, 1] if coordinates are inside the frustum. If perspective is True the frustum is a truncated pyramid with the perspective point at origin and direction along z axis, otherwise an orthographic canonical view volume (a box). Homogeneous coordinates transformed by the perspective clip matrix need to be dehomogenized (divided by w coordinate). >>> frustum = numpy.random.rand(6) >>> frustum[1] += frustum[0] >>> frustum[3] += frustum[2] >>> frustum[5] += frustum[4] >>> M = clip_matrix(perspective=False, *frustum) >>> numpy.dot(M, [frustum[0], frustum[2], frustum[4], 1]) array([-1., -1., -1., 1.]) >>> numpy.dot(M, [frustum[1], frustum[3], frustum[5], 1]) array([ 1., 1., 1., 1.]) >>> M = clip_matrix(perspective=True, *frustum) >>> v = numpy.dot(M, [frustum[0], frustum[2], frustum[4], 1]) >>> v / v[3] array([-1., -1., -1., 1.]) >>> v = numpy.dot(M, [frustum[1], frustum[3], frustum[4], 1]) >>> v / v[3] array([ 1., 1., -1., 1.]) """ if left >= right or bottom >= top or near >= far: raise ValueError("invalid frustum") if perspective: if near <= _EPS: raise ValueError("invalid frustum: near <= 0") t = 2.0 * near M = [[t/(left-right), 0.0, (right+left)/(right-left), 0.0], [0.0, t/(bottom-top), (top+bottom)/(top-bottom), 0.0], [0.0, 0.0, (far+near)/(near-far), t*far/(far-near)], [0.0, 0.0, -1.0, 0.0]] else: M = [[2.0/(right-left), 0.0, 0.0, (right+left)/(left-right)], [0.0, 2.0/(top-bottom), 0.0, (top+bottom)/(bottom-top)], [0.0, 0.0, 2.0/(far-near), (far+near)/(near-far)], [0.0, 0.0, 0.0, 1.0]] return numpy.array(M) def shear_matrix(angle, direction, point, normal): """Return matrix to shear by angle along direction vector on shear plane. The shear plane is defined by a point and normal vector. The direction vector must be orthogonal to the plane's normal vector. A point P is transformed by the shear matrix into P" such that the vector P-P" is parallel to the direction vector and its extent is given by the angle of P-P'-P", where P' is the orthogonal projection of P onto the shear plane. >>> angle = (random.random() - 0.5) * 4*math.pi >>> direct = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.cross(direct, numpy.random.random(3)) >>> S = shear_matrix(angle, direct, point, normal) >>> numpy.allclose(1, numpy.linalg.det(S)) True """ normal = unit_vector(normal[:3]) direction = unit_vector(direction[:3]) if abs(numpy.dot(normal, direction)) > 1e-6: raise ValueError("direction and normal vectors are not orthogonal") angle = math.tan(angle) M = numpy.identity(4) M[:3, :3] += angle * numpy.outer(direction, normal) M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction return M def shear_from_matrix(matrix): """Return shear angle, direction and plane from shear matrix. >>> angle = (random.random() - 0.5) * 4*math.pi >>> direct = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.cross(direct, numpy.random.random(3)) >>> S0 = shear_matrix(angle, direct, point, normal) >>> angle, direct, point, normal = shear_from_matrix(S0) >>> S1 = shear_matrix(angle, direct, point, normal) >>> is_same_transform(S0, S1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=False) M33 = M[:3, :3] # normal: cross independent eigenvectors corresponding to the eigenvalue 1 w, V = numpy.linalg.eig(M33) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-4)[0] if len(i) < 2: raise ValueError("no two linear independent eigenvectors found %s" % w) V = numpy.real(V[:, i]).squeeze().T lenorm = -1.0 for i0, i1 in ((0, 1), (0, 2), (1, 2)): n = numpy.cross(V[i0], V[i1]) w = vector_norm(n) if w > lenorm: lenorm = w normal = n normal /= lenorm # direction and angle direction = numpy.dot(M33 - numpy.identity(3), normal) angle = vector_norm(direction) direction /= angle angle = math.atan(angle) # point: eigenvector corresponding to eigenvalue 1 w, V = numpy.linalg.eig(M) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0] if not len(i): raise ValueError("no eigenvector corresponding to eigenvalue 1") point = numpy.real(V[:, i[-1]]).squeeze() point /= point[3] return angle, direction, point, normal def decompose_matrix(matrix): """Return sequence of transformations from transformation matrix. matrix : array_like Non-degenerative homogeneous transformation matrix Return tuple of: scale : vector of 3 scaling factors shear : list of shear factors for x-y, x-z, y-z axes angles : list of Euler angles about static x, y, z axes translate : translation vector along x, y, z axes perspective : perspective partition of matrix Raise ValueError if matrix is of wrong type or degenerative. >>> T0 = translation_matrix([1, 2, 3]) >>> scale, shear, angles, trans, persp = decompose_matrix(T0) >>> T1 = translation_matrix(trans) >>> numpy.allclose(T0, T1) True >>> S = scale_matrix(0.123) >>> scale, shear, angles, trans, persp = decompose_matrix(S) >>> scale[0] 0.123 >>> R0 = euler_matrix(1, 2, 3) >>> scale, shear, angles, trans, persp = decompose_matrix(R0) >>> R1 = euler_matrix(*angles) >>> numpy.allclose(R0, R1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=True).T if abs(M[3, 3]) < _EPS: raise ValueError("M[3, 3] is zero") M /= M[3, 3] P = M.copy() P[:, 3] = 0.0, 0.0, 0.0, 1.0 if not numpy.linalg.det(P): raise ValueError("matrix is singular") scale = numpy.zeros((3, )) shear = [0.0, 0.0, 0.0] angles = [0.0, 0.0, 0.0] if any(abs(M[:3, 3]) > _EPS): perspective = numpy.dot(M[:, 3], numpy.linalg.inv(P.T)) M[:, 3] = 0.0, 0.0, 0.0, 1.0 else: perspective = numpy.array([0.0, 0.0, 0.0, 1.0]) translate = M[3, :3].copy() M[3, :3] = 0.0 row = M[:3, :3].copy() scale[0] = vector_norm(row[0]) row[0] /= scale[0] shear[0] = numpy.dot(row[0], row[1]) row[1] -= row[0] * shear[0] scale[1] = vector_norm(row[1]) row[1] /= scale[1] shear[0] /= scale[1] shear[1] = numpy.dot(row[0], row[2]) row[2] -= row[0] * shear[1] shear[2] = numpy.dot(row[1], row[2]) row[2] -= row[1] * shear[2] scale[2] = vector_norm(row[2]) row[2] /= scale[2] shear[1:] /= scale[2] if numpy.dot(row[0], numpy.cross(row[1], row[2])) < 0: numpy.negative(scale, scale) numpy.negative(row, row) angles[1] = math.asin(-row[0, 2]) if math.cos(angles[1]): angles[0] = math.atan2(row[1, 2], row[2, 2]) angles[2] = math.atan2(row[0, 1], row[0, 0]) else: #angles[0] = math.atan2(row[1, 0], row[1, 1]) angles[0] = math.atan2(-row[2, 1], row[1, 1]) angles[2] = 0.0 return scale, shear, angles, translate, perspective def compose_matrix(scale=None, shear=None, angles=None, translate=None, perspective=None): """Return transformation matrix from sequence of transformations. This is the inverse of the decompose_matrix function. Sequence of transformations: scale : vector of 3 scaling factors shear : list of shear factors for x-y, x-z, y-z axes angles : list of Euler angles about static x, y, z axes translate : translation vector along x, y, z axes perspective : perspective partition of matrix >>> scale = numpy.random.random(3) - 0.5 >>> shear = numpy.random.random(3) - 0.5 >>> angles = (numpy.random.random(3) - 0.5) * (2*math.pi) >>> trans = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(4) - 0.5 >>> M0 = compose_matrix(scale, shear, angles, trans, persp) >>> result = decompose_matrix(M0) >>> M1 = compose_matrix(*result) >>> is_same_transform(M0, M1) True """ M = numpy.identity(4) if perspective is not None: P = numpy.identity(4) P[3, :] = perspective[:4] M = numpy.dot(M, P) if translate is not None: T = numpy.identity(4) T[:3, 3] = translate[:3] M = numpy.dot(M, T) if angles is not None: R = euler_matrix(angles[0], angles[1], angles[2], 'sxyz') M = numpy.dot(M, R) if shear is not None: Z = numpy.identity(4) Z[1, 2] = shear[2] Z[0, 2] = shear[1] Z[0, 1] = shear[0] M = numpy.dot(M, Z) if scale is not None: S = numpy.identity(4) S[0, 0] = scale[0] S[1, 1] = scale[1] S[2, 2] = scale[2] M = numpy.dot(M, S) M /= M[3, 3] return M def orthogonalization_matrix(lengths, angles): """Return orthogonalization matrix for crystallographic cell coordinates. Angles are expected in degrees. The de-orthogonalization matrix is the inverse. >>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90]) >>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10) True >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7]) >>> numpy.allclose(numpy.sum(O), 43.063229) True """ a, b, c = lengths angles = numpy.radians(angles) sina, sinb, _ = numpy.sin(angles) cosa, cosb, cosg = numpy.cos(angles) co = (cosa * cosb - cosg) / (sina * sinb) return numpy.array([ [ a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0], [-a*sinb*co, b*sina, 0.0, 0.0], [ a*cosb, b*cosa, c, 0.0], [ 0.0, 0.0, 0.0, 1.0]]) def affine_matrix_from_points(v0, v1, shear=True, scale=True, usesvd=True): """Return affine transform matrix to register two point sets. v0 and v1 are shape (ndims, \*) arrays of at least ndims non-homogeneous coordinates, where ndims is the dimensionality of the coordinate space. If shear is False, a similarity transformation matrix is returned. If also scale is False, a rigid/Euclidean transformation matrix is returned. By default the algorithm by Hartley and Zissermann [15] is used. If usesvd is True, similarity and Euclidean transformation matrices are calculated by minimizing the weighted sum of squared deviations (RMSD) according to the algorithm by Kabsch [8]. Otherwise, and if ndims is 3, the quaternion based algorithm by Horn [9] is used, which is slower when using this Python implementation. The returned matrix performs rotation, translation and uniform scaling (if specified). >>> v0 = [[0, 1031, 1031, 0], [0, 0, 1600, 1600]] >>> v1 = [[675, 826, 826, 677], [55, 52, 281, 277]] >>> affine_matrix_from_points(v0, v1) array([[ 0.14549, 0.00062, 675.50008], [ 0.00048, 0.14094, 53.24971], [ 0. , 0. , 1. ]]) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> R = random_rotation_matrix(numpy.random.random(3)) >>> S = scale_matrix(random.random()) >>> M = concatenate_matrices(T, R, S) >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20 >>> v0[3] = 1 >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0, 1e-8, 300).reshape(3, -1) >>> M = affine_matrix_from_points(v0[:3], v1[:3]) >>> numpy.allclose(v1, numpy.dot(M, v0)) True More examples in superimposition_matrix() """ v0 = numpy.array(v0, dtype=numpy.float64, copy=True) v1 = numpy.array(v1, dtype=numpy.float64, copy=True) ndims = v0.shape[0] if ndims < 2 or v0.shape[1] < ndims or v0.shape != v1.shape: raise ValueError("input arrays are of wrong shape or type") # move centroids to origin t0 = -numpy.mean(v0, axis=1) M0 = numpy.identity(ndims+1) M0[:ndims, ndims] = t0 v0 += t0.reshape(ndims, 1) t1 = -numpy.mean(v1, axis=1) M1 = numpy.identity(ndims+1) M1[:ndims, ndims] = t1 v1 += t1.reshape(ndims, 1) if shear: # Affine transformation A = numpy.concatenate((v0, v1), axis=0) u, s, vh = numpy.linalg.svd(A.T) vh = vh[:ndims].T B = vh[:ndims] C = vh[ndims:2*ndims] t = numpy.dot(C, numpy.linalg.pinv(B)) t = numpy.concatenate((t, numpy.zeros((ndims, 1))), axis=1) M = numpy.vstack((t, ((0.0,)*ndims) + (1.0,))) elif usesvd or ndims != 3: # Rigid transformation via SVD of covariance matrix u, s, vh = numpy.linalg.svd(numpy.dot(v1, v0.T)) # rotation matrix from SVD orthonormal bases R = numpy.dot(u, vh) if numpy.linalg.det(R) < 0.0: # R does not constitute right handed system R -= numpy.outer(u[:, ndims-1], vh[ndims-1, :]*2.0) s[-1] *= -1.0 # homogeneous transformation matrix M = numpy.identity(ndims+1) M[:ndims, :ndims] = R else: # Rigid transformation matrix via quaternion # compute symmetric matrix N xx, yy, zz = numpy.sum(v0 * v1, axis=1) xy, yz, zx = numpy.sum(v0 * numpy.roll(v1, -1, axis=0), axis=1) xz, yx, zy = numpy.sum(v0 * numpy.roll(v1, -2, axis=0), axis=1) N = [[xx+yy+zz, 0.0, 0.0, 0.0], [yz-zy, xx-yy-zz, 0.0, 0.0], [zx-xz, xy+yx, yy-xx-zz, 0.0], [xy-yx, zx+xz, yz+zy, zz-xx-yy]] # quaternion: eigenvector corresponding to most positive eigenvalue w, V = numpy.linalg.eigh(N) q = V[:, numpy.argmax(w)] q /= vector_norm(q) # unit quaternion # homogeneous transformation matrix M = quaternion_matrix(q) if scale and not shear: # Affine transformation; scale is ratio of RMS deviations from centroid v0 *= v0 v1 *= v1 M[:ndims, :ndims] *= math.sqrt(numpy.sum(v1) / numpy.sum(v0)) # move centroids back M = numpy.dot(numpy.linalg.inv(M1), numpy.dot(M, M0)) M /= M[ndims, ndims] return M def superimposition_matrix(v0, v1, scale=False, usesvd=True): """Return matrix to transform given 3D point set into second point set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points. The parameters scale and usesvd are explained in the more general affine_matrix_from_points function. The returned matrix is a similarity or Euclidean transformation matrix. This function has a fast C implementation in transformations.c. >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]] >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20 >>> v0[3] = 1 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scale=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3)) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True """ v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3] v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3] return affine_matrix_from_points(v0, v1, shear=False, scale=scale, usesvd=usesvd) def euler_matrix(ai, aj, ak, axes='sxyz'): """Return homogeneous rotation matrix from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> R = euler_matrix(1, 2, 3, 'syxz') >>> numpy.allclose(numpy.sum(R[0]), -1.34786452) True >>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1)) >>> numpy.allclose(numpy.sum(R[0]), -0.383436184) True >>> ai, aj, ak = (4*math.pi) * (numpy.random.random(3) - 0.5) >>> for axes in _AXES2TUPLE.keys(): ... R = euler_matrix(ai, aj, ak, axes) >>> for axes in _TUPLE2AXES.keys(): ... R = euler_matrix(ai, aj, ak, axes) """ try: firstaxis, parity, repetition, frame = _AXES2TUPLE[axes] except (AttributeError, KeyError): _TUPLE2AXES[axes] # validation firstaxis, parity, repetition, frame = axes i = firstaxis j = _NEXT_AXIS[i+parity] k = _NEXT_AXIS[i-parity+1] if frame: ai, ak = ak, ai if parity: ai, aj, ak = -ai, -aj, -ak si, sj, sk = math.sin(ai), math.sin(aj), math.sin(ak) ci, cj, ck = math.cos(ai), math.cos(aj), math.cos(ak) cc, cs = ci*ck, ci*sk sc, ss = si*ck, si*sk M = numpy.identity(4) if repetition: M[i, i] = cj M[i, j] = sj*si M[i, k] = sj*ci M[j, i] = sj*sk M[j, j] = -cj*ss+cc M[j, k] = -cj*cs-sc M[k, i] = -sj*ck M[k, j] = cj*sc+cs M[k, k] = cj*cc-ss else: M[i, i] = cj*ck M[i, j] = sj*sc-cs M[i, k] = sj*cc+ss M[j, i] = cj*sk M[j, j] = sj*ss+cc M[j, k] = sj*cs-sc M[k, i] = -sj M[k, j] = cj*si M[k, k] = cj*ci return M def euler_from_matrix(matrix, axes='sxyz'): """Return Euler angles from rotation matrix for specified axis sequence. axes : One of 24 axis sequences as string or encoded tuple Note that many Euler angle triplets can describe one matrix. >>> R0 = euler_matrix(1, 2, 3, 'syxz') >>> al, be, ga = euler_from_matrix(R0, 'syxz') >>> R1 = euler_matrix(al, be, ga, 'syxz') >>> numpy.allclose(R0, R1) True >>> angles = (4*math.pi) * (numpy.random.random(3) - 0.5) >>> for axes in _AXES2TUPLE.keys(): ... R0 = euler_matrix(axes=axes, *angles) ... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes)) ... if not numpy.allclose(R0, R1): print(axes, "failed") """ try: firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()] except (AttributeError, KeyError): _TUPLE2AXES[axes] # validation firstaxis, parity, repetition, frame = axes i = firstaxis j = _NEXT_AXIS[i+parity] k = _NEXT_AXIS[i-parity+1] M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:3, :3] if repetition: sy = math.sqrt(M[i, j]*M[i, j] + M[i, k]*M[i, k]) if sy > _EPS: ax = math.atan2( M[i, j], M[i, k]) ay = math.atan2( sy, M[i, i]) az = math.atan2( M[j, i], -M[k, i]) else: ax = math.atan2(-M[j, k], M[j, j]) ay = math.atan2( sy, M[i, i]) az = 0.0 else: cy = math.sqrt(M[i, i]*M[i, i] + M[j, i]*M[j, i]) if cy > _EPS: ax = math.atan2( M[k, j], M[k, k]) ay = math.atan2(-M[k, i], cy) az = math.atan2( M[j, i], M[i, i]) else: ax = math.atan2(-M[j, k], M[j, j]) ay = math.atan2(-M[k, i], cy) az = 0.0 if parity: ax, ay, az = -ax, -ay, -az if frame: ax, az = az, ax return ax, ay, az def euler_from_quaternion(quaternion, axes='sxyz'): """Return Euler angles from quaternion for specified axis sequence. >>> angles = euler_from_quaternion([0.99810947, 0.06146124, 0, 0]) >>> numpy.allclose(angles, [0.123, 0, 0]) True """ return euler_from_matrix(quaternion_matrix(quaternion), axes) def quaternion_from_euler(ai, aj, ak, axes='sxyz'): """Return quaternion from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> q = quaternion_from_euler(1, 2, 3, 'ryxz') >>> numpy.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435]) True """ try: firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()] except (AttributeError, KeyError): _TUPLE2AXES[axes] # validation firstaxis, parity, repetition, frame = axes i = firstaxis + 1 j = _NEXT_AXIS[i+parity-1] + 1 k = _NEXT_AXIS[i-parity] + 1 if frame: ai, ak = ak, ai if parity: aj = -aj ai /= 2.0 aj /= 2.0 ak /= 2.0 ci = math.cos(ai) si = math.sin(ai) cj = math.cos(aj) sj = math.sin(aj) ck = math.cos(ak) sk = math.sin(ak) cc = ci*ck cs = ci*sk sc = si*ck ss = si*sk q = numpy.empty((4, )) if repetition: q[0] = cj*(cc - ss) q[i] = cj*(cs + sc) q[j] = sj*(cc + ss) q[k] = sj*(cs - sc) else: q[0] = cj*cc + sj*ss q[i] = cj*sc - sj*cs q[j] = cj*ss + sj*cc q[k] = cj*cs - sj*sc if parity: q[j] *= -1.0 return q def quaternion_about_axis(angle, axis): """Return quaternion for rotation about axis. >>> q = quaternion_about_axis(0.123, [1, 0, 0]) >>> numpy.allclose(q, [0.99810947, 0.06146124, 0, 0]) True """ q = numpy.array([0.0, axis[0], axis[1], axis[2]]) qlen = vector_norm(q) if qlen > _EPS: q *= math.sin(angle/2.0) / qlen q[0] = math.cos(angle/2.0) return q def quaternion_matrix(quaternion): """Return homogeneous rotation matrix from quaternion. >>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0]) >>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0])) True >>> M = quaternion_matrix([1, 0, 0, 0]) >>> numpy.allclose(M, numpy.identity(4)) True >>> M = quaternion_matrix([0, 1, 0, 0]) >>> numpy.allclose(M, numpy.diag([1, -1, -1, 1])) True """ q = numpy.array(quaternion, dtype=numpy.float64, copy=True) n = numpy.dot(q, q) if n < _EPS: return numpy.identity(4) q *= math.sqrt(2.0 / n) q = numpy.outer(q, q) return numpy.array([ [1.0-q[2, 2]-q[3, 3], q[1, 2]-q[3, 0], q[1, 3]+q[2, 0], 0.0], [ q[1, 2]+q[3, 0], 1.0-q[1, 1]-q[3, 3], q[2, 3]-q[1, 0], 0.0], [ q[1, 3]-q[2, 0], q[2, 3]+q[1, 0], 1.0-q[1, 1]-q[2, 2], 0.0], [ 0.0, 0.0, 0.0, 1.0]]) def quaternion_from_matrix(matrix, isprecise=False): """Return quaternion from rotation matrix. If isprecise is True, the input matrix is assumed to be a precise rotation matrix and a faster algorithm is used. >>> q = quaternion_from_matrix(numpy.identity(4), True) >>> numpy.allclose(q, [1, 0, 0, 0]) True >>> q = quaternion_from_matrix(numpy.diag([1, -1, -1, 1])) >>> numpy.allclose(q, [0, 1, 0, 0]) or numpy.allclose(q, [0, -1, 0, 0]) True >>> R = rotation_matrix(0.123, (1, 2, 3)) >>> q = quaternion_from_matrix(R, True) >>> numpy.allclose(q, [0.9981095, 0.0164262, 0.0328524, 0.0492786]) True >>> R = [[-0.545, 0.797, 0.260, 0], [0.733, 0.603, -0.313, 0], ... [-0.407, 0.021, -0.913, 0], [0, 0, 0, 1]] >>> q = quaternion_from_matrix(R) >>> numpy.allclose(q, [0.19069, 0.43736, 0.87485, -0.083611]) True >>> R = [[0.395, 0.362, 0.843, 0], [-0.626, 0.796, -0.056, 0], ... [-0.677, -0.498, 0.529, 0], [0, 0, 0, 1]] >>> q = quaternion_from_matrix(R) >>> numpy.allclose(q, [0.82336615, -0.13610694, 0.46344705, -0.29792603]) True >>> R = random_rotation_matrix() >>> q = quaternion_from_matrix(R) >>> is_same_transform(R, quaternion_matrix(q)) True >>> R = euler_matrix(0.0, 0.0, numpy.pi/2.0) >>> numpy.allclose(quaternion_from_matrix(R, isprecise=False), ... quaternion_from_matrix(R, isprecise=True)) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:4, :4] if isprecise: q = numpy.empty((4, )) t = numpy.trace(M) if t > M[3, 3]: q[0] = t q[3] = M[1, 0] - M[0, 1] q[2] = M[0, 2] - M[2, 0] q[1] = M[2, 1] - M[1, 2] else: i, j, k = 1, 2, 3 if M[1, 1] > M[0, 0]: i, j, k = 2, 3, 1 if M[2, 2] > M[i, i]: i, j, k = 3, 1, 2 t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3] q[i] = t q[j] = M[i, j] + M[j, i] q[k] = M[k, i] + M[i, k] q[3] = M[k, j] - M[j, k] q *= 0.5 / math.sqrt(t * M[3, 3]) else: m00 = M[0, 0] m01 = M[0, 1] m02 = M[0, 2] m10 = M[1, 0] m11 = M[1, 1] m12 = M[1, 2] m20 = M[2, 0] m21 = M[2, 1] m22 = M[2, 2] # symmetric matrix K K = numpy.array([[m00-m11-m22, 0.0, 0.0, 0.0], [m01+m10, m11-m00-m22, 0.0, 0.0], [m02+m20, m12+m21, m22-m00-m11, 0.0], [m21-m12, m02-m20, m10-m01, m00+m11+m22]]) K /= 3.0 # quaternion is eigenvector of K that corresponds to largest eigenvalue w, V = numpy.linalg.eigh(K) q = V[[3, 0, 1, 2], numpy.argmax(w)] if q[0] < 0.0: numpy.negative(q, q) return q def quaternion_multiply(quaternion1, quaternion0): """Return multiplication of two quaternions. >>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7]) >>> numpy.allclose(q, [28, -44, -14, 48]) True """ w0, x0, y0, z0 = quaternion0 w1, x1, y1, z1 = quaternion1 return numpy.array([-x1*x0 - y1*y0 - z1*z0 + w1*w0, x1*w0 + y1*z0 - z1*y0 + w1*x0, -x1*z0 + y1*w0 + z1*x0 + w1*y0, x1*y0 - y1*x0 + z1*w0 + w1*z0], dtype=numpy.float64) def quaternion_conjugate(quaternion): """Return conjugate of quaternion. >>> q0 = random_quaternion() >>> q1 = quaternion_conjugate(q0) >>> q1[0] == q0[0] and all(q1[1:] == -q0[1:]) True """ q = numpy.array(quaternion, dtype=numpy.float64, copy=True) numpy.negative(q[1:], q[1:]) return q def quaternion_inverse(quaternion): """Return inverse of quaternion. >>> q0 = random_quaternion() >>> q1 = quaternion_inverse(q0) >>> numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0]) True """ q = numpy.array(quaternion, dtype=numpy.float64, copy=True) numpy.negative(q[1:], q[1:]) return q / numpy.dot(q, q) def quaternion_real(quaternion): """Return real part of quaternion. >>> quaternion_real([3, 0, 1, 2]) 3.0 """ return float(quaternion[0]) def quaternion_imag(quaternion): """Return imaginary part of quaternion. >>> quaternion_imag([3, 0, 1, 2]) array([ 0., 1., 2.]) """ return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True) def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True): """Return spherical linear interpolation between two quaternions. >>> q0 = random_quaternion() >>> q1 = random_quaternion() >>> q = quaternion_slerp(q0, q1, 0) >>> numpy.allclose(q, q0) True >>> q = quaternion_slerp(q0, q1, 1, 1) >>> numpy.allclose(q, q1) True >>> q = quaternion_slerp(q0, q1, 0.5) >>> angle = math.acos(numpy.dot(q0, q)) >>> numpy.allclose(2, math.acos(numpy.dot(q0, q1)) / angle) or \ numpy.allclose(2, math.acos(-numpy.dot(q0, q1)) / angle) True """ q0 = unit_vector(quat0[:4]) q1 = unit_vector(quat1[:4]) if fraction == 0.0: return q0 elif fraction == 1.0: return q1 d = numpy.dot(q0, q1) if abs(abs(d) - 1.0) < _EPS: return q0 if shortestpath and d < 0.0: # invert rotation d = -d numpy.negative(q1, q1) angle = math.acos(d) + spin * math.pi if abs(angle) < _EPS: return q0 isin = 1.0 / math.sin(angle) q0 *= math.sin((1.0 - fraction) * angle) * isin q1 *= math.sin(fraction * angle) * isin q0 += q1 return q0 def random_quaternion(rand=None): """Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quaternion() >>> numpy.allclose(1, vector_norm(q)) True >>> q = random_quaternion(numpy.random.random(3)) >>> len(q.shape), q.shape[0]==4 (1, True) """ if rand is None: rand = numpy.random.rand(3) else: assert len(rand) == 3 r1 = numpy.sqrt(1.0 - rand[0]) r2 = numpy.sqrt(rand[0]) pi2 = math.pi * 2.0 t1 = pi2 * rand[1] t2 = pi2 * rand[2] return numpy.array([numpy.cos(t2)*r2, numpy.sin(t1)*r1, numpy.cos(t1)*r1, numpy.sin(t2)*r2]) def random_rotation_matrix(rand=None): """Return uniform random rotation matrix. rand: array like Three independent random variables that are uniformly distributed between 0 and 1 for each returned quaternion. >>> R = random_rotation_matrix() >>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4)) True """ return quaternion_matrix(random_quaternion(rand)) class Arcball(object): """Virtual Trackball Control. >>> ball = Arcball() >>> ball = Arcball(initial=numpy.identity(4)) >>> ball.place([320, 320], 320) >>> ball.down([500, 250]) >>> ball.drag([475, 275]) >>> R = ball.matrix() >>> numpy.allclose(numpy.sum(R), 3.90583455) True >>> ball = Arcball(initial=[1, 0, 0, 0]) >>> ball.place([320, 320], 320) >>> ball.setaxes([1, 1, 0], [-1, 1, 0]) >>> ball.constrain = True >>> ball.down([400, 200]) >>> ball.drag([200, 400]) >>> R = ball.matrix() >>> numpy.allclose(numpy.sum(R), 0.2055924) True >>> ball.next() """ def __init__(self, initial=None): """Initialize virtual trackball control. initial : quaternion or rotation matrix """ self._axis = None self._axes = None self._radius = 1.0 self._center = [0.0, 0.0] self._vdown = numpy.array([0.0, 0.0, 1.0]) self._constrain = False if initial is None: self._qdown = numpy.array([1.0, 0.0, 0.0, 0.0]) else: initial = numpy.array(initial, dtype=numpy.float64) if initial.shape == (4, 4): self._qdown = quaternion_from_matrix(initial) elif initial.shape == (4, ): initial /= vector_norm(initial) self._qdown = initial else: raise ValueError("initial not a quaternion or matrix") self._qnow = self._qpre = self._qdown def place(self, center, radius): """Place Arcball, e.g. when window size changes. center : sequence[2] Window coordinates of trackball center. radius : float Radius of trackball in window coordinates. """ self._radius = float(radius) self._center[0] = center[0] self._center[1] = center[1] def setaxes(self, *axes): """Set axes to constrain rotations.""" if axes is None: self._axes = None else: self._axes = [unit_vector(axis) for axis in axes] @property def constrain(self): """Return state of constrain to axis mode.""" return self._constrain @constrain.setter def constrain(self, value): """Set state of constrain to axis mode.""" self._constrain = bool(value) def down(self, point): """Set initial cursor window coordinates and pick constrain-axis.""" self._vdown = arcball_map_to_sphere(point, self._center, self._radius) self._qdown = self._qpre = self._qnow if self._constrain and self._axes is not None: self._axis = arcball_nearest_axis(self._vdown, self._axes) self._vdown = arcball_constrain_to_axis(self._vdown, self._axis) else: self._axis = None def drag(self, point): """Update current cursor window coordinates.""" vnow = arcball_map_to_sphere(point, self._center, self._radius) if self._axis is not None: vnow = arcball_constrain_to_axis(vnow, self._axis) self._qpre = self._qnow t = numpy.cross(self._vdown, vnow) if numpy.dot(t, t) < _EPS: self._qnow = self._qdown else: q = [numpy.dot(self._vdown, vnow), t[0], t[1], t[2]] self._qnow = quaternion_multiply(q, self._qdown) def next(self, acceleration=0.0): """Continue rotation in direction of last drag.""" q = quaternion_slerp(self._qpre, self._qnow, 2.0+acceleration, False) self._qpre, self._qnow = self._qnow, q def matrix(self): """Return homogeneous rotation matrix.""" return quaternion_matrix(self._qnow) def arcball_map_to_sphere(point, center, radius): """Return unit sphere coordinates from window coordinates.""" v0 = (point[0] - center[0]) / radius v1 = (center[1] - point[1]) / radius n = v0*v0 + v1*v1 if n > 1.0: # position outside of sphere n = math.sqrt(n) return numpy.array([v0/n, v1/n, 0.0]) else: return numpy.array([v0, v1, math.sqrt(1.0 - n)]) def arcball_constrain_to_axis(point, axis): """Return sphere point perpendicular to axis.""" v = numpy.array(point, dtype=numpy.float64, copy=True) a = numpy.array(axis, dtype=numpy.float64, copy=True) v -= a * numpy.dot(a, v) # on plane n = vector_norm(v) if n > _EPS: if v[2] < 0.0: numpy.negative(v, v) v /= n return v if a[2] == 1.0: return numpy.array([1.0, 0.0, 0.0]) return unit_vector([-a[1], a[0], 0.0]) def arcball_nearest_axis(point, axes): """Return axis, which arc is nearest to point.""" point = numpy.array(point, dtype=numpy.float64, copy=False) nearest = None mx = -1.0 for axis in axes: t = numpy.dot(arcball_constrain_to_axis(point, axis), point) if t > mx: nearest = axis mx = t return nearest # epsilon for testing whether a number is close to zero _EPS = numpy.finfo(float).eps * 4.0 # axis sequences for Euler angles _NEXT_AXIS = [1, 2, 0, 1] # map axes strings to/from tuples of inner axis, parity, repetition, frame _AXES2TUPLE = { 'sxyz': (0, 0, 0, 0), 'sxyx': (0, 0, 1, 0), 'sxzy': (0, 1, 0, 0), 'sxzx': (0, 1, 1, 0), 'syzx': (1, 0, 0, 0), 'syzy': (1, 0, 1, 0), 'syxz': (1, 1, 0, 0), 'syxy': (1, 1, 1, 0), 'szxy': (2, 0, 0, 0), 'szxz': (2, 0, 1, 0), 'szyx': (2, 1, 0, 0), 'szyz': (2, 1, 1, 0), 'rzyx': (0, 0, 0, 1), 'rxyx': (0, 0, 1, 1), 'ryzx': (0, 1, 0, 1), 'rxzx': (0, 1, 1, 1), 'rxzy': (1, 0, 0, 1), 'ryzy': (1, 0, 1, 1), 'rzxy': (1, 1, 0, 1), 'ryxy': (1, 1, 1, 1), 'ryxz': (2, 0, 0, 1), 'rzxz': (2, 0, 1, 1), 'rxyz': (2, 1, 0, 1), 'rzyz': (2, 1, 1, 1)} _TUPLE2AXES = dict((v, k) for k, v in list(_AXES2TUPLE.items())) def vector_norm(data, axis=None, out=None): """Return length, i.e. Euclidean norm, of ndarray along axis. >>> v = numpy.random.random(3) >>> n = vector_norm(v) >>> numpy.allclose(n, numpy.linalg.norm(v)) True >>> v = numpy.random.rand(6, 5, 3) >>> n = vector_norm(v, axis=-1) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=2))) True >>> n = vector_norm(v, axis=1) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1))) True >>> v = numpy.random.rand(5, 4, 3) >>> n = numpy.empty((5, 3)) >>> vector_norm(v, axis=1, out=n) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1))) True >>> vector_norm([]) 0.0 >>> vector_norm([1]) 1.0 """ data = numpy.array(data, dtype=numpy.float64, copy=True) if out is None: if data.ndim == 1: return math.sqrt(numpy.dot(data, data)) data *= data out = numpy.atleast_1d(numpy.sum(data, axis=axis)) numpy.sqrt(out, out) return out else: data *= data numpy.sum(data, axis=axis, out=out) numpy.sqrt(out, out) def unit_vector(data, axis=None, out=None): """Return ndarray normalized by length, i.e. Euclidean norm, along axis. >>> v0 = numpy.random.random(3) >>> v1 = unit_vector(v0) >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) True >>> v0 = numpy.random.rand(5, 4, 3) >>> v1 = unit_vector(v0, axis=-1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2) >>> numpy.allclose(v1, v2) True >>> v1 = unit_vector(v0, axis=1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1) >>> numpy.allclose(v1, v2) True >>> v1 = numpy.empty((5, 4, 3)) >>> unit_vector(v0, axis=1, out=v1) >>> numpy.allclose(v1, v2) True >>> list(unit_vector([])) [] >>> list(unit_vector([1])) [1.0] """ if out is None: data = numpy.array(data, dtype=numpy.float64, copy=True) if data.ndim == 1: data /= math.sqrt(numpy.dot(data, data)) return data else: if out is not data: out[:] = numpy.array(data, copy=False) data = out length = numpy.atleast_1d(numpy.sum(data*data, axis)) numpy.sqrt(length, length) if axis is not None: length = numpy.expand_dims(length, axis) data /= length if out is None: return data def random_vector(size): """Return array of random doubles in the half-open interval [0.0, 1.0). >>> v = random_vector(10000) >>> numpy.all(v >= 0) and numpy.all(v < 1) True >>> v0 = random_vector(10) >>> v1 = random_vector(10) >>> numpy.any(v0 == v1) False """ return numpy.random.random(size) def vector_product(v0, v1, axis=0): """Return vector perpendicular to vectors. >>> v = vector_product([2, 0, 0], [0, 3, 0]) >>> numpy.allclose(v, [0, 0, 6]) True >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]] >>> v1 = [[3], [0], [0]] >>> v = vector_product(v0, v1) >>> numpy.allclose(v, [[0, 0, 0, 0], [0, 0, 6, 6], [0, -6, 0, -6]]) True >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]] >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]] >>> v = vector_product(v0, v1, axis=1) >>> numpy.allclose(v, [[0, 0, 6], [0, -6, 0], [6, 0, 0], [0, -6, 6]]) True """ return numpy.cross(v0, v1, axis=axis) def angle_between_vectors(v0, v1, directed=True, axis=0): """Return angle between vectors. If directed is False, the input vectors are interpreted as undirected axes, i.e. the maximum angle is pi/2. >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3]) >>> numpy.allclose(a, math.pi) True >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False) >>> numpy.allclose(a, 0) True >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]] >>> v1 = [[3], [0], [0]] >>> a = angle_between_vectors(v0, v1) >>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532]) True >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]] >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]] >>> a = angle_between_vectors(v0, v1, axis=1) >>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532]) True """ v0 = numpy.array(v0, dtype=numpy.float64, copy=False) v1 = numpy.array(v1, dtype=numpy.float64, copy=False) dot = numpy.sum(v0 * v1, axis=axis) dot /= vector_norm(v0, axis=axis) * vector_norm(v1, axis=axis) return numpy.arccos(dot if directed else numpy.fabs(dot)) def inverse_matrix(matrix): """Return inverse of square transformation matrix. >>> M0 = random_rotation_matrix() >>> M1 = inverse_matrix(M0.T) >>> numpy.allclose(M1, numpy.linalg.inv(M0.T)) True >>> for size in range(1, 7): ... M0 = numpy.random.rand(size, size) ... M1 = inverse_matrix(M0) ... if not numpy.allclose(M1, numpy.linalg.inv(M0)): print(size) """ return numpy.linalg.inv(matrix) def concatenate_matrices(*matrices): """Return concatenation of series of transformation matrices. >>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5 >>> numpy.allclose(M, concatenate_matrices(M)) True >>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T)) True """ M = numpy.identity(4) for i in matrices: M = numpy.dot(M, i) return M def is_same_transform(matrix0, matrix1): """Return True if two matrices perform same transformation. >>> is_same_transform(numpy.identity(4), numpy.identity(4)) True >>> is_same_transform(numpy.identity(4), random_rotation_matrix()) False """ matrix0 = numpy.array(matrix0, dtype=numpy.float64, copy=True) matrix0 /= matrix0[3, 3] matrix1 = numpy.array(matrix1, dtype=numpy.float64, copy=True) matrix1 /= matrix1[3, 3] return numpy.allclose(matrix0, matrix1) def _import_module(name, package=None, warn=True, prefix='_py_', ignore='_'): """Try import all public attributes from module into global namespace. Existing attributes with name clashes are renamed with prefix. Attributes starting with underscore are ignored by default. Return True on successful import. """ import warnings from importlib import import_module try: if not package: module = import_module(name) else: module = import_module('.' + name, package=package) except ImportError: if warn: warnings.warn("failed to import module %s" % name) else: for attr in dir(module): if ignore and attr.startswith(ignore): continue if prefix: if attr in globals(): globals()[prefix + attr] = globals()[attr] elif warn: warnings.warn("no Python implementation of " + attr) globals()[attr] = getattr(module, attr) return True #_import_module('_transformations') if __name__ == "__main__": import doctest import random # used in doctests numpy.set_printoptions(suppress=True, precision=5) doctest.testmod()
Python
3D
Autodesk/molecular-design-toolkit
moldesign/external/pyquante2/__init__.py
.py
0
0
null
Python
3D
Autodesk/molecular-design-toolkit
moldesign/external/pyquante2/utils.py
.py
6,283
243
""" utils.py - Simple utilility funtions used in pyquante2. """ import numpy as np from math import factorial,lgamma from itertools import combinations_with_replacement,combinations from functools import reduce def pairs(it): return combinations_with_replacement(it,2) def upairs(it): return combinations(it,2) def fact2(n): """ fact2(n) - n!!, double factorial of n >>> fact2(0) 1 >>> fact2(1) 1 >>> fact2(3) 3 >>> fact2(8) 384 >>> fact2(-1) 1 """ return reduce(int.__mul__,range(n,0,-2),1) def norm2(a): return np.dot(a,a) def binomial(n,k): """ Binomial coefficient >>> binomial(5,2) 10 >>> binomial(10,5) 252 """ if n == k: return 1 assert n>k, "Attempting to call binomial(%d,%d)" % (n,k) return factorial(n)//(factorial(k)*factorial(n-k)) def Fgamma(m,x): """ Incomplete gamma function >>> np.isclose(Fgamma(0,0),1.0) True """ SMALL=1e-12 x = max(x,SMALL) return 0.5*pow(x,-m-0.5)*gamm_inc(m+0.5,x) # def gamm_inc_scipy(a,x): # """ # Demonstration on how to replace the gamma calls with scipy.special functions. # By default, pyquante only requires numpy, but this may change as scipy # builds become more stable. # >>> np.isclose(gamm_inc_scipy(0.5,1),1.49365) # True # >>> np.isclose(gamm_inc_scipy(1.5,2),0.6545103) # True # >>> np.isclose(gamm_inc_scipy(2.5,1e-12),0) # True # """ # from scipy.special import gamma,gammainc # return gamma(a)*gammainc(a,x) def gamm_inc(a,x): """ Incomple gamma function \gamma; computed from NumRec routine gammp. >>> np.isclose(gamm_inc(0.5,1),1.49365) True >>> np.isclose(gamm_inc(1.5,2),0.6545103) True >>> np.isclose(gamm_inc(2.5,1e-12),0) True """ assert (x > 0 and a >= 0), "Invalid arguments in routine gamm_inc: %s,%s" % (x,a) if x < (a+1.0): #Use the series representation gam,gln = _gser(a,x) else: #Use continued fractions gamc,gln = _gcf(a,x) gam = 1-gamc return np.exp(gln)*gam def _gser(a,x): "Series representation of Gamma. NumRec sect 6.1." ITMAX=100 EPS=3.e-7 gln=lgamma(a) assert(x>=0),'x < 0 in gser' if x == 0 : return 0,gln ap = a delt = sum = 1./a for i in range(ITMAX): ap=ap+1. delt=delt*x/ap sum=sum+delt if abs(delt) < abs(sum)*EPS: break else: print('a too large, ITMAX too small in gser') gamser=sum*np.exp(-x+a*np.log(x)-gln) return gamser,gln def _gcf(a,x): "Continued fraction representation of Gamma. NumRec sect 6.1" ITMAX=100 EPS=3.e-7 FPMIN=1.e-30 gln=lgamma(a) b=x+1.-a c=1./FPMIN d=1./b h=d for i in range(1,ITMAX+1): an=-i*(i-a) b=b+2. d=an*d+b if abs(d) < FPMIN: d=FPMIN c=b+an/c if abs(c) < FPMIN: c=FPMIN d=1./d delt=d*c h=h*delt if abs(delt-1.) < EPS: break else: print('a too large, ITMAX too small in gcf') gammcf=np.exp(-x+a*np.log(x)-gln)*h return gammcf,gln def trace2(A,B): "Return trace(AB) of matrices A and B" return np.sum(A*B) def dmat(c,nclosed,nopen=0): """Form the density matrix from the first nclosed orbitals of c. If nopen != 0, add in half the density matrix from the next nopen orbitals. """ d = np.dot(c[:,:nclosed],c[:,:nclosed].T) if nopen > 0: d += 0.5*np.dot(c[:,nclosed:(nclosed+nopen)],c[:,nclosed:(nclosed+nopen)].T) return d def symorth(S): "Symmetric orthogonalization" E,U = np.linalg.eigh(S) n = len(E) Shalf = np.identity(n,'d') for i in range(n): Shalf[i,i] /= np.sqrt(E[i]) return simx(Shalf,U,True) def canorth(S): "Canonical orthogonalization U/sqrt(lambda)" E,U = np.linalg.eigh(S) for i in range(len(E)): U[:,i] = U[:,i] / np.sqrt(E[i]) return U def cholorth(S): "Cholesky orthogonalization" return np.linalg.inv(np.linalg.cholesky(S)).T def simx(A,B,transpose=False): "Similarity transform B^T(AB) or B(AB^T) (if transpose)" if transpose: return np.dot(B,np.dot(A,B.T)) return np.dot(B.T,np.dot(A,B)) def ao2mo(H,C): return simx(H,C) def mo2ao(H,C,S): return simx(H,np.dot(S,C),transpose=True) def geigh(H,S): "Solve the generalized eigensystem Hc = ESc" A = cholorth(S) E,U = np.linalg.eigh(simx(H,A)) return E,np.dot(A,U) def parseline(line,format): """\ Given a line (a string actually) and a short string telling how to format it, return a list of python objects that result. The format string maps words (as split by line.split()) into python code: x -> Nothing; skip this word s -> Return this word as a string i -> Return this word as an int d -> Return this word as an int f -> Return this word as a float Basic parsing of strings: >>> parseline('Hello, World','ss') ['Hello,', 'World'] You can use 'x' to skip a record; you also don't have to parse every record: >>> parseline('1 2 3 4','xdd') [2, 3] >>> parseline('C1 0.0 0.0 0.0','sfff') ['C1', 0.0, 0.0, 0.0] Should this return an empty list? >>> parseline('This line wont be parsed','xx') """ xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} result = [] words = line.split() for i in range(len(format)): f = format[i] trans = xlat.get(f,None) if trans: result.append(trans(words[i])) if len(result) == 0: return None if len(result) == 1: return result[0] return result def colorscale(mag, cmin, cmax): """ Return a tuple of floats between 0 and 1 for R, G, and B. From Python Cookbook (9.11?) """ # Normalize to 0-1 try: x = float(mag-cmin)/(cmax-cmin) except ZeroDivisionError: x = 0.5 # cmax == cmin blue = min((max((4*(0.75-x), 0.)), 1.)) red = min((max((4*(x-0.25), 0.)), 1.)) green = min((max((4*abs(x-0.5)-1., 0.)), 1.)) return red, green, blue #Todo: replace with np.isclose #def isnear(a,b,tol=1e-6): return abs(a-b) < tol if __name__ == '__main__': import doctest doctest.testmod()
Python
3D
Autodesk/molecular-design-toolkit
moldesign/external/pyquante2/one.py
.py
7,343
254
""" One electron integrals. """ from numpy import pi,exp,floor,array,isclose from math import factorial ## BEGIN MODIFIED CODE: #from pyquante2.utils import binomial, fact2, Fgamma, norm2 from .utils import binomial, fact2, Fgamma, norm2 #END MODIFIED CODE # Notes: # The versions S,T,V include the normalization constants # The version overlap,kinetic,nuclear_attraction do not. # This is so, for example, the kinetic routines can call the potential routines # without the normalization constants getting in the way. def S(a,b): """ Simple interface to the overlap function. >>> from pyquante2 import pgbf,cgbf >>> s = pgbf(1) >>> isclose(S(s,s),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,sc),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,s),1.0) True >>> isclose(S(s,sc),1.0) True """ if b.contracted: return sum(cb*S(pb,a) for (cb,pb) in b) elif a.contracted: return sum(ca*S(b,pa) for (ca,pa) in a) return a.norm*b.norm*overlap(a.exponent,a.powers, a.origin,b.exponent,b.powers,b.origin) def T(a,b): """ Simple interface to the kinetic function. >>> from pyquante2 import pgbf,cgbf >>> from pyquante2.basis.pgbf import pgbf >>> s = pgbf(1) >>> isclose(T(s,s),1.5) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(T(sc,sc),1.5) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(T(sc,s),1.5) True >>> isclose(T(s,sc),1.5) True """ if b.contracted: return sum(cb*T(pb,a) for (cb,pb) in b) elif a.contracted: return sum(ca*T(b,pa) for (ca,pa) in a) return a.norm*b.norm*kinetic(a.exponent,a.powers,a.origin, b.exponent,b.powers,b.origin) def V(a,b,C): """ Simple interface to the nuclear attraction function. >>> from pyquante2 import pgbf,cgbf >>> s = pgbf(1) >>> isclose(V(s,s,(0,0,0)),-1.595769) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(V(sc,sc,(0,0,0)),-1.595769) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(V(sc,s,(0,0,0)),-1.595769) True >>> isclose(V(s,sc,(0,0,0)),-1.595769) True """ if b.contracted: return sum(cb*V(pb,a,C) for (cb,pb) in b) elif a.contracted: return sum(ca*V(b,pa,C) for (ca,pa) in a) return a.norm*b.norm*nuclear_attraction(a.exponent,a.powers,a.origin, b.exponent,b.powers,b.origin,C) def overlap(alpha1,lmn1,A,alpha2,lmn2,B): """ Full form of the overlap integral. Taken from THO eq. 2.12 >>> isclose(overlap(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d')),1.968701) True """ l1,m1,n1 = lmn1 l2,m2,n2 = lmn2 rab2 = norm2(A-B) gamma = alpha1+alpha2 P = gaussian_product_center(alpha1,A,alpha2,B) pre = pow(pi/gamma,1.5)*exp(-alpha1*alpha2*rab2/gamma) wx = overlap1d(l1,l2,P[0]-A[0],P[0]-B[0],gamma) wy = overlap1d(m1,m2,P[1]-A[1],P[1]-B[1],gamma) wz = overlap1d(n1,n2,P[2]-A[2],P[2]-B[2],gamma) return pre*wx*wy*wz def overlap1d(l1,l2,PAx,PBx,gamma): """ The one-dimensional component of the overlap integral. Taken from THO eq. 2.12 >>> isclose(overlap1d(0,0,0,0,1),1.0) True """ total = 0 for i in range(1+int(floor(0.5*(l1+l2)))): total += binomial_prefactor(2*i,l1,l2,PAx,PBx)* \ fact2(2*i-1)/pow(2*gamma,i) return total def gaussian_product_center(alpha1,A,alpha2,B): """ The center of the Gaussian resulting from the product of two Gaussians: >>> gaussian_product_center(1,array((0,0,0),'d'),1,array((0,0,0),'d')) array([ 0., 0., 0.]) """ return (alpha1*A+alpha2*B)/(alpha1+alpha2) def binomial_prefactor(s,ia,ib,xpa,xpb): """ The integral prefactor containing the binomial coefficients from Augspurger and Dykstra. >>> binomial_prefactor(0,0,0,0,0) 1 """ total= 0 for t in range(s+1): if s-ia <= t <= ib: total += binomial(ia,s-t)*binomial(ib,t)* \ pow(xpa,ia-s+t)*pow(xpb,ib-t) return total def kinetic(alpha1,lmn1,A,alpha2,lmn2,B): """ The full form of the kinetic energy integral >>> isclose(kinetic(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d')),2.953052) True """ l1,m1,n1 = lmn1 l2,m2,n2 = lmn2 term0 = alpha2*(2*(l2+m2+n2)+3)*\ overlap(alpha1,(l1,m1,n1),A,\ alpha2,(l2,m2,n2),B) term1 = -2*pow(alpha2,2)*\ (overlap(alpha1,(l1,m1,n1),A, alpha2,(l2+2,m2,n2),B) + overlap(alpha1,(l1,m1,n1),A, alpha2,(l2,m2+2,n2),B) + overlap(alpha1,(l1,m1,n1),A, alpha2,(l2,m2,n2+2),B)) term2 = -0.5*(l2*(l2-1)*overlap(alpha1,(l1,m1,n1),A, alpha2,(l2-2,m2,n2),B) + m2*(m2-1)*overlap(alpha1,(l1,m1,n1),A, alpha2,(l2,m2-2,n2),B) + n2*(n2-1)*overlap(alpha1,(l1,m1,n1),A, alpha2,(l2,m2,n2-2),B)) return term0+term1+term2 def nuclear_attraction(alpha1,lmn1,A,alpha2,lmn2,B,C): """ Full form of the nuclear attraction integral >>> isclose(nuclear_attraction(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d'),array((0,0,0),'d')),-3.141593) True """ l1,m1,n1 = lmn1 l2,m2,n2 = lmn2 gamma = alpha1+alpha2 P = gaussian_product_center(alpha1,A,alpha2,B) rab2 = norm2(A-B) rcp2 = norm2(C-P) dPA = P-A dPB = P-B dPC = P-C Ax = A_array(l1,l2,dPA[0],dPB[0],dPC[0],gamma) Ay = A_array(m1,m2,dPA[1],dPB[1],dPC[1],gamma) Az = A_array(n1,n2,dPA[2],dPB[2],dPC[2],gamma) total = 0. for I in range(l1+l2+1): for J in range(m1+m2+1): for K in range(n1+n2+1): total += Ax[I]*Ay[J]*Az[K]*Fgamma(I+J+K,rcp2*gamma) val= -2*pi/gamma*exp(-alpha1*alpha2*rab2/gamma)*total return val def A_term(i,r,u,l1,l2,PAx,PBx,CPx,gamma): """ THO eq. 2.18 >>> A_term(0,0,0,0,0,0,0,0,1) 1.0 >>> A_term(0,0,0,0,1,1,1,1,1) 1.0 >>> A_term(1,0,0,0,1,1,1,1,1) -1.0 >>> A_term(0,0,0,1,1,1,1,1,1) 1.0 >>> A_term(1,0,0,1,1,1,1,1,1) -2.0 >>> A_term(2,0,0,1,1,1,1,1,1) 1.0 >>> A_term(2,0,1,1,1,1,1,1,1) -0.5 >>> A_term(2,1,0,1,1,1,1,1,1) 0.5 """ return pow(-1,i)*binomial_prefactor(i,l1,l2,PAx,PBx)*\ pow(-1,u)*factorial(i)*pow(CPx,i-2*r-2*u)*\ pow(0.25/gamma,r+u)/factorial(r)/factorial(u)/factorial(i-2*r-2*u) def A_array(l1,l2,PA,PB,CP,g): """ THO eq. 2.18 and 3.1 >>> A_array(0,0,0,0,0,1) [1.0] >>> A_array(0,1,1,1,1,1) [1.0, -1.0] >>> A_array(1,1,1,1,1,1) [1.5, -2.5, 1.0] """ Imax = l1+l2+1 A = [0]*Imax for i in range(Imax): for r in range(int(floor(i/2)+1)): for u in range(int(floor((i-2*r)/2)+1)): I = i-2*r-u A[I] = A[I] + A_term(i,r,u,l1,l2,PA,PB,CP,g) return A if __name__ == '__main__': import doctest; doctest.testmod()
Python
3D
Autodesk/molecular-design-toolkit
moldesign/mathutils/__init__.py
.py
67
3
from .vectormath import * from .eigen import * from .grids import *
Python
3D
Autodesk/molecular-design-toolkit
moldesign/mathutils/spherical_harmonics.py
.py
6,809
199
from __future__ import print_function, absolute_import, division from future import standard_library standard_library.install_aliases() from future.builtins import * # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np __all__ = ['SPHERE_TO_CART'] def cart_to_polar_angles(coords): if len(coords.shape) == 2: r_xy_2 = np.sum(coords[:,:2]**2, axis=1) theta = np.arctan2(np.sqrt(r_xy_2), coords[:,2]) phi = np.arctan2(coords[:,1], coords[:,0]) return theta, phi else: assert len(coords) == 3 and len(coords.shape) == 1 r_xy_2 = np.sum(coords[:2]**2) theta = np.arctan2(np.sqrt(r_xy_2), coords[2]) phi = np.arctan2(coords[1], coords[0]) return theta, phi class Y(object): r""" A real-valued spherical harmonic function These functions are orthonormalized over the sphere such that .. math:: \int d^2\Omega \: Y_{lm}(\theta, \phi) Y_{l'm'}(\theta, \phi) = \delta_{l,l'} \delta_{m,m'} References: https://en.wikipedia.org/wiki/Table_of_spherical_harmonics#Real_spherical_harmonics """ def __init__(self, l, m): self.l = l self.m = m self._posneg = -1 if self.m < 0: self._posneg *= -1 if self.m % 2 == 0: self._posneg *= -1 def __call__(self, coords): from scipy.special import sph_harm theta, phi = cart_to_polar_angles(coords) if self.m == 0: return (sph_harm(self.m, self.l, phi, theta)).real vplus = sph_harm(abs(self.m), self.l, phi, theta) vminus = sph_harm(-abs(self.m), self.l, phi, theta) value = np.sqrt(1/2.0) * (self._posneg*vplus + vminus) if self.m < 0: return -value.imag else: return value.real class Cart(object): def __init__(self, px, py, pz, coeff): self.powers = np.array([px, py, pz], dtype='int') self.coeff = coeff self._l = self.powers.sum() def __call__(self, coords): """ Evaluate this function at the given list of coordinates Args: coords (Vector[len=3] or Matrix[matrix=shape(*,3)): coordinate(s) at which to evaluate Returns: Scalar or Vector: value of the function at these coordinates """ c = coords**self.powers if len(coords.shape) == 2: r_l = (coords**2).sum(axis=1) ** (-self._l / 2.0) return self.coeff * np.product(c, axis=1) * r_l else: r_l = (coords**2).sum() ** (-self._l / 2.0) return self.coeff * np.product(c) * r_l def __iter__(self): yield self # for interface compatibility with the CartSum class class CartSum(object): def __init__(self, coeff, carts): self.coeff = coeff prefacs = [] powers = [] self.l = None for cart in carts: powers.append(np.array(cart[:3], dtype='int')) prefacs.append(np.array(cart[3])) if self.l is None: self.l = sum(cart[:3]) else: assert self.l == sum(cart[:3]) self.prefactors = np.array(prefacs) self.powers = np.array(powers) def __call__(self, coords): # likely can speed this up a lot using clever numpy broadcasting if len(coords.shape) == 2: c = np.zeros((len(coords), )) axis = 1 r_l = (coords**2).sum(axis=1) ** (-self.l / 2.0) else: c = 0.0 axis = None r_l = (coords**2).sum() ** (-self.l / 2.0) for factor, power in zip(self.prefactors, self.powers): c += factor * np.product(coords**power, axis=axis) return c * self.coeff * r_l def __iter__(self): for pf, (px, py, pz) in zip(self.prefactors, self.powers): yield Cart(px, py, pz, coeff=self.coeff*pf) def sqrt_x_over_pi(num, denom): return np.sqrt(num / (denom*np.pi)) ############ s ############ SPHERE_TO_CART = {(0, 0): Cart(0, 0, 0, sqrt_x_over_pi(1, 4)), ############ p ############ (1, -1): Cart(0, 1, 0, sqrt_x_over_pi(3, 4)), (1, 0): Cart(0, 0, 1, sqrt_x_over_pi(3, 4)), (1, 1): Cart(1, 0, 0, sqrt_x_over_pi(3, 4)), ############ d ############ (2, -2): Cart(1, 1, 0, sqrt_x_over_pi(15, 4)), (2, -1): Cart(0, 1, 1, sqrt_x_over_pi(15, 4)), (2, 0): CartSum(sqrt_x_over_pi(5, 16), [(2, 0, 0, -1.0), (0, 2, 0, -1.0), (0, 0, 2, 2.0)]), (2, 1): Cart(1, 0, 1, sqrt_x_over_pi(15, 4)), (2, 2): CartSum(sqrt_x_over_pi(15, 16), [(2, 0, 0, 1.0), (0, 2, 0, -1.0)]), ############ f ############ (3, -3): CartSum(sqrt_x_over_pi(35, 32), [(2, 1, 0, 3.0), (0, 3, 0, -1.0)]), (3, -2): Cart(1, 1, 1, sqrt_x_over_pi(105, 4)), (3, -1): CartSum(sqrt_x_over_pi(21, 32), [(0, 1, 2, 4.0), (2, 1, 0, -1.0), (0, 3, 0, -1.0)]), (3, 0): CartSum(sqrt_x_over_pi(7, 16), [(0, 0, 3, 2.0), (2, 0, 1, -3.0), (0, 2, 1, -3.0)]), (3, 1): CartSum(sqrt_x_over_pi(21, 32), [(1, 0, 2, 4.0), (3, 0, 0, -1.0), (1, 2, 0, -1.0)]), (3, 2): CartSum(sqrt_x_over_pi(105, 16), [(2, 0, 1, 1.0), (0, 2, 1, -1.0)]), (3, 3): CartSum(sqrt_x_over_pi(35, 32), [(3, 0, 0, 1.0), (1, 2, 0, -3.0)]), }
Python
3D
Autodesk/molecular-design-toolkit
moldesign/mathutils/vectormath.py
.py
5,770
191
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from .. import units as u from ..utils import exports @exports def perpendicular(vec): """ Return arbitrary unit vector(s) perpendicular to one or more vectors. This obviously doesn't have a unique solution, but is useful for various computations. Args: vec (Vector or List[Vector]): 3-D vector or list thereof Returns: vec (np.ndarray): normalized unit vector in a perpendicular direction """ vectorized = len(vec.shape) > 1 direction = normalized(vec) if vectorized: cross_axis = np.array([[0.0, 0.0, 1.0] if d[2] < 0.9 else [0.0, 1.0, 0.0] for d in direction]) else: if abs(direction[2]) < 0.9: cross_axis = np.array([0.0, 0.0, 1.0]) else: cross_axis = np.array([0.0, 1.0, 0.0]) perp = normalized(np.cross(direction, cross_axis)) return perp @exports def norm(vec): """ Calculate norm of a vector or list thereof Args: vec (Vector or List[Vector]): vector(s) to compute norm of Returns: Scalar or List[Scalar]: norms """ if len(vec.shape) == 1: # it's just a single column vector return np.sqrt(vec.dot(vec)) else: # treat as list of vectors return np.sqrt((vec*vec).sum(axis=1)) @exports def normalized(vector, zero_as_zero=True): """ Create normalized versions of a vector or lists of vectors. Args: vector (Vector or List[Vector]): vector(s) to be normalized zero_as_zero (bool): if True, return a 0-vector if a 0-vector is passed; otherwise, will follow default system behavior (depending on numpy's configuration) Returns: Vector or List[Vector]: normalized vector(s) """ vec = getattr(vector, 'magnitude', vector) # strip units right away if necessary mag = norm(vec) if len(vec.shape) == 1: # it's just a single column vector if mag == 0.0 and zero_as_zero: return vec*0.0 else: return vec/mag else: # treat as list of vectors if zero_as_zero: mag[mag == 0.0] = 1.0 # prevent div by 0 return vec / mag[:, None] @exports def alignment_rotation(v1, v2, handle_linear=True): """ Calculate rotation angle(s) and axi(e)s to make v1 parallel with v2 Args: v1 (vector or List[Vector]): 3-dimensional vector(s) to create rotation for v2 (vector or List[Vector]): 3-dimensional vector(s) to make v1 parallel to handle_linear (bool): if v1 is parallel or anti-parallel to v2, return an arbitrary vector perpendicular to both as the axis (otherwise, returns a 0-vector) Returns: MdtQuantity[angle]: angle between the two np.ndarray[len=3]: rotation axis (unit vector) References: https://stackoverflow.com/a/10145056/1958900 """ e1 = normalized(v1) e2 = normalized(v2) vectorize = len(e1.shape) > 1 normal = np.cross(e1, e2) s = norm(normal) if vectorize: c = (e1*e2).sum(axis=1) if handle_linear: linear_indices = s == 0.0 if linear_indices.any(): normal[linear_indices] = perpendicular(v1[linear_indices]) s[linear_indices] = 1.0 else: c = np.dot(e1, e2) if handle_linear and s == 0.0: normal = perpendicular(v1) s = 1.0 angle = np.arctan2(s, c) return angle*u.radian, normal / s @exports def safe_arccos(costheta): """ Version of arccos that can handle numerical noise greater than 1.0 """ if hasattr(costheta, 'shape') and costheta.shape: # vector version assert (np.abs(costheta)-1.0 < 1.0e-13).all() costheta[costheta > 1.0] = 1.0 costheta[costheta < -1.0] = -1.0 return np.arccos(costheta) else: if abs(costheta) > 1.0: assert abs(costheta) - 1.0 < 1.0e-14 return u.pi else: return np.arccos(costheta) @exports def sub_angles(a, b): """ Subtract two angles, keeping the result within [-180,180) """ return normalize_angle(a - b) @exports def normalize_angle(c): """ Normalize an angle to the interval [-180,180) """ return (c + 180.0 * u.degrees) % (360.0 * u.degrees) - (180.0 * u.degrees) @exports def apply_4x4_transform(trans, vecs): """ Applies a 4x4 transformation vector so one or more 3-D position vector :param trans: :param vecs: :return: transformed position vector """ has_units = False if hasattr(vecs, 'get_units'): has_units = True units = vecs.get_units() vecs = vecs.magnitude if len(vecs.shape) == 1: v = np.ones(4) v[:3] = vecs vt = trans.dot(v) result = vt[:3] / vt[3] else: v = np.ones((4, len(vecs))) v[:3, :] = vecs.T vt = trans.dot(v) result = (vt[:3] / vt[3]).T if has_units: result = result * units return result
Python
3D
Autodesk/molecular-design-toolkit
moldesign/mathutils/grids.py
.py
5,650
164
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import numpy as np from .. import utils from .. import units as u @utils.exports class VolumetricGrid(object): """ Creates a 3D, rectangular grid of points Args: xrange (Tuple[len=2]): (min,max) in x direction yrange (Tuple[len=2]): (min,max) in y direction zrange (Tuple[len=2]): (min,max) in z direction xpoints (int): number of grid lines in x direction (default: npoints) ypoints (int): number of grid lines in y direction (default: npoints) zpoints (int): number of grid lines in z direction (default: npoints) npoints (int): synonym for "xpoints" """ dx, dy, dz = (utils.IndexView('deltas', i) for i in range(3)) xr, yr, zr = (utils.IndexView('ranges', i) for i in range(3)) xpoints, ypoints, zpoints = (utils.IndexView('points', i) for i in range(3)) xspace, yspace, zspace = (utils.IndexView('spaces', i) for i in range(3)) def __init__(self, xrange, yrange, zrange, xpoints=None, ypoints=None, zpoints=None, npoints=32): if xpoints is not None: npoints = xpoints self.points = np.array([xpoints if xpoints is not None else npoints, ypoints if ypoints is not None else npoints, zpoints if zpoints is not None else npoints], dtype='int') self.ranges = u.array([xrange, yrange, zrange]) self.deltas = (self.ranges[:,1] - self.ranges[:,0]) / (self.points - 1.0) self.spaces = [u.linspace(*r, num=p) for r,p in zip(self.ranges, self.points)] @property def ndims(self): return len(self.ranges) ndim = num_dims = ndims @property def origin(self): """ Vector[len=3]: the origin of the grid (the lowermost corner in each dimension) """ origin = [r[0] for r in (self.ranges)] try: return u.array(origin) except u.DimensionalityError: return origin @property def npoints(self): """ int: total number of grid points in this grid """ return np.product(self.points) def iter_points(self): """ Iterate through every point on the grid. Always iterates in the same order. The x-index is the most slowly varying, the z-index is the fastest. Yields: Vector[len=3]: x,y,z coordinate of each point on the grid """ for i,j,k in itertools.product(*map(range, self.points)): yield self.origin + self.deltas * [i,j,k] def allpoints(self): """ Return an array of all coordinates on the grid. This obviously takes a lot of memory, but is useful for evaluating vectorized functions on this grid. Points are returned in the same order as ``iter_points``. Yields: Matrix[shape=(self.npoints**3,3)]: x,y,z coordinate of each point on the grid """ return _cartesian_product(self.spaces) def _cartesian_product(arrays): """ Fast grid creation routine from @senderle on Stack Overflow. This is awesome. Modifications: 1. Module import names 2. Unit handling References: https://stackoverflow.com/a/11146645/1958900 """ import functools # AMV mod for units handling units = getattr(arrays[0], 'units', u.ureg.dimensionless) # original code broadcastable = np.ix_(*arrays) broadcasted = np.broadcast_arrays(*broadcastable) rows, cols = functools.reduce(np.multiply, broadcasted[0].shape), len(broadcasted) out = np.empty(rows * cols, dtype=broadcasted[0].dtype) start, end = 0, rows for a in broadcasted: out[start:end] = a.reshape(-1) start, end = end, end + rows result = out.reshape(cols, rows).T # AMV mod for units handling if units == u.ureg.dimensionless: return result else: # do it this way to avoid copying a huge array quantity = u.MdtQuantity(result, units=units) return quantity @utils.exports def padded_grid(positions, padding, npoints=25): """ Creates a 3D, rectangular grid of points surrounding a set of positions The points in the grid are evenly spaced in each dimension, but spacing may differ between in different dimensions. Args: positions (Matrix[shape=(*,3)]): positions to create the grid around padding (Scalar): how far to extend the grid past the positions in each dimension npoints (int): number of points in each direction (total number of points is npoints**3) Returns: VolumetricGrid: grid object """ mins = positions.min(axis=0)-padding maxes = positions.max(axis=0)+padding xr = (mins[0], maxes[0]) yr = (mins[1], maxes[1]) zr = (mins[2], maxes[2]) return VolumetricGrid(xr, yr, zr, npoints)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/mathutils/eigen.py
.py
3,708
101
from __future__ import print_function, absolute_import, division from future import standard_library standard_library.install_aliases() from future.builtins import * # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .. import units as u from ..utils import exports from ..mathutils import normalized @exports class Eigenspace(object): """ Holds sets of eigenvactors and eigenvalues, offers helpful methods for organizing them. Args: evals (List[Scalar]): list of eigenvalues evecs (List[Vector]): list of eigenvectors (in the same order as eigenvalues). These will automatically be normalized Note: The eigenvectors from many eigenvector solvers - notably including scipy's - will need to be transposed to fit the form of ``evecs`` here! It's generally assumed that Eigenspace objects will be subclassed to wrap various bits of eignproblem-related functionality. """ def __init__(self, evals, evecs): if len(evals) != len(evecs): raise ValueError('Eigenvalues and eigenvectors have different lengths!') self.evals = u.array(evals) self.evecs = u.array([normalized(evec, zero_as_zero=True) for evec in evecs]) def __str__(self): return "%s of dimension %s" % (self.__class__.__name__, len(self.evals)) def sort(self, largest_first=True, key=abs): """ Sort the eigenvectors and values in place* By default, this sorts from largest to smallest by the _absolute magnitude_ of the eigenvalues. Note: *this sort is only "in place" in the sense that it mutates the data in this instance; note that it still uses auxiliary memroy Args: largest_first (bool): sort from largest to smallest (equivalent to ``reverse=True`` in a standard python sort, except that it is true by default here) key (callable): function of the form ``f(eigenval)`` OR ``f(eval, evec)``. By default, sorts by the ``abs`` of the eigenvalues """ try: # construct the sorting function result = key(self.evals[0], self.evecs[0]) except TypeError: def keyfn(t): return key(t[0]) else: def keyfn(t): return key(t[0], t[1]) evals, evecs = zip(*sorted(zip(self.evals.copy(), self.evecs.copy()), key=keyfn, reverse=largest_first)) self.evals[:] = evals self.evecs[:] = evecs def transform(self, coords): """ Transform a list of coordinates (or just a single one) into this eigenbasis Args: coords (List[Vector] or Vector): coordinate(s) to transform Returns: List[Vector] or vector: transformed coordinate(s) """ c = u.array(coords) dims = len(c.shape) if dims == 1: return u.dot(self.evecs, c) elif dims == 2: return u.dot(self.evecs, c.T).T else: raise ValueError('Transform accepts only 1- or 2-dimensional arrays')
Python
3D
Autodesk/molecular-design-toolkit
moldesign/min/scipy.py
.py
5,685
159
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .. import units as u from ..utils import exports from .base import MinimizerBase from .. import exceptions from . import toplevel class ScipyMinimizer(MinimizerBase): """ SciPy's implementation of the BFGS method, with gradients if available. Args: bfgs_threshold (u.Scalar[force]): Maximum force on a single atom Note: This implementation will fail rapidly if large forces are present (>> 1 eV/angstrom). """ _strip_units = True _METHOD_NAME = None _TAKES_FTOL = False _TAKES_GTOL = False def _run(self): import scipy.optimize if self.mol.constraints and self._METHOD_NAME == 'bfgs': raise exceptions.NotSupportedError('BFGS minimization does not ' 'support constrained minimization') print('Starting geometry optimization: SciPy/%s with %s gradients'%( self._METHOD_NAME, self.gradtype)) options = {'disp': True} if self.nsteps is not None: options['maxiter'] = self.nsteps if self.gradtype == 'analytical': grad = self.grad else: grad = None if self.force_tolerance is not None: if self._TAKES_GTOL: options['gtol'] = self.force_tolerance.defunits().magnitude elif self._TAKES_FTOL: print('WARNING: this method does not use force to measure convergence; ' 'approximating force_tolerance keyword') options['ftol'] = (self.force_tolerance * u.angstrom / 50.0).defunits_value() else: print('WARNING: no convergence criteria for this method; using defaults') self._optimize_kwargs = dict(method=self._METHOD_NAME, options=options) self._constraint_multiplier = 1.0 result = scipy.optimize.minimize(self.objective, self._coords_to_vector(self.mol.positions), jac=grad, callback=self.callback, constraints=self._make_constraints(), **self._optimize_kwargs) if self.mol.constraints: result = self._force_constraint_convergence(result) self.traj.info = result finalprops = self._calc_cache[tuple(result.x)] self.mol.positions = finalprops.positions self.mol.properties = finalprops def _force_constraint_convergence(self, result): """ Make sure that all constraints are satisfied, ramp up the constraint functions if not Note - if additional iterations are necessary, this will destroy the scipy optimize results object stored at self.traj.info. Not sure what to do about that """ import scipy.optimize for i in range(5): for constraint in self.mol.constraints: if not constraint.satisfied(): break else: return result print('Constraints not satisfied; raising penalties ...') self._constraint_multiplier *= 10.0 result = scipy.optimize.minimize(self.objective, self._coords_to_vector(self.mol.positions), jac=self.grad if self.gradtype=='analytical' else None, callback=self.callback, constraints=self._make_constraints(), **self._optimize_kwargs) return result def _make_constraints(self): from .. import geom constraints = [] for constraint in geom.get_base_constraints(self.mol.constraints): fun, jac = self._make_constraint_funs(constraint) constraints.append(dict(type='eq', fun=fun, jac=jac)) return constraints def _make_constraint_funs(self, const): def fun(v): self._sync_positions(v) return const.error().defunits_value() * self._constraint_multiplier def jac(v): self._sync_positions(v) return (const.gradient().defunits_value().reshape(self.mol.num_atoms*3) * self._constraint_multiplier) return fun, jac @exports class BFGS(ScipyMinimizer): _METHOD_NAME = 'bfgs' _TAKES_GTOL = True bfgs = BFGS._as_function('bfgs') exports(bfgs) toplevel(bfgs) @exports class SequentialLeastSquares(ScipyMinimizer): _METHOD_NAME = 'SLSQP' _TAKES_FTOL = True sequential_least_squares = SequentialLeastSquares._as_function('sequential_least_squares') exports(sequential_least_squares) toplevel(sequential_least_squares)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/min/descent.py
.py
5,961
153
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import moldesign as mdt from .. import units as u from ..utils import exports from .base import MinimizerBase from . import toplevel @exports class GradientDescent(MinimizerBase): """ A careful (perhaps overly careful) gradient descent implementation designed to relax structures far from equilibrium. A backtracking line search is performed along the steepest gradient direction. The maximum move for any single atom is also limited by ``max_atom_move`` Note: This algorithm is good at stably removing large forces, but it's very poorly suited to locating any type of critical point; don't use this to find a minimum! References: https://www.math.washington.edu/~burke/crs/408/lectures/L7-line-search.pdf Args: mol (moldesign.Molecule): molecule to minimize max_atom_move (Scalar[length]): maximum displacement of a single atom scaling (Scalar[length/force]): unit of displacement per unit force gamma (float): number between 0 and 1 indicating scale factor for backtracking search control (float): threshold for terminating line search; this is a proportion (0<=``control``<=1) of the expected function decrease **kwargs (dict): kwargs from :class:`MinimizerBase` """ _strip_units = False def __init__(self, mol, max_atom_move=0.05*u.angstrom, scaling=0.01*u.angstrom**2/u.eV, gamma=0.4, control=0.25, **kwargs): super().__init__(mol, **kwargs) assert 'forces' in self.request_list, 'Gradient descent requires built-in gradients' self.max_atom_move = max_atom_move self.scaling = scaling self.gamma = gamma self.control = control self._last_energy = None self._constraintlist = None def _run(self): print('Starting geometry optimization: built-in gradient descent') lastenergy = self.objective(self._coords_to_vector(self.mol.positions)) current = self._coords_to_vector(self.mol.positions) if self.mol.constraints: self._constraintlist = mdt.geom.get_base_constraints(self.mol.constraints) for i in range(self.nsteps): grad = self.grad(current) if np.abs(grad.max()) < self.force_tolerance: # converged return move = self.scale_move(grad) armijo_goldstein_prefac = self.control * move.norm() for icycle in range(0, 10): g = self.gamma**icycle newpos = self._make_move(current, g * move) # move direction may be different than gradient direction due to constraints move_vec = (newpos-current).normalized() if grad.dot(move_vec) >= 0.0: # move flipped direction! if self._constraint_convergence(newpos, current, grad): return # flip was because we're converged else: # flip was because move was too big newenergy = np.inf * u.default.energy continue try: newenergy = self.objective(newpos) except mdt.QMConvergenceError: continue if newenergy <= lastenergy + g * armijo_goldstein_prefac * grad.dot(move_vec): break else: if newenergy >= lastenergy: raise mdt.ConvergenceFailure('Line search failed') if self._constraint_convergence(newpos, current, grad): return else: current = newpos lastenergy = newenergy self._sync_positions(current) self.callback() def scale_move(self, grad): move = -self.scaling*grad mmax = np.abs(move).max() if mmax > self.max_atom_move: # rescale the move move *= self.max_atom_move/mmax return move def _make_move(self, current, move): if self.mol.constraints: # TODO: get constraint forces from lagrange multipliers and use them to check for convergence self._sync_positions(current) prev = self.mol.positions.copy() self._sync_positions(current+move) mdt.geom.shake_positions(self.mol, prev, constraints=self._constraintlist) return self._coords_to_vector(self.mol.positions) else: return current + move def _constraint_convergence(self, pos, lastpos, energygrad): """ Test for force-based convergence after projecting out constraint forces Until the shake method starts explicitly storing constraint forces, we calculate this direction as the SHAKE-adjusted displacement vector from the current descent step """ direction = mdt.mathutils.normalized((pos - lastpos).flatten()) proj_grad = energygrad.dot(direction) return abs(proj_grad) < self.force_tolerance gradient_descent = GradientDescent._as_function('gradient_descent') exports(gradient_descent) toplevel(gradient_descent)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/min/__init__.py
.py
159
10
def toplevel(o): __all__.append(o.__name__) return o __all__ = [] from . import base from .scipy import * from .descent import * from .smart import *
Python
3D
Autodesk/molecular-design-toolkit
moldesign/min/smart.py
.py
4,412
129
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .base import MinimizerBase from . import toplevel, BFGS, GradientDescent, SequentialLeastSquares from moldesign import utils from moldesign import units as u from moldesign.utils import exports GDTHRESH = 1.5*u.eV/u.angstrom @exports class SmartMin(MinimizerBase): """ Uses gradient descent until forces fall below a threshold, then switches to BFGS (unconstrained) or SLSQP (constrained). Args: gd_threshold (u.Scalar[force]): Use gradient descent if there are any forces larger than this; use an approximate hessian method (BFGS or SLSQP) otherwise Note: Not really that smart. """ # TODO: use non-gradient methods if forces aren't available _strip_units = True @utils.args_from(MinimizerBase, inject_kwargs={'gd_threshold': GDTHRESH}) def __init__(self, *args, **kwargs): self.gd_threshold = kwargs.pop('gd_threshold', GDTHRESH) self.args = args self.kwargs = kwargs self._spmin = None self._descent = None self._traj = None self._currentstep = None self.__foundmin = None super().__init__(*args, **kwargs) def _run(self): # If forces are already low, go directly to the quadratic convergence methods and return forces = self.mol.calculate_forces() if abs(forces).max() <= self.gd_threshold: self._spmin = self._make_quadratic_method() self._spmin.traj = self.traj self._spmin._run() return # Otherwise, remove large forces with gradient descent; exit if we pass the cycle limit descent_kwargs = self.kwargs.copy() descent_kwargs['force_tolerance'] = self.gd_threshold self._descender = GradientDescent(*self.args, **descent_kwargs) self._descender._run() if self._descender.current_step >= self.nsteps: self.traj = self._descender.traj return # Finally, use a quadratic method to converge the optimization kwargs = dict(_restart_from=self._descender.current_step, _restart_energy=self._descender._initial_energy) kwargs['frame_interval'] = self.kwargs.get('frame_interval', self._descender.frame_interval) self._spmin = self._make_quadratic_method(kwargs) self._spmin.current_step = self.current_step self._spmin._foundmin = self._foundmin self._spmin._run() self.traj = self._descender.traj + self._spmin.traj self.traj.info = getattr(self._spmin, 'info', None) @property def _foundmin(self): if self._descent: return self._descent._foundmin elif self._spmin: return self._spmin._foundmin else: return self.__foundmin @_foundmin.setter def _foundmin(self, val): self.__foundmin = val @property def currentstep(self): if self._descent: return self._descent.currentstep elif self._spmin: return self._spmin.currentstep else: return self._currentstep @currentstep.setter def currentstep(self, val): self._currentstep = val def _make_quadratic_method(self, kwargs=None): if kwargs is None: kwargs = {} kw = self.kwargs.copy() kw.update(kwargs) if self.mol.constraints: spmin = SequentialLeastSquares(*self.args, **kw) else: spmin = BFGS(*self.args, **kw) return spmin minimize = SmartMin._as_function('minimize') exports(minimize) toplevel(minimize)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/min/base.py
.py
8,600
227
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import numpy as np import moldesign as mdt from .. import data from .. import units as u class MinimizerBase(object): _strip_units = True # callbacks expect and return dimensionless quantities scaled to default unit system def __init__(self, mol, nsteps=20, force_tolerance=data.DEFAULT_FORCE_TOLERANCE, frame_interval=None, _restart_from=0, _restart_energy=None): self.mol = mol self.nsteps = nsteps - _restart_from self.force_tolerance = force_tolerance self.frame_interval = mdt.utils.if_not_none(frame_interval, max(nsteps/10, 1)) self._restart_from = _restart_from self._foundmin = None self._calc_cache = {} # Set up the trajectory to track the minimization self.traj = mdt.Trajectory(mol) self.current_step = _restart_from if _restart_energy is None: self.traj.new_frame(minimization_step=0, annotation='minimization steps:%d (energy=%s)' % (0, mol.calc_potential_energy())) self._initial_energy = _restart_energy self._last_energy = None self._last_grad = None # Figure out whether we'll use gradients self.request_list = ['potential_energy'] if 'forces' in mol.energy_model.ALL_PROPERTIES: self.gradtype = 'analytical' self.request_list.append('forces') else: self.gradtype = 'approximate' assert len(mol.constraints) == 0, \ 'Constrained minimization only available with analytical gradients' def _sync_positions(self, vector): """ Set the molecule's position """ c = vector.reshape((self.mol.num_atoms, 3)) if self._strip_units: self.mol.positions = c*u.default.length else: self.mol.positions = c def _coords_to_vector(self, coords): """ Convert position array to a flat vector """ vec = coords.reshape(self.mol.num_atoms * 3).copy() if self._strip_units: return vec.magnitude else: return vec def objective(self, vector): """ Callback function to calculate the objective function """ self._sync_positions(vector) try: self.mol.calculate(requests=self.request_list) except mdt.QMConvergenceError: # returning infinity can help rescue some line searches return np.inf self._cachemin() self._calc_cache[tuple(vector)] = self.mol.properties pot = self.mol.potential_energy if self._initial_energy is None: self._initial_energy = pot self._last_energy = pot if self._strip_units: return pot.defunits().magnitude else: return pot.defunits() def grad(self, vector): """ Callback function to calculate the objective's gradient """ self._sync_positions(vector) self.mol.calculate(requests=self.request_list) self._cachemin() self._calc_cache[tuple(vector)] = self.mol.properties grad = -self.mol.forces grad = grad.reshape(self.mol.num_atoms * 3) self._last_grad = grad if self._strip_units: return grad.defunits().magnitude else: return grad.defunits() def _cachemin(self): """ Caches the minimum potential energy properties so we can return them when the calculation is done. Underlying implementations can use this or not - it may not be valid if constraints are present """ if self._foundmin is None or self.mol.potential_energy < self._foundmin.potential_energy: self._foundmin = self.mol.properties def __call__(self, remote=False, wait=True): """ Run the minimization Args: remote (bool): launch the minimization in a remote job wait (bool): if remote, wait until the minimization completes before returning. (if remote=True and wait=False, will return a reference to the job) Returns: moldesign.Trajectory: the minimization trajectory """ if hasattr(self.mol.energy_model, '_PKG') and self.mol.energy_model._PKG.force_remote: remote = True if remote: return self.runremotely(wait=wait) self._run() # Write the last step to the trajectory, if needed if self.traj.potential_energy[-1] != self.mol.potential_energy: assert self.traj.potential_energy[-1] > self.mol.potential_energy self.traj.new_frame(minimization_step=self.current_step, annotation='minimization result (%d steps) (energy=%s)'% (self.current_step, self.mol.potential_energy)) return self.traj def runremotely(self, wait=True): """ Execute this minimization in a remote process Args: wait (bool): if True, block until the minimization is complete. Otherwise, return a ``pyccc.PythonJob`` object """ return mdt.compute.runremotely(self.__call__, wait=wait, jobname='%s: %s' % (self.__class__.__name__, self.mol.name), when_finished=self._finishremoterun) def _finishremoterun(self, job): traj = job.function_result self.mol.positions = traj.positions[-1] self.mol.properties.update(traj.frames[-1]) return traj def _run(self): raise NotImplementedError('This is an abstract base class') def callback(self, *args): """ To be called after each minimization step Args: *args: ignored """ self.current_step += 1 if self.current_step % self.frame_interval != 0: return self.mol.calculate(self.request_list) self.traj.new_frame(minimization_step=self.current_step, annotation='minimization steps:%d (energy=%s)'% (self.current_step, self.mol.potential_energy)) if self.nsteps is None: message = ['Minimization step %d' % self.current_step] else: message = ['Step %d/%d' % (self.current_step, self.nsteps + self._restart_from)] if self._last_energy is not None: message.append(u'\u0394E={x.magnitude:.3e} {x.units}'.format( x=self._last_energy - self._initial_energy)) if self.gradtype == 'analytical' and self._last_grad is not None: force = self._last_grad message.append(u'RMS \u2207E={rmsf.magnitude:.3e}, ' u'max \u2207E={mf.magnitude:.3e} {mf.units}'.format( rmsf=np.sqrt(force.dot(force) / self.mol.ndims), mf=np.abs(force).max())) if self.mol.constraints: nsatisfied = 0 for c in self.mol.constraints: if c.satisfied(): nsatisfied += 1 message.append('constraints:%d/%d' % (nsatisfied, len(self.mol.constraints))) print(', '.join(message)) sys.stdout.flush() @classmethod def _as_function(cls, newname): """ Create a function that runs this minimization """ @mdt.utils.args_from(cls, allexcept=['self']) def asfn(*args, **kwargs): remote = kwargs.pop('remote', False) wait = kwargs.pop('wait', True) obj = cls(*args, **kwargs) return obj(remote=remote, wait=wait) asfn.__name__ = newname asfn.__doc__ = cls.__doc__ return asfn
Python
3D
Autodesk/molecular-design-toolkit
moldesign/models/amber.py
.py
2,282
63
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import moldesign as mdt from ..parameters import Parameter, WhenParam from ..utils import exports from . import ForceField @exports class GaffSmallMolecule(ForceField): """ Model the energy using the GAFF forcefield This is implemented as a special case of the ForceField energy model; it automates small parameterization process """ # TODO: mechanism to store partial charges so they don't need to be constantly recomputed PARAMETERS = [Parameter('partial_charges', 'Partial charge model', type=str, default='am1-bcc', choices=['am1-bcc', 'gasteiger', 'esp']), Parameter('gaff_version', 'GAFF version', type=str, choices='gaff gaff2'.split(), default='gaff2') ] + ForceField.PARAMETERS def prep(self, force=False): self._parameterize() return super().prep() def calculate(self, requests=None): if not self._prepped: self._parameterize() return super().calculate(requests=requests) def _parameterize(self): if not self.mol.ff: params = mdt.create_ff_parameters(self.mol, charges=self.params.partial_charges, baseff=self.params.gaff_version) params.assign(self.mol)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/models/models.py
.py
2,349
80
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TODO: look into http://molmod.github.io/ """ "Generic" energy models - models that can be specified directly by name, without worrying about which specific implementation is used. Currently, everything here is an alias. However, more complicated logic (including runtime dispatch) may be used to determine the best implementation in a given situation """ from moldesign import utils from . import PySCFPotential from . import OpenMMPotential ################## # ForceField @utils.exports class ForceField(OpenMMPotential): pass # currently an alias ################## # QM generics @utils.exports class RHF(PySCFPotential): @utils.doc_inherit def __init__(self, *args, **kwargs): kwargs['theory'] = 'rhf' super(RHF, self).__init__(*args, **kwargs) @utils.exports class DFT(PySCFPotential): @utils.doc_inherit def __init__(self, *args, **kwargs): kwargs['theory'] = 'rks' super(DFT, self).__init__(*args, **kwargs) @utils.exports class B3LYP(PySCFPotential): @utils.doc_inherit def __init__(self, *args, **kwargs): kwargs['theory'] = 'rks' kwargs['functional'] = 'b3lyp' super(B3LYP, self).__init__(*args, **kwargs) @utils.exports class MP2(PySCFPotential): @utils.doc_inherit def __init__(self, *args, **kwargs): kwargs['theory'] = 'mp2' super(MP2, self).__init__(*args, **kwargs) @utils.exports class CASSCF(PySCFPotential): @utils.doc_inherit def __init__(self, *args, **kwargs): kwargs['theory'] = 'casscf' super(CASSCF, self).__init__(*args, **kwargs)
Python
3D
Autodesk/molecular-design-toolkit
moldesign/models/nwchem.py
.py
6,978
175
# Copyright 2016 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import json import numpy as np import pyccc import moldesign as mdt from moldesign.utils import exports from moldesign import units as u from .base import QMBase, QMMMBase from .jsonmodel import JsonModelBase @exports class NWChemQM(JsonModelBase, QMBase): """ Interface with NWChem package (QM only) Note: This is the first interface based on our new wrapping strategy. This is slightly hacked, but has the potential to become very general; very few things here are NWChem-specific """ IMAGE = 'nwchem' MODELNAME = 'nwchem' DEFAULT_PROPERTIES = ['potential_energy'] ALL_PROPERTIES = DEFAULT_PROPERTIES + 'forces dipole esp'.split() def _get_inputfiles(self): return {'input.xyz': self.mol.write(format='xyz')} def write_constraints(self, parameters): parameters['constraints'] = [] for constraint in self.mol.constraints: if not constraint.satisfied(): # TODO: factor this out into NWChem subclass raise ValueError('Constraints must be satisfied before passing to NWChem %s' % constraint) cjson = {'type': constraint['desc'], 'value': constraint['value'].to_json()} if cjson['type'] == 'position': cjson['atomIdx'] = constraint.atom.index elif cjson['type'] == 'distance': cjson['atomIdx1'] = constraint.a1.index cjson['atomIdx2'] = constraint.a2.index @exports class NWChemQMMM(NWChemQM): """ Interface with NWChem package for QM/MM only. Note that this is currently only set up for optimizations, and only of the QM geometry - the MM region cannot move. """ IMAGE = 'nwchem' MODELNAME = 'nwchem_qmmmm' DEFAULT_PROPERTIES = ['potential_energy', 'forces', 'esp'] ALL_PROPERTIES = DEFAULT_PROPERTIES RUNNER = 'runqmmm.py' PARSER = 'getresults.py' PARAMETERS = NWChemQM.PARAMETERS + [mdt.parameters.Parameter('qm_atom_indices')] def _get_inputfiles(self): crdparamfile = self._makecrdparamfile() return {'nwchem.crdparams': crdparamfile} def _makecrdparamfile(self, include_mmterms=True): pmdparms = self.mol.ff.parmed_obj lines = ['qm'] qmatom_idxes = set(self.params.qm_atom_indices) def crosses_boundary(*atoms): total = 0 inqm = 0 for atom in atoms: total += 1 if atom.idx in qmatom_idxes: inqm += 1 return inqm != 0 and inqm < total # write QM atoms for atomidx in sorted(self.params.qm_atom_indices): atom = self.mol.atoms[atomidx] x, y, z = atom.position.value_in(u.angstrom) lines.append(' %d %s %24.14f %24.14f %24.14f' % (atom.index+1, atom.element, x, y, z)) qmatom_idxes.add(atom.index) # write MM atoms lines.append('end\n\nmm') for atom, patm in zip(self.mol.atoms, pmdparms.atoms): assert atom.index == patm.idx assert atom.atnum == patm.element x, y, z = atom.position.value_in(u.angstrom) if atom.index not in qmatom_idxes: lines.append(' %d %s %24.14f %24.14f %24.14f %24.14f' %(atom.index+1, atom.element, x, y, z, patm.charge)) lines.append('end\n\nbond\n# i j k_ij r0') if include_mmterms: for term in pmdparms.bonds: if crosses_boundary(term.atom1, term.atom2): lines.append(' %d %d %20.10f %20.10f' % (term.atom1.idx+1, term.atom2.idx+1, term.type.k, term.type.req)) lines.append('end\n\nangle\n# i j k k_ijk theta0') if include_mmterms: for term in pmdparms.angles: if crosses_boundary(term.atom1, term.atom2, term.atom3): lines.append(' %d %d %d %20.10f %20.10f' % (term.atom1.idx+1, term.atom2.idx+1, term.atom3.idx+1, term.type.k, term.type.theteq)) lines.append('end\n\ndihedral\n' '# i j k l k_ijkl periodicity phase') if include_mmterms: for term in pmdparms.dihedrals: if crosses_boundary(term.atom1, term.atom2, term.atom3, term.atom4): lines.append(' %d %d %d %d %20.10f %d %20.10f' % (term.atom1.idx+1, term.atom2.idx+1, term.atom3.idx+1, term.atom4.idx+1, term.type.phi_k, term.type.per, term.type.phase)) lines.append('end\n\nvdw\n' '# i j A_coeff B_coeff') if include_mmterms: for atom1idx, atom2 in itertools.product(qmatom_idxes, pmdparms.atoms): if atom2.idx in qmatom_idxes: continue atom1 = pmdparms.atoms[atom1idx] epsilon = np.sqrt(atom1.epsilon * atom2.epsilon) if epsilon == 0: continue sigma = (atom1.sigma + atom2.sigma) / 2.0 lj_a = 4.0 * epsilon * sigma**12 lj_b = 4.0 * epsilon * sigma**6 lines.append(' %d %d %20.10e %20.10e' % (atom1.idx+1, atom2.idx+1, lj_a, lj_b)) lines.append('end\n\nscaled_vdw\n' '# i j A_coeff B_coeff one_scnb') # TODO: this part lines.append('end') return pyccc.files.StringContainer('\n'.join(lines)) def finish_min(self, job): traj = mdt.Trajectory(self.mol) traj.new_frame() results = json.loads(job.get_output('results.json').read()) new_state = self._json_to_quantities(results['states'][0]) for iatom in sorted(self.params.qm_indices): for position in new_state['positions']: self.mol.atoms[iatom].position = position properties = self._process_results(results) properties.positions = self.mol.positions self.mol.properties = properties traj.new_frame() return traj
Python
3D
Autodesk/molecular-design-toolkit
moldesign/models/jsonmodel.py
.py
6,004
167
# Copyright 2016 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import pyccc import moldesign as mdt from .. import units as u from .base import EnergyModelBase class JsonModelBase(EnergyModelBase): """ Abstract energy model interface using JSON inputs and outputs """ IMAGE = None # base name of the docker image MODELNAME = 'abstract model' RUNNER = 'run.py' PARSER = 'getresults.py' def prep(self): parameters = self.params.copy() parameters['constraints'] = [] for constraint in self.mol.constraints: self._handle_constraint(constraint) parameters['charge'] = self.mol.charge.value_in(u.q_e) self._jobparams = parameters self._prepped = True def calculate(self, requests=None): if requests is None: requests = self.DEFAULT_PROPERTIES job = self._make_calculation_job(requests) return mdt.compute.run_job(job, _return_result=True) def _handle_constraint(self, constraint): raise NotImplementedError() def _make_calculation_job(self, requests=None): params, inputfiles = self._prep_calculation(requests) inputfiles['params.json'] = mdt.utils.json_dumps(dict(params)) job = pyccc.Job(image=mdt.compute.get_image_path(self.IMAGE), command='%s && %s' % (self.RUNNER, self.PARSER), inputs=inputfiles, when_finished=self.finish, name='%s/%s' % (self.MODELNAME, self.mol.name)) return job def _prep_calculation(self, requests): self.prep() parameters = self._jobparams.copy() parameters['runType'] = 'singlePoint' parameters['properties'] = list(requests) if self.mol.constraints: self.write_constraints(parameters) inputfiles = self._get_inputfiles() return parameters, inputfiles def finish(self, job): results = json.loads(job.get_output('results.json').read()) return self._process_results(results) def _process_results(self, results): assert len(results['states']) == 1 jsonprops = results['states'][0]['calculated'] if 'orbitals' in jsonprops: wfn = self._make_wfn(results['states'][0]) else: wfn = None result = mdt.MolecularProperties(self.mol, **self._json_to_quantities(jsonprops)) if wfn: result['wfn'] = wfn return result def _make_wfn(self, state): from moldesign import orbitals try: basis_fns = state['calculated']['method']['aobasis'] except KeyError: basis_set = None else: bfs = [orbitals.AtomicBasisFunction(**bdata) for bdata in basis_fns] basis_set = orbitals.BasisSet(self.mol, orbitals=bfs, name=self.params.basis) wfn = orbitals.ElectronicWfn(self.mol, self.mol.num_electrons, aobasis=basis_set) for setname, orbdata in state['calculated']['orbitals'].items(): orbs = [] for iorb in range(len(orbdata['coefficients'])): orbs.append(orbitals.Orbital(orbdata['coefficients'][iorb])) if 'occupations' in orbs: orbs[-1].occupation = orbdata['occupations'][iorb] wfn.add_orbitals(orbs, orbtype=setname) return wfn @staticmethod def _json_to_quantities(jsonprops): # TODO: handle this within JSON decoder props = {} for name, property in jsonprops.items(): if isinstance(property, dict) and len(property) == 2 and \ 'units' in property and 'value' in property: props[name] = property['value'] * u.ureg(property['units']) else: props[name] = property return props def _get_inputfiles(self): """ Override this method to pass additional input files to the program """ return {} def minimize(self, nsteps=None): job = self._make_minimization_job(nsteps) return mdt.compute.run_job(job, _return_result=True) def _make_minimization_job(self, nsteps): params, inputfiles = self._prep_calculation([self.DEFAULT_PROPERTIES]) params['runType'] = 'minimization' if nsteps is not None: params['minimization_steps'] = 100 inputfiles['params.json'] = mdt.utils.json_dumps(dict(params)) job = pyccc.Job(image=mdt.compute.get_image_path(self.IMAGE), command='%s && %s' % (self.RUNNER, self.PARSER), inputs=inputfiles, when_finished=self.finish_min, name='%s/%s' % (self.MODELNAME, self.mol.name)) return job def finish_min(self, job): # TODO: parse more data than just the final minimization state traj = mdt.Trajectory(self.mol) traj.new_frame() results = json.loads(job.get_output('results.json').read()) new_state = self._json_to_quantities(results['states'][0]) self.mol.positions = new_state['positions'] self.mol.properties = self._process_results(results) traj.new_frame() return traj
Python
3D
Autodesk/molecular-design-toolkit
moldesign/models/qmmm.py
.py
8,032
208
# Copyright 2016 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import moldesign as mdt from ..molecules import MolecularProperties from ..utils import exports from .base import QMMMBase class QMMMEmbeddingBase(QMMMBase): """ Abstract class for standard QM/MM embedding models. To use any of this classes' subclasses, the MM models must support the ability to calculate the internal energies and interaction energies between subsystems, using the ``calculation_groups`` parameter. """ def __init__(self, *args, **kwargs): super(QMMMEmbeddingBase, self).__init__(*args, **kwargs) self.qmmol = None self.mmmol = None self.qm_atoms = None self.qm_link_atoms = None self._qm_index_set = None # TODO: add `qm_atom_indices` to QMMMBase parameters def calculate(self, requests): self.prep() self.mmmol.positions = self.mol.positions self._set_qm_positions() qmprops = self.qmmol.calculate(requests) mmprops = self.mmmol.calculate(requests) potential_energy = mmprops.potential_energy+qmprops.potential_energy forces = mmprops.forces.copy() for iatom, realatom in enumerate(self.qm_atoms): forces[realatom.index] = qmprops.forces[iatom] for atom in self.qm_link_atoms: self._distribute_linkatom_forces(forces, atom) properties = MolecularProperties(self.mol, mmprops=mmprops, qmprops=qmprops, potential_energy=potential_energy, forces=forces) if 'wfn' in qmprops: properties.wfn = qmprops.wfn return properties def prep(self): if self._prepped: return None self.params.qm_atom_indices.sort() self.qm_atoms = [self.mol.atoms[idx] for idx in self.params.qm_atom_indices] self._qm_index_set = set(self.params.qm_atom_indices) self.qmmol = self._setup_qm_subsystem() self.mmmol = mdt.Molecule(self.mol, name='%s MM subsystem' % self.mol.name) self.mol.ff.copy_to(self.mmmol) self._turn_off_qm_forcefield(self.mmmol.ff) self.mmmol.set_energy_model(self.params.mm_model) self._prepped = True return True def _setup_qm_subsystem(self): raise NotImplemented("%s is an abstract class, use one of its subclasses" % self.__class__.__name__) def _turn_off_qm_forcefield(self, ff): self._remove_internal_qm_bonds(ff.parmed_obj) self._exclude_internal_qm_ljterms(ff.parmed_obj) def _exclude_internal_qm_ljterms(self, pmdobj): # Turn off QM/QM LJ interactions (must be done AFTER _remove_internal_qm_bonds) numqm = len(self.params.qm_atom_indices) for i in range(numqm): for j in range(i+1, numqm): pmdobj.atoms[i].exclude(pmdobj.atoms[j]) def _remove_internal_qm_bonds(self, pmdobj): for i, iatom in enumerate(self.params.qm_atom_indices): pmdatom = pmdobj.atoms[iatom] allterms = ((pmdatom.bonds, 2), (pmdatom.angles, 3), (pmdatom.dihedrals, 4), (pmdatom.impropers, 4)) for termlist, numatoms in allterms: for term in termlist[:]: # make a copy so it doesn't change during iteration if self._term_in_qm_system(term, numatoms): term.delete() @staticmethod def _distribute_linkatom_forces(fullforces, linkatom): """ Distribute forces according to the apparently indescribable and unciteable "lever rule" """ # TODO: CHECK THIS!!!! mmatom = linkatom.metadata.mmatom qmatom = linkatom.metadata.mmpartner dfull = mmatom.distance(qmatom) d_mm = linkatom.distance(mmatom) p = (dfull - d_mm)/dfull fullforces[qmatom.index] += p*linkatom.force fullforces[mmatom.index] += (1.0-p) * linkatom.force def _set_qm_positions(self): for qmatom, realatom in zip(self.qmmol.atoms, self.qm_atoms): qmatom.position = realatom.position mdt.helpers.qmmm.set_link_atom_positions(self.qm_link_atoms) def _term_in_qm_system(self, t, numatoms): """ Check if an FF term is entirely within the QM subsystem """ for iatom in range(numatoms): attrname = 'atom%i' % (iatom + 1) if not getattr(t, attrname).idx in self._qm_index_set: return True else: return False @exports class MechanicalEmbeddingQMMM(QMMMEmbeddingBase): """ Handles _non-covalent_ QM/MM with mechanical embedding. No electrostatic interactions will be calculated between the QM and MM subsystems. No covalent bonds are are allowed between the two susbystems. """ def prep(self): if not super(MechanicalEmbeddingQMMM, self).prep(): return # was already prepped # Set QM partial charges to 0 self.mmmol.energy_model._prepped = False pmdobj = self.mmmol.ff.parmed_obj for i, iatom in enumerate(self.params.qm_atom_indices): pmdatom = pmdobj.atoms[iatom] pmdatom.charge = 0.0 def _setup_qm_subsystem(self): """ QM subsystem for mechanical embedding is the QM atoms + any link atoms """ qm_atoms = [self.mol.atoms[iatom] for iatom in self.params.qm_atom_indices] self.qm_link_atoms = mdt.helpers.qmmm.create_link_atoms(self.mol, qm_atoms) qmmol = mdt.Molecule(qm_atoms + self.qm_link_atoms, name='%s QM subsystem' % self.mol.name) for real_atom, qm_atom in zip(self.qm_atoms, qmmol.atoms): qm_atom.metadata.real_atom = real_atom qmmol.set_energy_model(self.params.qm_model) return qmmol @exports class ElectrostaticEmbeddingQMMM(QMMMEmbeddingBase): """ Handles _non-covalent_ QM/MM with electrostaic embedding. No bonds allowed across the QM/MM boundaries. To support this calculation type, the QM model must support the ability to denote a subset of atoms as the "QM" atoms, using the ``qm_atom_indices`` parameter. To support this calculation type, the QM model must support the ability to denote a subset of atoms as the "QM" atoms, using the ``qm_atom_indices`` parameter. The MM models must support the ability to turn of _internal_ interactions for a certain subset of the system, using the ``no_internal_calculations`` parameter. """ def prep(self): if not super(ElectrostaticEmbeddingQMMM, self).prep(): return # was already prepped if not self.params.qm_model.supports_parameter('qm_atom_indices'): raise TypeError('Supplied QM model ("%s") does not support QM/MM' % self.params.qm_model.__name__) def _setup_qm_subsystem(self): qmmol = mdt.Molecule(self.mol) self.mol.ff.copy_to(qmmol) self.qm_link_atoms = mdt.helpers.qmmm.create_link_atoms(self.mol, self.qm_atoms) if self.qm_link_atoms: raise ValueError('The %s model does not support link atoms' % self.__class__.__name__) qmmol.set_energy_model(self.params.qm_model) qmmol.energy_model.params.qm_atom_indices = self.params.qm_atom_indices return qmmol
Python
3D
Autodesk/molecular-design-toolkit
moldesign/models/__init__.py
.py
172
8
from .openmm import * from .pyscf import * from .models import * from .toys import * from .amber import * from .openbabel import * from .nwchem import * from .qmmm import *
Python