#!/usr/bin/python

import os
import sys
import glob
import copy
import time 
import math
import string
import subprocess
import argparse

def modvec(l):
    s=0
    for i in range(0,len(l)):
	s=s+l[i]*l[i]
    return math.sqrt(s)

def modvec2(l):
    s=0
    for i in range(0,len(l)):
	s=s+l[i]*l[i]
    return s
    
def spltlist(l,n):
    for i in range(0,len(l),n):
	yield l[i:i+n]

def printl(l):
    for i in range(0,len(l)):
	print '    '.join(str(x) for x in l[i])

# 2,3 and 4 elements are coords
def printf(L,start):
    tmp=copy.deepcopy(L)
    for i in range(start,len(tmp)):
	for j in range(2,5):
	    tmp[i][j]="{: e}".format(tmp[i][j])
    printl(tmp)

def move(l,n):
    return l[-n:]+l[:-n]

def getMass(nameAtom):
    if nameAtom == "O": mass=15.999
    if nameAtom == "H": mass=1.00794
    if nameAtom == "C": mass=12.0107
    if nameAtom == "N": mass=14.00686
    if nameAtom == "S": mass=32.065
    if nameAtom == "Ti": mass=47.867

    return mass

# Get mass-weighted coords from xyz
# element of L should have structure:
# [n nameNumber x y z nameAtom]
# [1 1 0.123 0.231 0.132 H]
def makeMW(L):
    Lmwc=copy.deepcopy(L)
    for j in range(0,len(L)): #go through atoms
	mass=getMass(L[j][5])
	#mass=1 # <<<<<<<<<<<<<<<<<<<<<<<
	for k in range(2,5): #go through coords
	    Lmwc[j][k]=L[j][k]/math.sqrt(mass)
    return Lmwc
# reverse task
def antiMW(L):
    Lxyz=copy.deepcopy(L)
    for j in range(0,len(L)): #go through atoms
	mass=getMass(L[j][5])
	#mass=1 # <<<<<<<<<<<<<<<<<<<<<<<
	for k in range(2,5): #go through coords
	    Lxyz[j][k]=L[j][k]*math.sqrt(mass)
    return Lxyz
def antiMW2(L):
    Lxyz=copy.deepcopy(L)
    for j in range(0,len(L)):
	mass=getMass(L[j][5])
	for k in range(2,5):
	    Lxyz[j][k]=L[j][k]*mass
    return Lxyz


# make tmp.gen file, run dftb+ and get Dipole moment
def getDM(Gen):
    ftmpgen=open('tmp.gen','w')
    for i in range(0,len(Gen)):
	ftmpgen.write('   '.join(str(x) for x in Gen[i])+'\n')
    ftmpgen.close()
    
    flog=open('dftb.log','w')
    print '>>> DFTB Plus Time <<<'
    subprocess.Popen("dftb+",stdout=flog).wait()
    print '>>> DFTB Plus finished <<<'
    flog.close()

    DipMom=[]
    fdetailed=open('detailed.out','r')
    for line in fdetailed:
	if "Dipole moment: " in line:
	    DipMom.append([])
	    for i in range(2,6):
	        DipMom[-1].append(line.split()[i])
    for i in range(0,len(DipMom)):
	for j in range(0,3):
	    DipMom[i][j]=float(DipMom[i][j])
    os.remove('band.out')
    os.remove('dftb_pin.hsd')
    os.remove('detailed.out')
    os.remove('tmp-out.gen')
    os.remove('tmp-out.xyz')
    os.remove('tmp.gen')
    os.remove('dftb.log')
#    print 'Dipole moment:',DipMom
    return DipMom


#-----------------------
#  README
#------------------------

readme="""
Instruction of calculation IR spectra using DFTB Plus and dftb_getIR script:

1. Run standard DFTB Plus geometry optimization in separate folder (folder name could be "1_geom").
   After optimization you should get file out.gen with optimized geometry. 
   Also keep your dftb_in.hsd file - it will be necessary later.

2. Run standard DFTB Plus calculation of second derivatives in next separate folder ("2_secder").
   You should get file hessian.out with second derivatives.

3. Now put out.gen, hessian.out and dftb_in.hsd file from optimization to third folder ("3_getIR") and run dftb_getIR.
   What script dftb_getIR should do:
   * check if all the necessary files are present in folder
   * generate file modes_in.hsd from dftb_in.hsd file
   * run program modes from DFTB Plus software package
   * generate new dftb_in.hsd file for single point calculations of dipole moments
   * generate distorted geometry for each mode using modes output 
   * calculate dipole moment for each mode using generated geometry and new dftb_in.hsd file
     (script automatically starts DFTB Plus code)
   * calculate intensity of each mode
   * write output .irs file with IR spectra data

   NOTE 1. Script automatically generates modes_in.hsd with SlaterKoserFiles section which is taken from dftb_in.hsd file.

   NOTE 2. Script overwrites dftb_in.hsd from geometry optimization step with following changes:
   (a) New Geometry section with "<<< tmp-out.gen".
   (b) New Driver section (important lines: "MaxSteps=0" and "OutputPrefix=0").
   The rest of sections (including SlaterKosterFiles section) would be saved as they were specified in dftb_in.hsd from optimization step.

   NOTE 3. Before overwriting dftb_in.hsd script saves file as dftb_in.src.
   (!) Be careful. Script will overwrite dftb_in.src in case of second run! So you better to save original dftb_in.hsd from optimization somewhere else.
   
   Developer: Vladimir S. Naumov, vsnaumov@yandex.ru 
"""

parser = argparse.ArgumentParser(description=readme, usage='use "%(prog)s --help" for more information',formatter_class=argparse.RawTextHelpFormatter)
args = parser.parse_args()


#--------------------------------------------------------
#  Check necessary files, create HSD files and run modes
#--------------------------------------------------------

print('\nChecking files:')
if glob.glob('out.gen'):
    print('OK: out.gen file has been found')
else:
    print('ERROR: no out.gen file\n')
    sys.exit(0)
if glob.glob('hessian.out'):
    print('OK: hessian.out file has been found')
else:
    print('ERROR: no hessian.out file\n')
    sys.exit(0)
if glob.glob('dftb_in.hsd'):
    print('OK: dftb_in.hsd file has been found')
else:
    print('ERROR: no dftb_in.hsd file\n')
    sys.exit(0)

hsdinp=open('dftb_in.hsd','read')
hsdsrc=open('dftb_in.src','write')
hsdarr=[]
for line in hsdinp:
    hsdarr.append(line)
    hsdsrc.write(line)
hsdinp.close()
hsdsrc.close()
    
hsdsw1=0
hsdsw2=0
hsdsw3=0
for i in range(0,len(hsdarr)):
    #find geometry in hsd
    if 'eometry =' in hsdarr[i] or 'eometry=' in hsdarr[i]: 
	HsdGeomStart=i
	hsdsw1=1
    if ("}" in hsdarr[i]) and hsdsw1==1:
	HsdGeomEnd=i
	hsdsw1=0

    #find driver in hsd
    if 'river =' in hsdarr[i] or 'river=' in hsdarr[i]: 
	HsdDriverStart=i
	hsdsw2=1
    if ("}" in hsdarr[i]) and hsdsw2==1:
	HsdDriverEnd=i
	hsdsw2=0

    #find SKFiles info in hsd
    if 'iles =' in hsdarr[i] or 'iles=' in hsdarr[i]:
	HsdSkfStart=i
	hsdsw3=1
    if ("}" in hsdarr[i]) and hsdsw3==1:
	HsdSkfEnd=i
	hsdsw3=0
	
# create modes_in.hsd to calculate modes and obtain geometries
hsdm=open('modes_in.hsd','write')
hsdm.write("Geometry = GenFormat {\n<<< out.gen\n}\n\nDisplayModes = {\n PlotModes = 1:-1\n Animate = No\n XMakeMol = Yes\n}\n\n")
for i in range(HsdSkfStart,HsdSkfEnd+1):
    hsdm.write(hsdarr[i])
hsdm.write("\nHessian = {\n  <<< \"hessian.out\"\n}")
hsdm.close()

# create dftb_in.hsd for calculations of dipole moment
hsdd=open('dftb_in.hsd','write')
hsdd.write("Geometry = GenFormat {\n<<< tmp.gen\n}\n\nDriver = ConjugateGradient {\n  MovedAtoms = 1:-1\n  MaxForceComponent = 1E-4\n  MaxSteps = 0\n  OutputPrefix = \"tmp-out\"\n  AppendGeometries = Yes\n  ConvergentForcesOnly = Yes\n}\n")
for i in range(0,len(hsdarr)):
    if (i < HsdGeomStart) or (i > HsdGeomEnd):
	if (i < HsdDriverStart) or (i > HsdDriverEnd):
	    hsdd.write(hsdarr[i])
hsdd.close()

#run modes
flogm=open('log_modes.log','write')
subprocess.call("modes",stdout=flogm,shell=True)
time.sleep(1)
flogm.close()



# ------------------------
# HERE MAIN PROGRAM STARTS
# ------------------------


# read gen-file to list Gen
fgen=open('out.gen','r')
SrcGen=[]
for line in fgen:
    SrcGen.append(line.split())
fgen.close()

# process list SrcGen
SrcGen[0][0]=int(SrcGen[0][0])
for i in range(2,len(SrcGen)): # start from string 2nd element of Gen = start from 3rd line of gen.out 
    SrcGen[i][0]=int(SrcGen[i][0]) # convert atom number
    SrcGen[i][1]=int(SrcGen[i][1]) # convert atom type number
    for j in range (2,5):
	SrcGen[i][j]=float(SrcGen[i][j]) # convert coordinatet coord (A, according to gen-file format)
    # convert numbers of atoms to atom names
    # Gen[i][1]=Gen[1][Gen[i][1]-1]

SrcGeom=copy.deepcopy(SrcGen)
for i in range(2,len(SrcGeom)):
    SrcGeom[i].append(SrcGen[1][SrcGen[i][1]-1]) #add atom names
del SrcGeom[0]
del SrcGeom[0]

print '-- Source Gen file (Angstrems) --'
tmp=copy.deepcopy(SrcGen)
for i in range (2,len(SrcGen)):
    for j in range(2,5):
	tmp[i][j]="{: E}".format(tmp[i][j])
printl(tmp)

print '\n\n-- Source Geometry (Angstrems) ---'
printf(SrcGeom,0)


# read vibrations.tag file to list Tag
ftag=open('vibrations.tag', 'r')
Tag=[]
for line in ftag:
    Tag.append(line.split()) # split each line into list by space
ftag.close()

# find indexes for different sections of Tag
for i in range(0,len(Tag)):
    if "frequencies" == Tag[i][0]: nFreq=i 
    if "saved_modes" == Tag[i][0]: nSavedModes=i
    if "eigenmodes" == Tag[i][0]: nEigenModes=i
    if "eigenmodes_scaled" == Tag[i][0]: nEigenModesScaled=i


# freq list
Freq=[]
Hartree__cm=2.1947E+5
for i in range(nFreq+1,nSavedModes):
    for j in range(0,3):
	Freq.append(Hartree__cm*float(Tag[i][j])) #freq

nModes=len(Freq) # number of modes
nAtoms=SrcGen[0][0] # number of atoms

# eigenmodes list
EM=[] # EM is mass-weighted and in Bohrs according to source code of modes
k=0
for i in range(nEigenModes+1,nEigenModesScaled):
    EM.append(Tag[i])
    for j in range(0,len(EM[k])):
	EM[k][j]=float(EM[k][j])
    k=k+1

# eigenmodes_scaled list 
EMS=[] # EMS is mass-weighted and in Bohrs according to source code of modes
k=0
for i in range(nEigenModesScaled+1,len(Tag)):
    EMS.append(Tag[i])
    for j in range(0,len(EMS[k])):
	EMS[k][j]=float(EMS[k][j])
    k=k+1


# multi-level list EMSa for all the modes
# structure of EMSa is the same with SrcGeom
# level 1 - mode
# level 2 - atom
# level 3 - coord
EMSa=[]
k=0
for i in range(0,nModes):
    EMSa.append([])
    for j in range(0,nAtoms):
	EMSa[i].append(EMS[k])
	k=k+1
for i in range(0,nModes):
    for j in range(0,nAtoms):
	EMSa[i][j].append(SrcGeom[j][5])
	EMSa[i][j].append(SrcGeom[j][0])
	EMSa[i][j].append(SrcGeom[j][1])
	EMSa[i][j]=copy.deepcopy(move(EMSa[i][j],2))
    print '-- Mode',i+1,'- Atom vector (Bohrs) --'
    printf(EMSa[i],0)

print '\n\n-- Source Geometry mass-weighted (A/aem^0.5) --'
SrcGeomMwc=makeMW(SrcGeom)
printf(SrcGeomMwc,0)

#!!! According to source code of modes vibrations.tag, EMS and EMSa are already mass-weighted
# So we shouldnt mass-weight EMSa again
# By the way, EMS and EMSa are in Bohrs
''' 

EMSaMwc=[]
for i in range(0,nModes):
    EMSaMwc.append([])
    EMSaMwc[i]=makeMW(EMSa[i])
    print '-- Mode',i+1,'- Atom vector mass-weighted --'
    printf(EMSaMwc[i],0)

'''


coefStep=0.000001 # coef for step to make new geometry
if len(sys.argv)>1: 
    coefStep=float(sys.argv[1])
print '\n\nCoef for Displacement Vectors is',coefStep,'\n\n'


# create move vectors for all atoms in all frames regarding coefStep
Bohr_AA=0.529177249 # to convert Bohrs to Angstrems
DisplVect=copy.deepcopy(EMSa)
Qvect=copy.deepcopy(EMSa)
for i in range(0,nModes):
    for j in range(0,nAtoms):
	for k in range(2,5):
	    DisplVect[i][j][k]=EMSa[i][j][k]*coefStep*Bohr_AA # in Angstrems 
    Qvect[i]=antiMW2(DisplVect[i])
# create new geometry and new gen-lists 
NewGeomMwc=copy.deepcopy(EMSa)
NewGeom=copy.deepcopy(EMSa)
NewGen=[]
for i in range(0,nModes):                  # go through modes
    for j in range(0,nAtoms):              # go through atoms
	for k in range(2,5):               # go through coords
	    NewGeomMwc[i][j][k]=SrcGeomMwc[j][k]+DisplVect[i][j][k]
    NewGeom[i]=antiMW(NewGeomMwc[i])
#    print '-- Mode',i+1,'- New Geometry mass-weighted --'
#    printf(NewGeomMwc[i],0)
#    print '-- Mode',i+1,'- New Geometry simple xyz-coords --'
#    printf(NewGeom[i],0)

    # create gen from src gen and new coords
    NewGen.append(SrcGen[:2]+copy.deepcopy(NewGeom[i]))   
    for j in range(2,len(NewGen[i])):      # delete last element which is atom name
	del NewGen[i][j][-1]
#    print '-- Mode',i+1,'- New Gen file --'
#    printf(NewGen[i],2)


# create output file and start write to it
str1=os.getcwd()
str3='mode       Freq, cm^-1  Int, km/mol    |dDM|,au=A*e    |dQ|,A*aem^0.5 |dDM|/|dQ|,e/aem^0.5'
str2='coefStep = '+str(coefStep)+' # coef for displacement vectors'
str4='------------------------------------------------------------------------------------------'
nameFout='IR-spectra.irs'
fout=open(nameFout,'w')
header=str1+'\n'+str2+'\n'+str3+'\n'+str4
fout.write(header+'\n')



deltaDM=[]
deltaQ=[]
Int=[]
str2file=[]
for i in range(0,nModes):
    print '\n>>> MODE',i+1,'<<<'
    print '-- Source GEN-file (A) --'
    printf(SrcGen,2)
    print '-- Source XYZ (A) --'
    printf(SrcGeom,0)
    print '-- Source XYZ mass-weighted (A^aem^-0.5) --'
    printf(SrcGeomMwc,0)
    print '-- Displacement Vectors mass-weigted (A*aem^-0.5) --'
    printf(DisplVect[i],0)
    print '-- Qvect=DisplVect*m (A*aem^0.5) --'
    printf(Qvect[i],0)
    print '-- New XYZ mass-weighted (A*aem^-0.5) --'
    printf(NewGeomMwc[i],0)
    print '-- New XYZ (A) --'
    printf(NewGeom[i],0)
    print '-- New GEN-file (A) --'
    printf(NewGen[i],2)
    
    
    print '-- Calc delta DM --'
    dm0=getDM(SrcGen)[0]      #[0] is au / [1] is Debye
    dm1=getDM(NewGen[i])[0]   #[0] is au / [1] is Debye
    deltaDM.append([])
    for j in range(0,3):
	deltaDM[i].append(dm1[j]-dm0[j])
#	dm0[j]=": E".format(dm0[j])
#	dm1[j]=": E".format(dm0[j])
#	deltaDM[i][j]=": E".format(deltaDM[i][j])
    print 'Src DM:  ',dm0,'module',modvec(dm0[0:3])
    print 'New DM:  ',dm1,'module',modvec(dm1[0:3])
    print 'Delta DM:',deltaDM[i],'module',modvec(deltaDM[i])

    print '-- Calc deltaQ --'
    deltaQ.append([])
    for j in range(0,nAtoms):
	for k in range (2,5):
	    deltaQ[i].append(Qvect[i][j][k])
    print 'deltaQ:  ','   '.join(str(x) for x in deltaQ[i])
    print 'module',modvec(deltaQ[i])
    
    print '-- Calc Int --'
    dDM_dQ=modvec(deltaDM[i])/modvec(deltaQ[i]) # |dDM|/|dQ|
    Int.append(974.892*dDM_dQ*dDM_dQ)
    print 'Int:',Int[i]
    
    str2file.append([i+1,round(Freq[i],1),round(Int[i],1),modvec(deltaDM[i]),modvec(deltaQ[i]),dDM_dQ])
    str2file[i][0]="{:<6}".format(str2file[i][0])
    for j in range(1,3):
	str2file[i][j]="{:>10}".format(str2file[i][j])
    for j in range(3,6):
	str2file[i][j]="{: e}".format(str2file[i][j])
    fout.write('    '.join(str(x) for x in (str2file[i]))+'\n')

    print '\n'+header
    printl(str2file)

fout.close()

print '\nIR calculation finished'
