├── README.md ├── params.ini ├── params.py ├── lepsmove.py ├── lepspoint.py ├── lepsplots.py ├── lepsgui.py └── LICENSE.txt /README.md: -------------------------------------------------------------------------------- 1 | # LepsPy: A Molecular Reaction Dynamics Demonstration 2 | A program to perform classical molecular reaction dynamics for a tri-atomic system using a London-Eyring-Polanyi-Sato (LEPS) potential parameterised for several atoms. 3 | 4 | The first Python version of the code was written by Tristan Mackenzie, based on a Matlab version written by Lee Thompson, which in tern built upon a Fortran code written by Barry Smith. 5 | 6 | ### Running the program 7 | 8 | Python 3.5 or higher is needed to run the program. 9 | 10 | Click on the **Clone or download** button to the right and download the zip archive with all the progeam files. You need to unpack the folder before you can run the program. 11 | 12 | The program is run through a graphical user interface (GUI) which is started by running the file **lepsgui.py**. 13 | 14 | #### On Windows 15 | 16 | Double click on the **lepsgui.py** file to start the GUI. 17 | 18 | #### On Linux and OSX 19 | 20 | In a terminal, change directory to the LepsPy directory and execute "python lepsgui.py". 21 | 22 | 23 | ### Files 24 | 25 | #### [lepsgui.py](./lepsgui.py) 26 | 27 | This is the main program. lepsgui generates the GUI, and drives the calculations. 28 | 29 | #### [params.ini](./params.ini) 30 | 31 | params.ini contains the parameter sets for a number of atom combinations. New atoms and parameters can be added to the program here. 32 | 33 | #### [params.py](./params.py) 34 | 35 | params.py reads params.ini and passes parameters to the lepsgui. 36 | 37 | #### [lepspoint.py](./lepspoint.py) 38 | 39 | lepspoint calculations the energy, first and second energy derivatives for any point on the surface. 40 | 41 | #### [lepsmove.py](./lepsmove.py) 42 | 43 | This file contains several functions related to the displacement of the system and its dynamic state. 44 | 45 | 46 | #### [lepsplots.py](./lepsplots.py) 47 | 48 | This file contains the functions that plot the results of the simulation. 49 | -------------------------------------------------------------------------------- /params.ini: -------------------------------------------------------------------------------- 1 | #Author: Tristan Mackenzie 2 | # 3 | # This file is part of LepsPy. 4 | # 5 | # LepsPy is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # LepsPy is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with LepsPy. If not, see . 17 | 18 | # This file contains default options of the simulations, and parameters 19 | # for different atoms that can be simulated. To add new atoms, this is 20 | # the only file that needs to be edited. 21 | 22 | [defaults] 23 | # default values to use for Interactive class 24 | # Sato parameter for the potential: 0.18 is the original value JCP 23:2465 (1955) 25 | sato= 0.18 26 | 27 | [atoms] 28 | # Use this section to add atoms 29 | # key = [mass/g.mol^{-1}, VdW/pm, colour] 30 | H=1.0 , 120, cccccc 31 | D=2.0 , 120, c0c0c0 32 | F=19.0 , 147, ffdd00 33 | Cl=35.457, 175, 32d600 34 | I=126.91, 198, de00a0 35 | O=16.0 , 152, ff0000 36 | 37 | [isotopes] 38 | # Use this section to set isotopes that have the 39 | # same potential parameters but different masses 40 | D=H 41 | 42 | [morse] 43 | # Two-body Morse Parameters 44 | # Dr12 : Dissociation energy (in kJ.mol^{-1}) 45 | # Brab : Morse Parameter (in pm^{-1}) 46 | # lr12 : Equilibrium bond-length (in pm) 47 | # Dr12 , Br12, lr12 48 | HH= 435.1, 0.0199, 74 49 | HF= 560.7, 0.0227, 92 50 | FH= 560.7, 0.0227, 92 51 | HCl= 445.6, 0.0185, 128 52 | ClH= 445.6, 0.0185, 128 53 | FF= 150.6, 0.0160, 142 54 | FCl= 2083.6, 0.0212, 163 55 | ClF= 2083.6, 0.0212, 163 56 | ClCl= 242.7, 0.0203, 199 57 | HI= 309.6, 0.0175, 160 58 | IH= 309.6, 0.0175, 160 59 | II= 150.6, 0.0185, 267 60 | HO= 426.8, 0.0226, 96 61 | OH= 426.8, 0.0226, 96 62 | OO= 221.8, 0.0232, 132 63 | 64 | [limits] 65 | # Plot limits (in pm) 66 | # mina, maxa, minb, maxb 67 | HHH=40, 250, 40, 250 68 | HHF=40, 250, 50, 250 69 | FHH=50, 250, 40, 250 70 | HFH=55, 350, 55, 350 71 | FFH=80, 350, 50, 400 72 | HFF=50, 400, 80, 350 73 | FHF=55, 350, 55, 350 74 | FFF=95, 400, 95, 400 75 | ClHH=90, 400, 35, 350 76 | HHCl=35, 350, 90, 400 77 | HClH=85, 350, 85, 350 78 | HClCl=80, 350, 160, 450 79 | ClClH=160, 450, 80, 350 80 | ClHCl=90, 450, 90, 450 81 | FFCl=60, 350, 120, 550 82 | ClFF=120, 550, 60, 550 83 | FClF=130, 450, 130, 450 84 | ClClF=145, 350, 120, 450 85 | FClCl=120, 450, 145, 350 86 | ClFCl=130, 350, 130, 350 87 | ClClCl=160, 460, 160, 460 88 | HFCl=60, 300, 130, 450 89 | ClFH=130, 450, 60, 300 90 | FHCl=50, 350, 75, 350 91 | ClHF=75, 350, 50, 350 92 | HClF=80, 350, 130, 450 93 | FClH=130, 450, 80, 350 94 | HHI=40, 450, 120, 450 95 | IHH=120, 450, 40, 450 96 | HIH=120, 450, 120, 450 97 | HII=120, 400, 230, 500 98 | IIH=230, 500, 120, 400 99 | IHI=120, 400, 120, 400 100 | III=230, 550, 230, 550 101 | HHO=40, 350, 65, 350 102 | OHH=65, 350, 40, 350 103 | HOH=65, 350, 65, 350 104 | HOO=100, 350, 65, 350 105 | OOH=100, 350, 65, 350 106 | OHO=65, 350, 65, 350 107 | OOO=100, 350, 100, 350 108 | 109 | -------------------------------------------------------------------------------- /params.py: -------------------------------------------------------------------------------- 1 | #Created on Wed May 17 11:30:28 2017 2 | # 3 | #@author: Tristan Mackenzie 4 | # 5 | # This file is part of LepsPy. 6 | # 7 | # LepsPy is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # LepsPy is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with LepsPy. If not, see . 19 | 20 | 21 | from configparser import ConfigParser 22 | import numpy as np 23 | 24 | def _get_mass(config, key): 25 | '''Get the mass of a given atom from the config file.''' 26 | 27 | try: 28 | d = config['atoms'] 29 | l = d[key] 30 | m = float(l.split(',')[0]) 31 | except KeyError: 32 | raise KeyError('Mass not available for atom type {}'.format(key)) 33 | except: 34 | raise RuntimeError('Parameter file corrupted. Cannot get mass for atom type {}'.format(key)) 35 | 36 | return m 37 | 38 | def _get_morse(config, key): 39 | '''Gets parameters for a Morse potential from a config file for a given 40 | combination of 2 atoms.''' 41 | 42 | try: 43 | d = config['morse'] 44 | m = d[key] 45 | params = [float(p) for p in m.split(',')] 46 | assert len(params) == 3 47 | except KeyError: 48 | raise KeyError('Morse potential not available for atom pair {}'.format(key)) 49 | except: 50 | raise RuntimeError('Parameter file corrupted. Cannot get morse parater for atom pair {}'.format(key)) 51 | 52 | return params 53 | 54 | def _get_limits(config, key): 55 | '''Gets plot limits from config file a a given combination of 3 atoms.''' 56 | 57 | try: 58 | d = config['limits'] 59 | l = d[key] 60 | limits = [float(p) for p in l.split(',')] 61 | assert len(limits) == 4 62 | except KeyError: 63 | raise KeyError('Limits not available for atoms {}'.format(key)) 64 | except: 65 | raise RuntimeError('Parameter file corrupted. Cannot get morse parater for atom pair {}'.format(key)) 66 | 67 | return limits 68 | 69 | def params(a,b,c): 70 | '''Gets the parameters for any atom set or returns error message if no 71 | parameters exist.''' 72 | 73 | #Open parameter file 74 | config = ConfigParser(inline_comment_prefixes=(';', '#')) 75 | #The line below allows for dictionary keys with capital letters 76 | config.optionxform = lambda op:op 77 | config.read('params.ini') 78 | try: 79 | isotopes = config['isotopes'] 80 | except: 81 | isotopes = {} 82 | 83 | ab = (a + b) 84 | bc = (b + c) 85 | ac = (a + c) 86 | abc = (a + b + c) 87 | 88 | #Replace atoms set by the isotopes section in parameters file 89 | for i, o in isotopes.items(): 90 | ab = ab.replace(i, o) 91 | bc = bc.replace(i, o) 92 | ac = ac.replace(i, o) 93 | abc = abc.replace(i, o) 94 | 95 | # Masses 96 | masses = np.array([_get_mass(config, a),_get_mass(config, b),_get_mass(config, c)]) 97 | 98 | 99 | # Morse Parameters 100 | morse_params = np.array([_get_morse(config, ab), 101 | _get_morse(config, bc), 102 | _get_morse(config, ac)]) 103 | 104 | # Plot Limits 105 | plot_limits = np.reshape(np.array(_get_limits(config, abc)),(2,2)) 106 | 107 | return (masses,morse_params,plot_limits) 108 | -------------------------------------------------------------------------------- /lepsmove.py: -------------------------------------------------------------------------------- 1 | #@author: Tristan Mackenzie 2 | # 3 | # This file is part of LepsPy. 4 | # 5 | # LepsPy is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # LepsPy is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with LepsPy. If not, see . 17 | 18 | 19 | # There are problems with energy conservation when theta is not 180 degrees. 20 | # This might be due to energy transfer into/from rotational motion which is 21 | # not properly described in this treatment (no Coriolis coupling). 22 | # The variation in total energy seems significant, so a bug is not to be rules out. 23 | 24 | import numpy as np 25 | from numpy.linalg.linalg import LinAlgError 26 | from lepspoint import leps_gradient,leps_hessian 27 | 28 | 29 | def _gmat(coord,masses): 30 | '''Calculate the G-matrix of the system.''' 31 | # See E. B. Wildon Jr., J. C. Decius and P. C. Cross "Molecular Vibrations", McGraw-Hill (1955), sec. 4-6 32 | 33 | rAB,rBC,theta = coord 34 | 35 | G12 = np.cos(theta)/masses[1] 36 | G13 = -np.sin(theta)/(rBC*masses[1]) 37 | G23 = -np.sin(theta)/(rAB*masses[1]) 38 | 39 | G=np.array([[np.sum(1/masses[0:2]), G12, G13], 40 | [G12, np.sum(1/masses[1:3]), G23], 41 | [G13, G23, 42 | np.sum(1/(rAB**2 * masses[0:2])) + \ 43 | np.sum(1/(rBC**2 * masses[1:3])) - \ 44 | 2*np.cos(theta)/(rAB*rBC*masses[1]**2)]]) 45 | 46 | return G 47 | 48 | 49 | def kinetic_energy(coord,mom,masses): 50 | ''' 51 | Calculate the kineic energy: 52 | 53 | K = 1/2 mom^T G mom 54 | 55 | coord and mom are arrays in internal coordinates. 56 | masses is an array with masses of the 3 atoms. 57 | ''' 58 | 59 | G = _gmat(coord,masses) 60 | 61 | return 0.5 * mom.dot(G).dot(mom) 62 | 63 | 64 | def velocities(coord,mom,masses): 65 | ''' 66 | Calculate velocities in internal coordinates. 67 | These don't have a simple relation to momenta. 68 | They are calculate from Hamilton's equations by differentiating the kinetic 69 | energy with respect to momenta. 70 | ''' 71 | 72 | G = _gmat(coord,masses) 73 | 74 | return mom.dot(G) 75 | 76 | 77 | def velocity_AC(coord,vAB,vBC): 78 | ''' 79 | Calculate internuclear velocity between A and C atoms, by doing 80 | the vecor sum of the AB and BC velocities and projecting it onto 81 | the AC axis. 82 | ''' 83 | # setup frame vectors 84 | AB_vec=np.array([coord[0],0]) 85 | BC_vec=np.array([-np.cos(coord[2]),np.sin(coord[2])])*coord[1] 86 | AC_vec=AB_vec+BC_vec 87 | # normalise frame vectors 88 | AB_nvec=AB_vec/np.linalg.norm(AB_vec) 89 | BC_nvec=BC_vec/np.linalg.norm(BC_vec) 90 | AC_nvec=AC_vec/np.linalg.norm(AC_vec) 91 | 92 | # velocity vectors 93 | AB_vvec=-vAB*AB_nvec 94 | BC_vvec=-vBC*BC_nvec 95 | AC_vvec=AB_vvec+BC_vvec #note this is not along AC_nvec 96 | 97 | return -np.dot(AC_vvec,AC_nvec) 98 | 99 | 100 | def lepsnorm(coord,mom,masses,gradient,hessian,dt): 101 | ''' 102 | Updates coordinates and momenta by a time step. 103 | 104 | coord, mom, gradient and hessian are all arrays in internal coordinates rAB, 105 | rBC and theta. 106 | mass is an array with masses of atoms A, B and C. 107 | dt is the size of the timestep. 108 | 109 | The function first converts from internal coordinates into mass-weighted 110 | normal modes, the displacement is calculated in normal modes, and converted 111 | back to internal coordinates. 112 | ''' 113 | 114 | # Transform into normal modes and do dynamics in mass-weighted normal modes 115 | # The transformation does not seem so trivial. Has similarities with the Miyazawa 116 | # method described in: S. Caligano "Vibrational States" John Wiley & Sons (1976) sec. 4.6 117 | # but it is not the same 118 | 119 | GM=_gmat(coord,masses) 120 | 121 | GMVal, GMVec = np.linalg.eigh(GM) 122 | 123 | GMVal1 = GMVal ** 0.5 124 | GMVal2 = GMVal ** (-0.5) 125 | 126 | GRR = GMVec.dot(np.diag(GMVal1)).dot(GMVec.T) 127 | GROOT = GMVec.dot(np.diag(GMVal2)).dot(GMVec.T) 128 | 129 | # G-Matrix Weighted Hessian; 130 | mwhessian = GRR.dot(hessian).dot(GRR) 131 | w2, ALT = np.linalg.eigh(mwhessian) #ALT is antisymmetric version in Fort code but that does not give the right G-Matrix!!!! 132 | 133 | # Gradient Vector in mass-weighted normal modes 134 | gradN = ALT.T.dot(GRR).dot(gradient) 135 | 136 | # Momentum Vector in normal modes 137 | momN = ALT.T.dot(GRR).dot(mom) 138 | 139 | # The dynmics algorithm in mass-weighted normal modes follows: 140 | # T. Helgaker, E. Uggerud, H.J. Aa. Jensen, Chem. Phys Lett. 173(2,3):145-150 (1990) 141 | 142 | displacementN = np.zeros(3) 143 | 144 | epsilon = 1e-14 145 | 146 | for i in range(3): 147 | if w2[i] < - epsilon: # negative curvature of the potential 148 | wmod = abs(w2[i]) ** 0.5 149 | displacementN[i]=momN[i] * np.sinh(wmod*dt) / wmod + gradN[i] * (1 - np.cosh(wmod*dt)) / (wmod**2) 150 | momN[i] = momN[i] * np.cosh(wmod*dt) - gradN[i] * np.sinh(wmod*dt) / wmod 151 | elif abs(w2[i]) < epsilon: # no curvature in potential 152 | displacementN[i] = momN[i] * dt - (0.5 * gradN[i] * (dt ** 2)) 153 | momN[i] = momN[i] - gradN[i] * dt 154 | else: # positive curvature of the potential 155 | wroot =w2[i] ** 0.5 156 | displacementN[i]=momN[i] * np.sin(wroot*dt) / wroot - gradN[i] * (1 - np.cos(wroot*dt)) / (wroot**2) 157 | momN[i] = momN[i] * np.cos(wroot*dt) - gradN[i] * np.sin(wroot*dt) / wroot 158 | 159 | # update coordinates by first transforming displacementN into internal coordinates 160 | coord = coord + GRR.dot(ALT).dot(displacementN) 161 | 162 | # transform updated momentum back into internal coordinates 163 | mom = GROOT.dot(ALT).dot(momN) 164 | 165 | return (coord,mom) 166 | 167 | 168 | def calc_trajectory(coord_init,mom_init,masses,morse_params,sato,steps,dt,calc_type): 169 | ''' 170 | Make the system move. This may be the calculation of a inertial trajectory 171 | (calc_type="Dynamics"), a minimum energy path (calc_type="MEP"), a local 172 | monimum or transitions state search (calc_type="Opt Min" or calc_type="Opt TS"). 173 | 174 | The function outputs a trajectory array with position and momenta, and a string 175 | which may contain an error message. 176 | ''' 177 | 178 | # Rewrite inputs to avoid side effects 179 | coord=coord_init 180 | mom=mom_init 181 | step_size=dt 182 | 183 | # If not doing Dynamics (MEP, Opt Min or Opt TS), set initial momenta to zero 184 | if calc_type != "Dynamics": 185 | mom=np.zeros(3) 186 | 187 | # If doing a MEP increase step size to compensate absence of inertial term 188 | if calc_type == "MEP": 189 | step_size = 15*dt 190 | 191 | #Initialise outputs 192 | trajectory = [np.column_stack((coord,mom))] 193 | error = "" 194 | 195 | #Flag to stop appending to output in case of a crash 196 | terminate = False 197 | 198 | itcounter = 0 199 | while itcounter < steps and not terminate: 200 | itcounter = itcounter+1 201 | 202 | #Get current gradient, and Hessian 203 | #(array unpacking *coord used below only works for python 3.5 or higher) 204 | gradient = leps_gradient(*coord,morse_params,sato) 205 | hessian = leps_hessian(*coord,morse_params,sato) 206 | 207 | if calc_type in ["Opt Min", "Opt TS"]: #Optimisation calculations 208 | 209 | #Diagonalise Hessian 210 | eigenvalues, eigenvectors = np.linalg.eigh(hessian) 211 | 212 | #Eigenvalue test 213 | neg_eig = [eig for eig in eigenvalues if eig < -1e-14] 214 | if len(neg_eig) == 0 and calc_type == "Opt TS": 215 | error="Eigenvalues Info::No negative curvatures at this geometry" 216 | terminate = True 217 | elif len(neg_eig) > 0 and calc_type == "Opt Min": 218 | error="Eigenvalues Error::Too many negative curvatures at this geometry" 219 | terminate = True 220 | elif len(neg_eig) > 1: 221 | error="Eigenvalues Error::Too many negative curvatures at this geometry" 222 | terminate = True 223 | 224 | #Optimiser 225 | disps = np.zeros(3) 226 | for mode in range(len(eigenvalues)): 227 | e_val = eigenvalues[mode] 228 | e_vec = eigenvectors[:,mode] #eigenvectors are the columns 229 | 230 | #disp is a vector with the same direction as e_vec 231 | disp = np.dot(e_vec, -gradient) * e_vec / e_val 232 | disps += disp 233 | 234 | # update positions 235 | # use dt to scale the step 236 | coord = coord + dt*disps 237 | 238 | else: #Dynamics/MEP 239 | 240 | try: 241 | coord,mom = lepsnorm(coord,mom,masses,gradient,hessian,step_size) 242 | except LinAlgError: 243 | error="Surface Error::Energy could not be evaluated at step {}. Positions might be beyond the validity of the surface. Steps truncated".format(itcounter + 1) 244 | terminate = True 245 | 246 | if calc_type=="MEP": 247 | # reset momenta to zero if doing a MEP 248 | mom=np.zeros(3) 249 | 250 | if not terminate: 251 | # Update records 252 | trajectory.append(np.column_stack((coord,mom))) 253 | 254 | # convert to array and return 255 | return (np.array(trajectory),error) 256 | -------------------------------------------------------------------------------- /lepspoint.py: -------------------------------------------------------------------------------- 1 | #Created on Wed May 17 10:41:56 2017 2 | # 3 | #@author: Tristan Mackenzie 4 | # 5 | # This file is part of LepsPy. 6 | # 7 | # LepsPy is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # LepsPy is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with LepsPy. If not, see . 19 | 20 | 21 | # This file contains functions that calculate the London-Eyring-Polanyi-Sato (LEPS) 22 | # potential for a set of internal coordinates (2 bond distances and a bond angle), 23 | # as well and the gradient and hessian of the surface with respect to the internal 24 | # coordinates at that point of the surface. 25 | 26 | 27 | import numpy as np 28 | 29 | #this state variable looks strange 30 | state = 1 # 1 for ground state, >1 for excited states 31 | 32 | 33 | def cos_rule(side1,side2,angle): 34 | ''' 35 | Use the cos rule to calculate the length of the side of a triangle, 36 | given the other 2 side lengths and the angle between them. 37 | ''' 38 | 39 | return (side1**2 + side2**2 - 2*side1*side2*np.cos(angle))**0.5 40 | 41 | 42 | def _morse(r,D,B,re): 43 | '''Morse potential with a dissociation limit at 0.''' 44 | 45 | return D*(np.exp(-2*B*(r-re)) - 2*np.exp(-B*(r-re))) 46 | 47 | 48 | def _morse_deriv1(r,D,B,re): 49 | '''First derivative of the Morse potential with respect to r.''' 50 | 51 | return -2*B*D*(np.exp(-2*B*(r-re)) - np.exp(-B*(r-re))) 52 | 53 | 54 | def _morse_deriv2(r,D,B,re): 55 | '''Second derivative of the Morse potential with respect to r.''' 56 | 57 | return 2 * B**2 * D*(2*np.exp(-2*B*(r-re)) - np.exp(-B*(r-re))) 58 | 59 | 60 | def _anti_morse(r,D,B,re): 61 | '''Potential with functional form similar to Morse, used as the triplet 62 | component of the LEPS potential.''' 63 | 64 | return 0.5*D*(np.exp(-2*B*(r-re)) + 2*np.exp(-B*(r-re))) 65 | 66 | 67 | def _anti_morse_deriv1(r,D,B,re): 68 | '''First derivative of the anti-Morse potential with respect to r.''' 69 | 70 | return -B*D*(np.exp(-2*B*(r-re)) + np.exp(-B*(r-re))) 71 | 72 | 73 | def _anti_morse_deriv2(r,D,B,re): 74 | '''Second derivative of the anti-Morse potential with respect to r.''' 75 | 76 | return B**2 * D*(2*np.exp(-2*B*(r-re)) + np.exp(-B*(r-re))) 77 | 78 | 79 | def _coulomb(morse,anti_morse,k): 80 | '''Calculate Coulomb (Q) integral in the LEPS approximation. 81 | The function is also used to compute the derivatives of Q since it is linear 82 | on the morse and anti_morse components.''' 83 | 84 | return 0.5*(morse + anti_morse + k*(morse - anti_morse)) 85 | 86 | 87 | def _exchange(morse,anti_morse,k): 88 | '''Calculate Exchange (J) integral in the LEPS approximation. 89 | The function is also used to compute the derivatives of J since it is linear 90 | on the morse and anti_morse components.''' 91 | 92 | return 0.5*(morse - anti_morse + k*(morse + anti_morse)) 93 | 94 | 95 | def leps_energy(rAB,rBC,theta,params,k): 96 | '''Calculate LEPS potential energy for a given point in internal coordinates 97 | int_coord=array([rAB,rBC,theta]) 98 | params=array([[D_A,B_A,re_A], 99 | [D_B.B_B,re_B], 100 | [D_C,B_C,re_C]]).''' 101 | 102 | #Build array with distances rAB,rBC and rAC 103 | #moveaxis has no effect for a single point, but allows vectorisation of the function 104 | r=np.moveaxis(np.array([rAB,rBC,cos_rule(rAB,rBC,theta)]),0,-1) 105 | 106 | #Coulomb and Exchange integrals 107 | Q=_coulomb(_morse(r,params[:,0],params[:,1],params[:,2]), 108 | _anti_morse(r,params[:,0],params[:,1],params[:,2]),k) 109 | J=_exchange(_morse(r,params[:,0],params[:,1],params[:,2]), 110 | _anti_morse(r,params[:,0],params[:,1],params[:,2]),k) 111 | 112 | #axis=-1 below allows vectorisation of the function 113 | return 1/(1+k) * (np.sum(Q,axis=-1) - state/2**0.5 *np.linalg.norm(J - np.roll(J,-1,axis=-1),axis=-1)) 114 | 115 | 116 | def leps_gradient(rAB,rBC,theta,params,k): 117 | '''Calculates the gradient of LEPS potential for a given point in internal coordinates 118 | int_coord=array([rAB,rBC,theta]) 119 | params=array([[D_A,B_A,re_A], 120 | [D_B.B_B,re_B], 121 | [D_C,B_C,re_C]]). 122 | The gradient is given in internal coordinates: 123 | grad=array([dV/drAB,dV/drBC,dV/dtheta]).''' 124 | 125 | #Build array with distances rAB,rBC and rAC 126 | r=np.array([rAB,rBC,cos_rule(rAB,rBC,theta)]) 127 | 128 | #Exchange integrals (Coulomb not needed) 129 | J=_exchange(_morse(r,params[:,0],params[:,1],params[:,2]), 130 | _anti_morse(r,params[:,0],params[:,1],params[:,2]),k) 131 | 132 | #Partial derivative of Coulomb and Exchange integrals with respect to inter-atomic distances 133 | #this uses _coulomb() and _exchange() functions because they are linear functions 134 | partial_Q_r=_coulomb(_morse_deriv1(r,params[:,0],params[:,1],params[:,2]), 135 | _anti_morse_deriv1(r,params[:,0],params[:,1],params[:,2]),k) 136 | partial_J_r=_exchange(_morse_deriv1(r,params[:,0],params[:,1],params[:,2]), 137 | _anti_morse_deriv1(r,params[:,0],params[:,1],params[:,2]),k) 138 | 139 | #Note that Q_AC and J_AC depend on rAB and rBC. Calculated eg. dQ_AC/drAB = dQ_AC/drAC * drAC/drAB 140 | #Make array of the derivative of rAC with respect to the internal coordinate 141 | drACdint=np.array([r[0] - r[1]*np.cos(theta),r[1] - r[0]*np.cos(theta),r[0] * r[1]*np.sin(theta)])/r[2] 142 | 143 | #Calculate derivative of the Coulombic part of the potential with respect to the internal coordinates. 144 | #Only Q_AC depends on theta 145 | Qpart_grad_int=np.array([partial_Q_r[0],partial_Q_r[1],0]) + partial_Q_r[2] * drACdint 146 | 147 | #Calculate derivative of the Exchange part of the potential with respect to the internal coordinates. 148 | #Only J_AC depends on theta 149 | Jdiff = J - np.roll(J,-1) 150 | 151 | Jpart_grad_rAB=np.sum(Jdiff*(np.array([1,0,-1])*partial_J_r[0]+np.array([0,-1,1])*partial_J_r[2]*drACdint[0])) 152 | Jpart_grad_rBC=np.sum(Jdiff*(np.array([-1,1,0])*partial_J_r[1]+np.array([0,-1,1])*partial_J_r[2]*drACdint[1])) 153 | Jpart_grad_theta=np.sum(Jdiff*np.array([0,-1,1])*partial_J_r[2]*drACdint[2]) 154 | 155 | Jpart_grad_int=-state/(2**0.5 * np.linalg.norm(Jdiff)) * np.array([Jpart_grad_rAB,Jpart_grad_rBC,Jpart_grad_theta]) 156 | 157 | return 1/(1+k) * (Qpart_grad_int + Jpart_grad_int) 158 | 159 | 160 | def leps_hessian(rAB,rBC,theta,params,k): 161 | '''Calculates the Hessian of LEPS potential for a given point in internal coordinates 162 | params=array([[D_A,B_A,re_A], 163 | [D_B.B_B,re_B], 164 | [D_C,B_C,re_C]]). 165 | The gradient is given in internal coordinates,''' 166 | 167 | #Build array with distances rAB,rBC and rAC 168 | r=np.array([rAB,rBC,cos_rule(rAB,rBC,theta)]) 169 | 170 | #Exchange integrals (Coulomb not needed) 171 | J=_exchange(_morse(r,params[:,0],params[:,1],params[:,2]), 172 | _anti_morse(r,params[:,0],params[:,1],params[:,2]),k) 173 | 174 | #Partial first and second derivatives of Coulomb and Exchange integrals with respect to inter-atomic distances 175 | #this uses _coulomb() and _exchange() functions because they are linear functions 176 | partial_Q_r=_coulomb(_morse_deriv1(r,params[:,0],params[:,1],params[:,2]), 177 | _anti_morse_deriv1(r,params[:,0],params[:,1],params[:,2]),k) 178 | partial_J_r=_exchange(_morse_deriv1(r,params[:,0],params[:,1],params[:,2]), 179 | _anti_morse_deriv1(r,params[:,0],params[:,1],params[:,2]),k) 180 | partial2_Q_r=_coulomb(_morse_deriv2(r,params[:,0],params[:,1],params[:,2]), 181 | _anti_morse_deriv2(r,params[:,0],params[:,1],params[:,2]),k) 182 | partial2_J_r=_exchange(_morse_deriv2(r,params[:,0],params[:,1],params[:,2]), 183 | _anti_morse_deriv2(r,params[:,0],params[:,1],params[:,2]),k) 184 | 185 | #Note that Q_AC and J_AC depend on rAB and rBC. 186 | #Make array of first derivatives of rAC with respect to the internal coordinate 187 | drACdint=np.array([r[0] - r[1]*np.cos(theta),r[1] - r[0]*np.cos(theta),r[0] * r[1]*np.sin(theta)])/r[2] 188 | 189 | #Make matrix of second derivatives of rAC with respect to the internal coordinate 190 | #d2rAC/dint2=array([[d2rAC/drAB2,d2rAC/(drABdrBC),d2rAC/(drABdtheta)], 191 | # [d2rAC/(drABdrBC),d2rAC/drBC2,d2rAC/(drBCdtheta)], 192 | # [d2rAC/(drABdtheta),d2rAC/(drBCdtheta),d2rAC/dtheta2]]) 193 | d2rACdint2=np.array([[r[1]**2 * np.sin(theta)**2,-r[0]*r[1]*np.sin(theta)**2,r[1]**2 * np.sin(theta) * (r[1]-r[0]*np.cos(theta))], 194 | [-r[0]*r[1]*np.sin(theta)**2,r[0]**2 * np.sin(theta)**2,r[0]**2 * np.sin(theta) * (r[0]-r[1]*np.cos(theta))], 195 | [r[1]**2 * np.sin(theta) * (r[1]-r[0]*np.cos(theta)),r[0]**2 * np.sin(theta) * (r[0]-r[1]*np.cos(theta)),r[0]*r[1]*r[2]**2*np.cos(theta) - r[0]**2 * r[1]**2 *np.sin(theta)**2]]) / (r[2]**3) 196 | 197 | #Calculate Coulombic contribution to the Hessian 198 | Qpart_hess_int=np.diag(np.array([partial2_Q_r[0],partial2_Q_r[1],0])) + \ 199 | partial_Q_r[2] * d2rACdint2 + \ 200 | partial2_Q_r[2] * (drACdint * np.expand_dims(drACdint, axis=1)) #this last line is using broadcasting of 2 vectors to give a matrix 201 | 202 | #Calculate Exchange contribution to the Hessian 203 | #Divide into 2 parts. 204 | Jdiff = J - np.roll(J,-1) 205 | Jdiff_norm= np.linalg.norm(Jdiff) 206 | 207 | Jpart1_hess_drAB2=np.sum(Jdiff*(np.array([1,0,-1])*partial_J_r[0]+np.array([0,-1,1])*partial_J_r[2]*drACdint[0]))**2 208 | Jpart1_hess_drABdrBC=np.sum(Jdiff*(np.array([1,0,-1])*partial_J_r[0]+np.array([0,-1,1])*partial_J_r[2]*drACdint[0])) * \ 209 | np.sum(Jdiff*(np.array([-1,1,0])*partial_J_r[1]+np.array([0,-1,1])*partial_J_r[2]*drACdint[1])) 210 | Jpart1_hess_drABdtheta=np.sum(Jdiff*(np.array([1,0,-1])*partial_J_r[0]+np.array([0,-1,1])*partial_J_r[2]*drACdint[0])) * \ 211 | np.sum(Jdiff*np.array([0,-1,1])*partial_J_r[2]*drACdint[2]) 212 | Jpart1_hess_drBC2=np.sum(Jdiff*(np.array([-1,1,0])*partial_J_r[1]+np.array([0,-1,1])*partial_J_r[2]*drACdint[1]))**2 213 | Jpart1_hess_drBCdtheta=np.sum(Jdiff*(np.array([-1,1,0])*partial_J_r[1]+np.array([0,-1,1])*partial_J_r[2]*drACdint[1])) * \ 214 | np.sum(Jdiff*np.array([0,-1,1])*partial_J_r[2]*drACdint[2]) 215 | Jpart1_hess_dtheta2=np.sum(Jdiff*np.array([0,-1,1])*partial_J_r[2]*drACdint[2])**2 216 | 217 | Jpart1_hess_int=-1/Jdiff_norm**3 * np.array([[Jpart1_hess_drAB2,Jpart1_hess_drABdrBC,Jpart1_hess_drABdtheta], 218 | [Jpart1_hess_drABdrBC,Jpart1_hess_drBC2,Jpart1_hess_drBCdtheta], 219 | [Jpart1_hess_drABdtheta,Jpart1_hess_drBCdtheta,Jpart1_hess_dtheta2]]) 220 | 221 | Jpart2_hess_drAB2=np.sum(Jdiff*(np.array([1,0,-1])*partial2_J_r[0]+np.array([0,-1,1])*(partial2_J_r[2]*drACdint[0]**2+partial_J_r[2]*d2rACdint2[0,0]))) + \ 222 | 2*(partial_J_r[0]**2+(partial_J_r[2]*drACdint[0])**2-partial_J_r[0]*partial_J_r[2]*drACdint[0]) 223 | Jpart2_hess_drABdrBC=np.sum(Jdiff*np.array([0,-1,1])*(partial2_J_r[2]*drACdint[0]*drACdint[1]+partial_J_r[2]*d2rACdint2[0,1])) + \ 224 | (-partial_J_r[0]*partial_J_r[1]-partial_J_r[0]*partial_J_r[2]*drACdint[1]-partial_J_r[1]*partial_J_r[2]*drACdint[0] + \ 225 | 2*partial_J_r[2]**2*drACdint[0]*drACdint[1]) 226 | Jpart2_hess_drABdtheta=np.sum(Jdiff*np.array([0,-1,1])*(partial2_J_r[2]*drACdint[0]*drACdint[2]+partial_J_r[2]*d2rACdint2[0,2])) + \ 227 | (-partial_J_r[0]*partial_J_r[2]*drACdint[2] + 2*partial_J_r[2]**2*drACdint[0]*drACdint[2]) 228 | Jpart2_hess_drBC2=np.sum(Jdiff*(np.array([-1,1,0])*partial2_J_r[1]+np.array([0,-1,1])*(partial2_J_r[2]*drACdint[1]**2+partial_J_r[2]*d2rACdint2[1,1]))) + \ 229 | 2*(partial_J_r[1]**2+(partial_J_r[2]*drACdint[1])**2-partial_J_r[1]*partial_J_r[2]*drACdint[1]) 230 | Jpart2_hess_drBCdtheta=np.sum(Jdiff*np.array([0,-1,1])*(partial2_J_r[2]*drACdint[1]*drACdint[2]+partial_J_r[2]*d2rACdint2[1,2])) + \ 231 | (-partial_J_r[1]*partial_J_r[2]*drACdint[2] + 2*partial_J_r[2]**2*drACdint[1]*drACdint[2]) 232 | Jpart2_hess_dtheta2=np.sum(Jdiff*np.array([0,-1,1])*(partial2_J_r[2]*drACdint[2]**2+partial_J_r[2]*d2rACdint2[2,2])) + \ 233 | 2*(partial_J_r[2]*drACdint[2])**2 234 | 235 | Jpart2_hess_int=1/Jdiff_norm * np.array([[Jpart2_hess_drAB2,Jpart2_hess_drABdrBC,Jpart2_hess_drABdtheta], 236 | [Jpart2_hess_drABdrBC,Jpart2_hess_drBC2,Jpart2_hess_drBCdtheta], 237 | [Jpart2_hess_drABdtheta,Jpart2_hess_drBCdtheta,Jpart2_hess_dtheta2]]) 238 | 239 | return 1/(1+k)*(Qpart_hess_int + (-state/2**0.5 * (Jpart1_hess_int+Jpart2_hess_int))) 240 | 241 | -------------------------------------------------------------------------------- /lepsplots.py: -------------------------------------------------------------------------------- 1 | #@author: Tristan Mackenzie 2 | # 3 | # This file is part of LepsPy. 4 | # 5 | # LepsPy is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # LepsPy is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with LepsPy. If not, see . 17 | 18 | 19 | from lepspoint import leps_energy,cos_rule 20 | from lepsmove import kinetic_energy,velocities,velocity_AC 21 | 22 | import numpy as np 23 | 24 | import matplotlib.pyplot as plt 25 | import matplotlib.collections as mcoll 26 | from matplotlib.animation import FuncAnimation 27 | from mpl_toolkits.mplot3d import Axes3D 28 | 29 | 30 | def plot_contour(trajectory,x_grid,y_grid,Vmat,cutoff,spacing): 31 | """Contour Plot""" 32 | plt.clf() 33 | ax = plt.gca() 34 | ax.get_xaxis().get_major_formatter().set_useOffset(False) 35 | ax.get_yaxis().get_major_formatter().set_useOffset(False) 36 | 37 | plt.xlabel("AB Distance/pm") 38 | plt.ylabel("BC Distance/pm") 39 | 40 | X, Y = np.meshgrid(x_grid, y_grid) 41 | 42 | levels = np.arange(np.min(Vmat) -1, cutoff, spacing) 43 | plt.contour(X, Y, Vmat, levels = levels) 44 | plt.xlim([min(x_grid),max(x_grid)]) 45 | plt.ylim([min(y_grid),max(y_grid)]) 46 | 47 | if max(trajectory[:,2,0])-min(trajectory[:,2,0]) < 1e-7: 48 | plt.plot(trajectory[:,0,0], trajectory[:,1,0], linestyle='', marker='o', markersize=1.5, color='black') 49 | 50 | # highlight initial position 51 | plt.plot(trajectory[:1,0,0], trajectory[:1,1,0], marker='x', markersize=6, color="red") 52 | 53 | plt.draw() 54 | plt.pause(0.0001) #This stops matplotlib from blocking 55 | 56 | 57 | def plot_skew(trajectory,masses,x_grid,y_grid,Vmat,cutoff,spacing): 58 | """Skew Plot""" 59 | # 60 | #Taken from: 61 | #Introduction to Quantum Mechanics: A Time-Dependent Perspective 62 | #Chapter 12.3.3 63 | # 64 | #Transform X and Y to Q1 and Q2, where 65 | #Q1 = a*X + b*Y*cos(beta) 66 | #Q2 = b*Y*sin(beta) 67 | #a = ((m_A * (m_B + m_C)) / (m_A + m_B + m_C)) ** 0.5 68 | #b = ((m_C * (m_A + m_B)) / (m_A + m_B + m_C)) ** 0.5 69 | #beta = cos-1(((m_A * m_C) / ((m_B + m_C) * (m_A + m_B))) ** 0.5) 70 | # 71 | #m_i: mass of atom i 72 | 73 | plt.clf() 74 | ax = plt.gca() 75 | ax.get_xaxis().get_major_formatter().set_useOffset(False) 76 | ax.get_yaxis().get_major_formatter().set_useOffset(False) 77 | 78 | plt.xlabel("Q1/$pm.g^{1/2}.mol^{-1/2}$") 79 | plt.ylabel("Q2/$pm.g^{1/2}.mol^{-1/2}$") 80 | 81 | X, Y = np.meshgrid(x_grid, y_grid) 82 | 83 | ma,mb,mc = masses 84 | 85 | a = ((ma * (mb + mc)) / np.sum(masses)) ** 0.5 86 | b = ((mc * (ma + mb)) / np.sum(masses)) ** 0.5 87 | beta = np.arccos(((ma * mc) / ((mb + mc) * (ma + mb))) ** 0.5) 88 | 89 | #Transform grid 90 | Q1 = a * X + b * Y * np.cos(beta) 91 | Q2 = b * Y * np.sin(beta) 92 | 93 | #Plot gridlines every 30pm 94 | splot_grid_x = list(np.arange(x_grid[0], x_grid[-1], 30))+[x_grid[-1]] 95 | splot_grid_y = list(np.arange(y_grid[0], y_grid[-1], 30))+[y_grid[-1]] 96 | 97 | for x in splot_grid_x: 98 | r1 = [x, splot_grid_y[ 0]] 99 | r2 = [x, splot_grid_y[-1]] 100 | 101 | q1 = [a * r1[0] + b * r1[1] * np.cos(beta), b * r1[1] * np.sin(beta)] 102 | q2 = [a * r2[0] + b * r2[1] * np.cos(beta), b * r2[1] * np.sin(beta)] 103 | 104 | plt.plot([q1[0], q2[0]], [q1[1], q2[1]], linewidth=1, color='gray') 105 | plt.text(q2[0], q2[1], str(int(x))) #round label to integer 106 | 107 | for y in splot_grid_y: 108 | r1 = [splot_grid_x[ 0], y] 109 | r2 = [splot_grid_x[-1], y] 110 | 111 | q1 = [a * r1[0] + b * r1[1] * np.cos(beta), b * r1[1] * np.sin(beta)] 112 | q2 = [a * r2[0] + b * r2[1] * np.cos(beta), b * r2[1] * np.sin(beta)] 113 | 114 | plt.plot([q1[0], q2[0]], [q1[1], q2[1]], lw=1, color='gray') 115 | plt.text(q2[0], q2[1], str(int(y))) #round label to integer 116 | 117 | #Plot transformed PES 118 | levels = np.arange(np.min(Vmat) -1, cutoff, spacing) 119 | plt.contour(Q1, Q2, Vmat, levels = levels) 120 | plt.autoscale() 121 | plt.axes().set_aspect('equal') 122 | 123 | srab = a * trajectory[:,0,0] + b * trajectory[:,1,0] * np.cos(beta) 124 | srbc = b * trajectory[:,1,0] * np.sin(beta) 125 | 126 | if max(trajectory[:,2,0])-min(trajectory[:,2,0]) < 1e-7: 127 | #Plot transformed trajectory 128 | plt.plot(srab, srbc, linestyle='', marker='o', markersize=1.5, color='black') 129 | 130 | # highlight initial position 131 | plt.plot(srab[0], srbc[0], marker='x', markersize=6, color="red") 132 | 133 | plt.draw() 134 | plt.pause(0.0001) 135 | 136 | 137 | def plot_surface(trajectory,morse_params,sato,x_grid,y_grid,Vmat,cutoff,spacing): 138 | """3d Surface Plot""" 139 | 140 | plt.close('all') #New figure needed for 3D axes 141 | fig_3d = plt.figure('Surface Plot', figsize=(5,5)) 142 | 143 | ax = Axes3D(fig_3d) 144 | 145 | plt.xlabel("AB Distance/pm") 146 | plt.ylabel("BC Distance/pm") 147 | ax.set_zlabel("V/$kJ.mol^{-1}$") 148 | 149 | X, Y = np.meshgrid(x_grid, y_grid) 150 | ax.set_xlim3d([min(x_grid),max(x_grid)]) 151 | ax.set_ylim3d([min(y_grid),max(y_grid)]) 152 | 153 | Z = np.clip(Vmat, -800, cutoff) 154 | 155 | ax.plot_surface(X, Y, Z, rstride=int(spacing)+1, cstride=int(spacing)+1, cmap='jet', alpha=0.3, linewidth=0.25, edgecolor='black') 156 | 157 | levels = np.arange(np.min(Vmat) -1, cutoff, spacing) 158 | ax.contour(X, Y, Z, zdir='z', levels=levels, offset=ax.get_zlim()[0]-1) 159 | 160 | if max(trajectory[:,2,0])-min(trajectory[:,2,0]) < 1e-7: 161 | ax.plot(trajectory[:,0,0], trajectory[:,1,0], 162 | leps_energy(trajectory[:,0,0],trajectory[:,1,0],trajectory[:,2,0],morse_params,sato), 163 | color='black', linestyle='none', marker='o', markersize=2) 164 | 165 | plt.draw() 166 | plt.pause(0.0001) 167 | 168 | 169 | def plot_ind_vs_t(trajectory,dt,calc_type): 170 | """Internuclear Distances VS Time""" 171 | plt.clf() 172 | ax = plt.gca() 173 | ax.get_xaxis().get_major_formatter().set_useOffset(False) 174 | ax.get_yaxis().get_major_formatter().set_useOffset(False) 175 | 176 | if calc_type == "Dynamics": 177 | xaxis=dt*np.arange(len(trajectory)) 178 | plt.xlabel("Time/fs") 179 | else: 180 | xaxis=np.arange(len(trajectory)) 181 | plt.xlabel("Steps") 182 | 183 | plt.ylabel("Distance/pm") 184 | 185 | plt.plot(xaxis, trajectory[:,0,0], label = "A-B") 186 | plt.plot(xaxis, trajectory[:,1,0], label = "B-C") 187 | plt.plot(xaxis, cos_rule(trajectory[:,0,0],trajectory[:,1,0],trajectory[:,2,0]), label = "A-C") 188 | 189 | plt.legend() 190 | 191 | plt.draw() 192 | plt.pause(0.0001) 193 | 194 | 195 | def plot_inv_vs_t(trajectory,masses,dt,calc_type): 196 | """Internuclear velocities VS time""" 197 | plt.clf() 198 | ax = plt.gca() 199 | ax.get_xaxis().get_major_formatter().set_useOffset(False) 200 | ax.get_yaxis().get_major_formatter().set_useOffset(False) 201 | 202 | # calculate velocities 203 | veloc=[] 204 | for point in trajectory: 205 | # velicities in internal coordinates 206 | internal_veloc=list(velocities(point[:,0],point[:,1],masses)) 207 | # calculate magnitude of veloctity between AC 208 | vAC=velocity_AC(point[:,0],*internal_veloc[0:2]) 209 | # make list of internuclear velocities 210 | in_veloc=internal_veloc[0:2]+[vAC] 211 | 212 | veloc.append(in_veloc) 213 | 214 | veloc=np.array(veloc) 215 | 216 | if calc_type == "Dynamics": 217 | xaxis=dt*np.arange(len(trajectory)) 218 | plt.xlabel("Time/fs") 219 | else: 220 | xaxis=np.arange(len(trajectory)) 221 | plt.xlabel("Steps") 222 | 223 | plt.ylabel("$Velocity/pm.fs^{-1}$") 224 | 225 | plt.plot(xaxis, veloc[:,0], label = "A-B") 226 | plt.plot(xaxis, veloc[:,1], label = "B-C") 227 | plt.plot(xaxis, veloc[:,2], label = "A-C") 228 | 229 | plt.legend() 230 | 231 | plt.draw() 232 | plt.pause(0.0001) 233 | 234 | 235 | def plot_momenta_vs_t(trajectory,dt,calc_type): 236 | """Momenta VS Time""" 237 | plt.clf() 238 | ax = plt.gca() 239 | ax.get_xaxis().get_major_formatter().set_useOffset(False) 240 | ax.get_yaxis().get_major_formatter().set_useOffset(False) 241 | 242 | if calc_type == "Dynamics": 243 | xaxis=dt*np.arange(len(trajectory)) 244 | plt.xlabel("Time/fs") 245 | else: 246 | xaxis=np.arange(len(trajectory)) 247 | plt.xlabel("Steps") 248 | 249 | plt.ylabel("$Momentum/g.mol^{-1}.pm.fs^{-1}$") 250 | 251 | plt.plot(xaxis, trajectory[:,0,1], label = "A-B") 252 | plt.plot(xaxis, trajectory[:,1,1], label = "B-C") 253 | plt.plot(xaxis, trajectory[:,2,1], label = "θ") 254 | 255 | plt.legend() 256 | 257 | plt.draw() 258 | plt.pause(0.0001) 259 | 260 | 261 | def plot_momenta(trajectory): 262 | """AB Momentum VS BC Momentum""" 263 | plt.clf() 264 | ax = plt.gca() 265 | 266 | plt.xlabel("AB Momentum/$g.mol^{-1}.pm.fs^{-1}$") 267 | plt.ylabel("BC Momentum/$g.mol^{-1}.pm.fs^{-1}$") 268 | 269 | lc = colorline(trajectory[:,0,1], trajectory[:,1,1], cmap = plt.get_cmap("jet"), linewidth=1) 270 | 271 | ax.add_collection(lc) 272 | ax.autoscale() 273 | plt.draw() 274 | plt.pause(0.0001) 275 | 276 | 277 | def plot_velocities(trajectory,masses): 278 | """AB Velocity VS BC Velocity""" 279 | 280 | # calculate velocities in internal coordinates 281 | veloc=[] 282 | for point in trajectory: 283 | veloc.append(velocities(point[:,0],point[:,1],masses)) 284 | veloc=np.array(veloc) 285 | 286 | plt.clf() 287 | ax = plt.gca() 288 | 289 | plt.xlabel("AB Velocity/$pm.fs^{-1}$") 290 | plt.ylabel("BC Velocity/$pm.fs^{-1}$") 291 | 292 | lc = colorline(veloc[:,0], veloc[:,1], cmap = plt.get_cmap("jet"), linewidth=1) 293 | 294 | ax.add_collection(lc) 295 | ax.autoscale() 296 | plt.draw() 297 | plt.pause(0.0001) 298 | 299 | 300 | def plot_e_vs_t(trajectory,masses,morse_params,sato,dt,calc_type): 301 | """Energy VS Time""" 302 | plt.clf() 303 | ax = plt.gca() 304 | ax.get_xaxis().get_major_formatter().set_useOffset(False) 305 | ax.get_yaxis().get_major_formatter().set_useOffset(False) 306 | 307 | if calc_type == "Dynamics": 308 | xaxis=dt*np.arange(len(trajectory)) 309 | plt.xlabel("Time/fs") 310 | else: 311 | xaxis=np.arange(len(trajectory)) 312 | plt.xlabel("Steps") 313 | 314 | plt.ylabel("E/$kJ.mol^{-1}$") 315 | 316 | # calculate energies 317 | V=np.zeros(len(trajectory)) 318 | K=np.zeros(len(trajectory)) 319 | for i,point in enumerate(trajectory): 320 | V[i]=leps_energy(*point[:,0],morse_params,sato) 321 | K[i]=kinetic_energy(point[:,0],point[:,1],masses) 322 | 323 | plt.plot(xaxis, V, label = "Potential Energy") 324 | plt.plot(xaxis, K, label = "Kinetic Energy") 325 | plt.plot(xaxis, V+K, label = "Total Energy") 326 | 327 | plt.legend() 328 | 329 | plt.draw() 330 | plt.pause(0.0001) 331 | 332 | 333 | def animation(trajectory,masses,atom_list,atom_map): 334 | """Animation""" 335 | plt.close('all') 336 | ani_fig = plt.figure('Animation', figsize=(5,5)) 337 | 338 | #Positions in space of A, B and C relative to B 339 | frames = len(trajectory) 340 | positions = np.column_stack((- trajectory[:,0,0], np.zeros(frames), 341 | np.zeros(frames), np.zeros(frames), 342 | - np.cos(trajectory[:,2,0]) * trajectory[:,1,0], 343 | np.sin(trajectory[:,2,0]) * trajectory[:,1,0])) 344 | positions = np.reshape(positions,(frames,3,2)) 345 | 346 | #Get centre of mass 347 | com = masses.dot(positions[:])/np.sum(masses) 348 | 349 | #Translate to centre of mass (there might be a way to do this only with array operations) 350 | positions = positions - np.reshape(np.column_stack((com,com,com)),(frames,3,2)) 351 | 352 | def init(): 353 | ap, bp, cp = patches 354 | ax.add_patch(ap) 355 | ax.add_patch(bp) 356 | ax.add_patch(cp) 357 | return ap, bp, cp, 358 | 359 | def update(i): 360 | ap, bp, cp = patches 361 | ap.center = positions[i,0] 362 | bp.center = positions[i,1] 363 | cp.center = positions[i,2] 364 | return ap, bp, cp, 365 | 366 | ax = plt.axes( 367 | xlim = (min(np.ravel(positions[:,:,0])) - 100, max(np.ravel(positions[:,:,0])) + 100), 368 | ylim = (min(np.ravel(positions[:,:,1])) - 100, max(np.ravel(positions[:,:,1])) + 100) 369 | ) 370 | ax.set_aspect('equal') 371 | 372 | patches = [] 373 | 374 | for i,at_name in enumerate(atom_list): 375 | vdw, col = atom_map[at_name] 376 | patch = plt.Circle(positions[0,i], vdw * 0.25, color = col) 377 | patches.append(patch) 378 | 379 | anim = FuncAnimation(ani_fig, update, init_func=init, frames=len(positions), repeat=True, interval=5) 380 | 381 | # Try to show animation but be cautious about crashes 382 | try: 383 | plt.show() 384 | except: 385 | pass 386 | 387 | 388 | def colorline(x, y, z=None, cmap=plt.get_cmap('copper'), norm=plt.Normalize(0.0, 1.0), 389 | linewidth=3, alpha=1.0): 390 | """ 391 | http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb 392 | http://matplotlib.org/examples/pylab_examples/multicolored_line.html 393 | Plot a colored line with coordinates x and y 394 | Optionally specify colors in the array z 395 | Optionally specify a colormap, a norm function and a line width 396 | """ 397 | 398 | # Default colors equally spaced on [0,1]: 399 | if z is None: 400 | z = np.linspace(0.0, 1.0, len(x)) 401 | 402 | # Special case if a single number: 403 | if not hasattr(z, "__iter__"): # to check for numerical input -- this is a hack 404 | z = np.array([z]) 405 | 406 | z = np.asarray(z) 407 | 408 | segments = make_segments(x, y) 409 | lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm, 410 | linewidth=linewidth, alpha=alpha) 411 | 412 | return lc 413 | 414 | 415 | def make_segments(x, y): 416 | """ 417 | Create list of line segments from x and y coordinates, in the correct format 418 | for LineCollection: an array of the form numlines x (points per line) x 2 (x 419 | and y) array 420 | """ 421 | 422 | points = np.array([x, y]).T.reshape(-1, 1, 2) 423 | segments = np.concatenate([points[:-1], points[1:]], axis=1) 424 | return segments 425 | -------------------------------------------------------------------------------- /lepsgui.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | #Created on Mon May 22 16:59:17 2017 4 | # 5 | #@author: Tristan Mackenzie 6 | # 7 | # This file is part of LepsPy. 8 | # 9 | # LepsPy is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # LepsPy is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with LepsPy. If not, see . 21 | 22 | 23 | import numpy as np 24 | 25 | from matplotlib import use as mpl_use 26 | mpl_use("TkAgg") # might need to be changed on different operating systems 27 | 28 | import matplotlib.pyplot as plt 29 | import warnings 30 | 31 | import tkinter as tk 32 | import tkinter.messagebox as msgbox 33 | from tkinter.filedialog import asksaveasfilename 34 | 35 | from configparser import ConfigParser 36 | from argparse import ArgumentParser 37 | 38 | from params import params 39 | from lepspoint import leps_energy,leps_gradient,leps_hessian,cos_rule 40 | from lepsmove import calc_trajectory,kinetic_energy,velocities,velocity_AC 41 | from lepsplots import plot_contour,plot_skew,plot_surface,plot_ind_vs_t,plot_inv_vs_t,plot_momenta_vs_t,plot_momenta,plot_velocities,plot_e_vs_t,animation 42 | 43 | 44 | class Interactive(): 45 | 46 | def __init__(self, advanced=False): #Initialise Class 47 | 48 | ###Initialise tkinter### 49 | self.root = tk.Tk() 50 | self.root.title("LEPS GUI") 51 | self.root.resizable(False,False) 52 | 53 | ###Initialise defaults### 54 | 55 | config = ConfigParser(inline_comment_prefixes=(';', '#')) 56 | # The line below allows for dictionary keys with capital letters 57 | config.optionxform = lambda op:op 58 | config.read('params.ini') 59 | 60 | #Atom: [Index, VdW radius, colour] 61 | #VdW radius - used for animation 62 | #Colour - used for animation 63 | atom_map = {} 64 | atoms = config['atoms'] 65 | self.atoms_list = [] 66 | for element, l in atoms.items(): 67 | mass, vdw, colour = l.split(',') 68 | atom_map[element] = [ 69 | float(vdw), 70 | '#' + colour.strip() 71 | ] 72 | self.atoms_list.append(element) 73 | self.atom_map = atom_map 74 | 75 | defaults = config['defaults'] 76 | self.sato = float(defaults['sato']) #Surface parameter 77 | 78 | self.Vmat = None #Array where potential is stored for each gridpoint 79 | self.surf_params = None #Variable used to prevent surface being recalculated 80 | self.traj_params = None #Variable used to prevent trajectory being recalculated 81 | 82 | self.entries = {} #Dictionary of entries to be read on refresh (user input) 83 | self.defaults = { #Defaults for each entry 84 | #Key : Default value , type , processing function 85 | "a" : ["H" , str , None ], 86 | "b" : ["H" , str , None ], 87 | "c" : ["H" , str , None ], 88 | "xrabi" : ["230" , float, None ], 89 | "xrbci" : ["74" , float, None ], 90 | "prabi" : ["-5.1" , float, None ], 91 | "prbci" : ["-3.1" , float, None ], 92 | "steps" : ["500" , int , lambda x: max(1, x) ], 93 | "dt" : ["0.1" , float, lambda x: max(1e-5,x) ], 94 | "cutoff" : ["-80" , float, None ], 95 | "spacing" : ["10" , int , None ], 96 | "calc_type": ["Dynamics" , str , None ], 97 | "theta" : ["180" , float, lambda x:np.deg2rad(x) ], 98 | "plot_type": ["Contour Plot", str , None ] 99 | } 100 | 101 | #Store variable as class attributes 102 | for key, l in self.defaults.items(): 103 | val, vtype, procfunc = l 104 | val = vtype(val) 105 | if procfunc: #Check whether processing is needed 106 | val = procfunc(val) 107 | setattr(self, key, val) 108 | 109 | ###GUI### 110 | 111 | #Default frame format 112 | sunken = dict(height = 2, bd = 1, relief = "sunken") 113 | def gk(string): 114 | '''From a string generates a dictionary with the properties 115 | of the grid of different elements of the GUI''' 116 | 117 | grid = "".join([s for s in string if s.isdigit()]) 118 | sticky = "".join([s for s in string if s in "news"]) 119 | grid = grid.ljust(6, '0') 120 | r,c,rs,cs,px,py = [int(s) for s in grid] 121 | g = {"row": r, "column": c} 122 | if rs: g["rowspan"] = rs 123 | if cs: g["columnspan"] = cs 124 | if px: g["padx"] = px 125 | if py: g["pady"] = py 126 | 127 | if sticky: g["sticky"] = sticky 128 | 129 | return g 130 | 131 | #Atoms Selection Frame 132 | selection_frame = self._add_frame(dict(master=self.root, text="Atoms", **sunken), gk('000055news')) 133 | 134 | self._add_label(selection_frame, {"text": "A:"}, gk('00')) 135 | self._add_label(selection_frame, {"text": "B:"}, gk('02')) 136 | self._add_label(selection_frame, {"text": "C:"}, gk('04')) 137 | 138 | self._add_optionmenu(selection_frame, "a", self.atoms_list, {}, gk('01')) 139 | self._add_optionmenu(selection_frame, "b", self.atoms_list, {}, gk('03')) 140 | self._add_optionmenu(selection_frame, "c", self.atoms_list, {}, gk('05')) 141 | 142 | #Initial Conditions Frame 143 | values_frame = self._add_frame(dict(master=self.root, text="Initial Conditions", **sunken), gk('103055nsew')) 144 | 145 | self._add_label(values_frame, {"text": "Distance /\npm"}, gk('01ew')) 146 | self._add_label(values_frame, {"text": "Momentum /\ng.mol⁻¹.pm.fs⁻¹"}, gk('02ew')) 147 | 148 | self._add_label(values_frame, {"text": "AB"}, gk('10')) 149 | self._add_entry(values_frame, "xrabi", {}, gk('11'), {"width":10}, self.update_geometry_info) 150 | self._add_entry(values_frame, "prabi", {}, gk('12'), {"width":10}, self.update_geometry_info) 151 | 152 | self._add_label(values_frame, {"text": "BC"}, gk('20')) 153 | self._add_entry(values_frame, "xrbci", {}, gk('21'), {"width":10}, self.update_geometry_info) 154 | self._add_entry(values_frame, "prbci", {}, gk('22'), {"width":10}, self.update_geometry_info) 155 | 156 | #Angle Frame 157 | angle_frame = self._add_frame(dict(master=self.root, text="Collision Angle /ᴼ", **sunken), gk('400055news')) 158 | 159 | self._add_scale(angle_frame, "theta", {"from_":0, "to":180, "orient":"horizontal"}, gk('00'), {"length":200}) 160 | 161 | #Update and Export 162 | update_frame = self._add_frame(dict(master=self.root), gk('500355news')) 163 | self._add_button(update_frame, {"text": "Update Plot"} , gk('000055'), {"": self.update_plot }) 164 | self._add_button(update_frame, {"text": "Get Last Geometry"}, gk('010055'), {"": self.get_last_geo}) 165 | self._add_button(update_frame, {"text": "Export Data"} , gk('020055'), {"": self.export }) 166 | 167 | #Calculation Type Frame 168 | calc_type_frame = self._add_frame(dict(master=self.root, text="Calculation Type", **sunken), gk('010055news')) 169 | 170 | if advanced: 171 | calc_types = [ "Dynamics", "MEP", "Opt TS", "Opt Min"] 172 | else: 173 | calc_types = [ "Dynamics", "MEP"] 174 | 175 | self._add_optionmenu(calc_type_frame, "calc_type", calc_types, {}, gk('00'), {"width":20}) 176 | #Steps Frame 177 | steps_frame = self._add_frame(dict(master=self.root, text="Steps", **sunken), gk('110055news')) 178 | self._add_label(steps_frame, {"text": "number"}, gk('00')) 179 | self._add_entry(steps_frame, "steps", {}, gk('01'), {"width":5}) 180 | self._add_label(steps_frame, {"text": "size (fs)"}, gk('02')) 181 | self._add_entry(steps_frame, "dt", {}, gk('03'), {"width":5}) 182 | 183 | #Plot Type Frame 184 | type_frame = self._add_frame(dict(master=self.root, text="Plot Type", **sunken), gk('210055news')) 185 | 186 | if advanced: 187 | plot_types = ["Contour Plot", "Skew Plot", "Surface Plot", "Internuclear Distances vs Time", "Internuclear Velocities vs Time", 188 | "Momenta vs Time", "Energy vs Time", "p(AB) vs p(BC)", "v(AB) vs v(BC)", "Animation"] 189 | else: 190 | plot_types = ["Contour Plot", "Skew Plot", "Surface Plot", "Internuclear Distances vs Time", "Internuclear Velocities vs Time", 191 | "Momenta vs Time", "Energy vs Time", "Animation"] 192 | 193 | self._add_optionmenu(type_frame, "plot_type", plot_types , {}, gk('00'), {"width":20}) 194 | 195 | #Energy contours Frame 196 | energycont_frame = self._add_frame(dict(master=self.root, text="Energy contours /kJ.mol⁻¹", **sunken), gk('312055news')) 197 | self._add_label(energycont_frame, {"text": "cutoff"}, gk('00nw')) 198 | self._add_scale(energycont_frame, "cutoff",{"from_":0, "to":-400, "resolution":5, "orient":"vertical"}, gk('01'), {"length":100}) 199 | 200 | self._add_label(energycont_frame, {"text": "spacing"}, gk('02ne')) 201 | self._add_scale(energycont_frame, "spacing", {"from_":20, "to":1, "resolution":1, "orient":"vertical"}, gk('03'), {"length":100}) 202 | 203 | #Geometry Info Frame 204 | geometry_frame = self._add_frame(dict(master=self.root, text="Initial Geometry Information", **sunken), gk('025055news')) 205 | 206 | self._add_button(geometry_frame, {"text": "Refresh"}, gk('000055'), {"": self.update_geometry_info}) 207 | 208 | energy_frame = self._add_frame(dict(master=geometry_frame, text="Energy /kJ.mol⁻¹", **sunken), gk('100055news')) 209 | self._add_label(energy_frame, {"text": "Kinetic"}, gk('00'), {"width":8}) 210 | self._add_label(energy_frame, {"text": "Potential"}, gk('01'), {"width":8}) 211 | self._add_label(energy_frame, {"text": "Total"}, gk('02'), {"width":8}) 212 | 213 | self.i_ke = self._add_label(energy_frame, {"text": ""}, gk('10')) 214 | self.i_pe = self._add_label(energy_frame, {"text": ""}, gk('11')) 215 | self.i_etot = self._add_label(energy_frame, {"text": ""}, gk('12')) 216 | 217 | forces_frame = self._add_frame(dict(master=geometry_frame, text="Forces /kJ.mol⁻¹.pm⁻¹", **sunken), gk('200055news')) 218 | self._add_label(forces_frame, {"text": "along AB: "}, gk('00')) 219 | self._add_label(forces_frame, {"text": "along BC: "}, gk('10')) 220 | 221 | self.i_fab = self._add_label(forces_frame, {"text": ""}, gk('01')) 222 | self.i_fbc = self._add_label(forces_frame, {"text": ""}, gk('11')) 223 | 224 | hessian_frame = self._add_frame(dict(master=geometry_frame, text="Hessian eigenvalues/vectors", **sunken), gk('300055news')) 225 | self._add_label(hessian_frame, {"text": "ω² /\nkJ.mol⁻¹.pm⁻²"}, gk('00')) 226 | self._add_label(hessian_frame, {"text": "AB direction:"}, gk('10')) 227 | self._add_label(hessian_frame, {"text": "BC direction:"}, gk('20')) 228 | 229 | self.i_eval1 = self._add_label(hessian_frame, {"text": ""}, gk('01')) 230 | self.i_eval2 = self._add_label(hessian_frame, {"text": ""}, gk('02')) 231 | 232 | self.i_evec11 = self._add_label(hessian_frame, {"text": ""}, gk('11')) 233 | self.i_evec12 = self._add_label(hessian_frame, {"text": ""}, gk('12')) 234 | self.i_evec21 = self._add_label(hessian_frame, {"text": ""}, gk('21')) 235 | self.i_evec22 = self._add_label(hessian_frame, {"text": ""}, gk('22')) 236 | 237 | self._add_button(geometry_frame, {"text": "Plot eigenvectors"}, gk('400055'), {"": self.plot_eigen}) 238 | 239 | 240 | #Plot 241 | warnings.filterwarnings("ignore") 242 | self.fig = plt.figure('Plot', figsize=(5,5)) 243 | self.update_plot() 244 | 245 | #Make sure all plots are closed on exit 246 | def cl(): 247 | plt.close('all') 248 | self.root.destroy() 249 | 250 | self.root.protocol("WM_DELETE_WINDOW", cl) 251 | self.root.mainloop() 252 | 253 | def _read_entries(self): 254 | """Read entries from GUI, process and set attributes""" 255 | for key, l in self.entries.items(): 256 | entry, type, procfunc = l 257 | try: 258 | val = self._cast(entry, type) 259 | if procfunc: 260 | val = procfunc(val) 261 | setattr(self, key, val) 262 | except: 263 | pass 264 | 265 | def _cast(self, entry, type): 266 | """Read entry and cast to type""" 267 | val = type(entry.get()) 268 | return val 269 | 270 | def _add_frame(self, frame_kwargs={}, grid_kwargs={}): 271 | """Insert a frame (box) into parent. 272 | With text, a labelled frame is used""" 273 | 274 | if "text" in frame_kwargs: 275 | frame = tk.LabelFrame(**frame_kwargs) 276 | else: 277 | frame = tk.Frame(**frame_kwargs) 278 | 279 | frame.grid(**grid_kwargs) 280 | return frame 281 | 282 | def _add_label(self, frame, text_kwargs={}, grid_kwargs={}, config_kwargs={}): 283 | """Insert a label""" 284 | label = tk.Label(frame, **text_kwargs) 285 | label.grid(**grid_kwargs) 286 | label.config(**config_kwargs) 287 | return label 288 | 289 | def _add_scale(self, frame, key, scale_kwargs={}, grid_kwargs={}, config_kwargs={}): 290 | """Insert a scrollable bar""" 291 | val, vtype, procfunc = self.defaults[key] 292 | variable = tk.StringVar() 293 | variable.set(val) 294 | 295 | scale = tk.Scale(frame, **scale_kwargs) 296 | scale.set(variable.get()) 297 | scale.grid(**grid_kwargs) 298 | scale.config(**config_kwargs) 299 | scale.grid_columnconfigure(0, weight = 1) 300 | 301 | self.entries[key] = [scale, vtype, procfunc] 302 | 303 | def _add_button(self, frame, button_kwargs={}, grid_kwargs={}, bind_kwargs={}, config_kwargs={}): 304 | "Insert a button""" 305 | button = tk.Button(frame, **button_kwargs) 306 | button.grid(**grid_kwargs) 307 | for k, v in bind_kwargs.items(): 308 | button.bind(k, v) 309 | button.config(**config_kwargs) 310 | 311 | def _add_entry(self, frame, key, entry_kwargs={}, grid_kwargs={}, config_kwargs={}, attach_func=None): 312 | """Add a text entry""" 313 | val, vtype, procfunc = self.defaults[key] 314 | variable = tk.StringVar() 315 | variable.set(val) 316 | if attach_func: 317 | variable.trace("w", attach_func) 318 | 319 | entry = tk.Entry(frame, textvariable=variable, **entry_kwargs) 320 | entry.grid(**grid_kwargs) 321 | entry.config(**config_kwargs) 322 | 323 | self.entries[key] = [entry, vtype, procfunc] 324 | 325 | def _add_optionmenu(self, frame, key, items, optionmenu_kwargs={}, grid_kwargs={}, config_kwargs={}): 326 | """Add a dropdown menu""" 327 | val, vtype, procfunc = self.defaults[key] 328 | variable = tk.StringVar() 329 | variable.set(val) 330 | 331 | optionmenu = tk.OptionMenu(frame, variable, *items, **optionmenu_kwargs) 332 | optionmenu.grid(**grid_kwargs) 333 | optionmenu.config(**config_kwargs) 334 | 335 | self.entries[key] = [variable, vtype, procfunc] 336 | 337 | def _add_radio(self, frame, key, radio_kwargs={}, grid_kwargs={}, config_kwargs={}, variable=None): 338 | """Add a radio button""" 339 | val, vtype, procfunc = self.defaults[key] 340 | if variable is None: 341 | variable = tk.StringVar() 342 | variable.set(val) 343 | 344 | radio = tk.Radiobutton(frame, variable=variable, **radio_kwargs) 345 | radio.grid(**grid_kwargs) 346 | radio.config(**config_kwargs) 347 | 348 | self.entries[key] = [radio, vtype, procfunc] 349 | 350 | def get_params(self): 351 | """Gets parameters for a given set of atoms""" 352 | try: 353 | self.masses,self.morse_params,self.plot_limits = params(self.a,self.b,self.c) 354 | except Exception: 355 | msgbox.showerror("Error", "Parameters for this atom combination not available!") 356 | raise 357 | 358 | def get_surface(self): 359 | """Get the full potential energy surface (Vmat) at specified grid points or rAB and rBC.""" 360 | 361 | resl = 2 #Resolution 362 | 363 | #Get grid 364 | self.x = np.arange(self.plot_limits[0,0],self.plot_limits[0,1],resl) 365 | self.y = np.arange(self.plot_limits[1,0],self.plot_limits[1,1],resl) 366 | 367 | X,Y=np.meshgrid(self.x,self.y) 368 | 369 | self.Vmat=leps_energy(X,Y,self.theta,self.morse_params,self.sato) 370 | 371 | def get_last_geo(self, *args): 372 | """Copy last geometry and momenta""" 373 | self.entries["xrabi"][0].delete(0, tk.END) 374 | self.entries["xrabi"][0].insert(0, self.trajectory[-1,0,0]) 375 | 376 | self.entries["xrbci"][0].delete(0, tk.END) 377 | self.entries["xrbci"][0].insert(0, self.trajectory[-1,1,0]) 378 | 379 | self.entries["prabi"][0].delete(0, tk.END) 380 | self.entries["prabi"][0].insert(0, self.trajectory[-1,0,1]) 381 | 382 | self.entries["prbci"][0].delete(0, tk.END) 383 | self.entries["prbci"][0].insert(0, self.trajectory[-1,1,1]) 384 | 385 | def export(self, *args): 386 | """Run calculation and print output in CSV format""" 387 | self._read_entries() 388 | 389 | coord_init=np.array([self.xrabi,self.xrbci,self.theta]) 390 | # Set initial momenta (theta component = 0) 391 | mom_init=np.array([self.prabi,self.prbci,0]) 392 | 393 | self.trajectory,error=calc_trajectory(coord_init,mom_init,self.masses,self.morse_params,self.sato,self.steps,self.dt,self.calc_type) 394 | if error!='': 395 | msgbox.showerror(*error.split('::')) 396 | 397 | filename = asksaveasfilename(defaultextension=".csv") 398 | if not filename: 399 | return 400 | 401 | if self.calc_type == "Dynamics": 402 | header1="Time" 403 | first_column=self.dt*np.arange(len(self.trajectory)) 404 | else: 405 | header1="Step" 406 | first_column=np.arange(len(self.trajectory)) 407 | 408 | line1=header1+",AB distance,AB momentum,BC distance,BC momentum,theta,theta momentum,V energy,K energy,Tot energy" 409 | 410 | # calculate energies 411 | V=np.zeros(len(self.trajectory)) 412 | K=np.zeros(len(self.trajectory)) 413 | for i,point in enumerate(self.trajectory): 414 | V[i]=leps_energy(*point[:,0],self.morse_params,self.sato) 415 | K[i]=kinetic_energy(point[:,0],point[:,1],self.masses) 416 | 417 | data=np.column_stack((first_column,np.reshape(self.trajectory,(len(self.trajectory),6)) 418 | ,V,K,V+K)) 419 | 420 | np.savetxt(filename,data,delimiter=',',header=line1) 421 | 422 | def update_plot(self, *args): 423 | """Generate plot based on what type has been selected""" 424 | 425 | # Besides setting up information about initial position 426 | # this also reads GUI entries and gets relevant parameters 427 | # as it calls _read_entries() and get_params() 428 | self.update_geometry_info() 429 | 430 | # Check if atom types and collision angle have changed 431 | new_surf_params = (self.a, self.b, self.c, self.theta) 432 | if self.surf_params != new_surf_params: 433 | self.get_surface() 434 | 435 | # Check if need to calculate new trajectory 436 | coord_init=(self.xrabi,self.xrbci,self.theta) 437 | mom_init=(self.prabi,self.prbci,0) #Set initial momenta (theta component = 0) 438 | new_traj_params=(coord_init,mom_init,self.steps,self.dt,self.calc_type) 439 | if self.surf_params!=new_surf_params or self.traj_params!=new_traj_params: 440 | self.trajectory,error=calc_trajectory(np.array(coord_init),np.array(mom_init),self.masses, 441 | self.morse_params,self.sato,self.steps,self.dt,self.calc_type) 442 | if error!='': 443 | msgbox.showerror(*error.split('::')) 444 | 445 | self.surf_params=new_surf_params 446 | self.traj_params=new_traj_params 447 | 448 | # Set message to show when trajectory not shown 449 | warnmessage="The angle between bonds is changing along the simulation. \ 450 | Likely the initial collision angle is not 180°. \ 451 | Potential energy surfaces will change with time: surface at time 0 shown. \ 452 | The trajectory is not drawn in this plot." 453 | 454 | if self.plot_type == "Contour Plot": 455 | plot_contour(self.trajectory,self.x,self.y,self.Vmat,self.cutoff,self.spacing) 456 | if max(self.trajectory[:,2,0])-min(self.trajectory[:,2,0]) > 1e-7: 457 | msgbox.showinfo("Changing energy surfaces", warnmessage) 458 | 459 | elif self.plot_type == "Surface Plot": 460 | plot_surface(self.trajectory,self.morse_params,self.sato,self.x,self.y,self.Vmat,self.cutoff,self.spacing) 461 | if max(self.trajectory[:,2,0])-min(self.trajectory[:,2,0]) > 1e-7: 462 | msgbox.showinfo("Changing energy surfaces", warnmessage) 463 | 464 | elif self.plot_type == "Skew Plot": 465 | plot_skew(self.trajectory,self.masses,self.x,self.y,self.Vmat,self.cutoff,self.spacing) 466 | if max(self.trajectory[:,2,0])-min(self.trajectory[:,2,0]) > 1e-7: 467 | msgbox.showinfo("Changing energy surfaces", warnmessage) 468 | 469 | elif self.plot_type == "Internuclear Distances vs Time": 470 | plot_ind_vs_t(self.trajectory,self.dt,self.calc_type) 471 | 472 | elif self.plot_type == "Internuclear Velocities vs Time": 473 | plot_inv_vs_t(self.trajectory,self.masses,self.dt,self.calc_type) 474 | 475 | elif self.plot_type == "Momenta vs Time": 476 | plot_momenta_vs_t(self.trajectory,self.dt,self.calc_type) 477 | 478 | elif self.plot_type == "Energy vs Time": 479 | plot_e_vs_t(self.trajectory,self.masses,self.morse_params,self.sato,self.dt,self.calc_type) 480 | 481 | elif self.plot_type == "p(AB) vs p(BC)": 482 | plot_momenta(self.trajectory) 483 | 484 | elif self.plot_type == "v(AB) vs v(BC)": 485 | plot_velocities(self.trajectory,self.masses) 486 | 487 | elif self.plot_type == "Animation": 488 | animation(self.trajectory,self.masses,[self.a,self.b,self.c],self.atom_map) 489 | 490 | def get_first(self): 491 | """Gather information about the initial state.""" 492 | 493 | coord=np.array([self.xrabi,self.xrbci,self.theta]) 494 | mom=np.array([self.prabi,self.prbci,0]) 495 | 496 | V = leps_energy(*coord,self.morse_params,self.sato) 497 | gradient = leps_gradient(*coord,self.morse_params,self.sato) 498 | hessian = leps_hessian(*coord,self.morse_params,self.sato) 499 | K = kinetic_energy(coord,mom,self.masses) 500 | 501 | return (V,gradient,hessian,K) 502 | 503 | def update_geometry_info(self, *args): 504 | """Updates the info pane""" 505 | self._read_entries() 506 | self.get_params() 507 | 508 | try: 509 | V,gradient,hessian,K = self.get_first() 510 | eigenvalues, eigenvectors = np.linalg.eig(hessian) 511 | 512 | self.init_point_curvature = eigenvalues 513 | self.init_point_nmodes = eigenvectors 514 | 515 | ke = "{:+7.3f}".format(K) 516 | pe = "{:+7.3f}".format(V) 517 | etot = "{:+7.3f}".format(V + K) 518 | fab = "{:+7.3f}".format(-gradient[0]) 519 | fbc = "{:+7.3f}".format(-gradient[1]) 520 | 521 | eval1 = "{:+7.3f}".format(eigenvalues[0]) 522 | eval2 = "{:+7.3f}".format(eigenvalues[1]) 523 | 524 | evec11 = "{:+7.3f}".format(eigenvectors[0,0]) 525 | evec12 = "{:+7.3f}".format(eigenvectors[0,1]) 526 | evec21 = "{:+7.3f}".format(eigenvectors[1,0]) 527 | evec22 = "{:+7.3f}".format(eigenvectors[1,1]) 528 | 529 | except: 530 | ke = " " 531 | pe = " " 532 | etot = " " 533 | fab = " " 534 | fbc = " " 535 | eval1 = " " 536 | eval2 = " " 537 | evec11 = " " 538 | evec12 = " " 539 | evec21 = " " 540 | evec22 = " " 541 | 542 | self.i_ke["text"] = ke 543 | self.i_pe["text"] = pe 544 | self.i_etot["text"] = etot 545 | 546 | self.i_fab["text"] = fab 547 | self.i_fbc["text"] = fbc 548 | 549 | self.i_eval1["text"] = eval1 550 | self.i_eval2["text"] = eval2 551 | 552 | self.i_evec11["text"] = evec11 553 | self.i_evec12["text"] = evec12 554 | 555 | self.i_evec21["text"] = evec21 556 | self.i_evec22["text"] = evec22 557 | 558 | def plot_eigen(self, *args): 559 | """Plot eigenvectors and eigenvalues of the hessian on contour plot""" 560 | if not self.plot_type == "Contour Plot": 561 | return 562 | 563 | evecs=self.init_point_nmodes #columns are eigenvectors/nmodes 564 | evals=self.init_point_curvature 565 | 566 | plt.arrow(self.trajectory[0,0,0], self.trajectory[0,1,0], 567 | evecs[0,0] * 20, evecs[1,0] * 20, 568 | color = "blue" if evals[0] > 0 else "red", 569 | label = "{:+7.3f}".format(evals[0])) 570 | 571 | plt.arrow(self.trajectory[0,0,0], self.trajectory[0,1,0], 572 | evecs[1,0] * 20, evecs[1,1] * 20, 573 | color = "blue" if evals[1] > 0 else "red", 574 | label = "{:+7.3f}".format(evals[1])) 575 | 576 | plt.draw() 577 | plt.pause(0.0001) 578 | 579 | 580 | if __name__ == "__main__": 581 | 582 | parser = ArgumentParser(description="Starts the Triatomic LEPS GUI") 583 | parser.add_argument("-a", "--advanced", action="store_true", help="Include additional features in the GUI") 584 | 585 | args = parser.parse_args() 586 | interactive = Interactive(advanced = args.advanced) 587 | 588 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------