def firstNotRepeatingChar_Fast(s): od=collections.orderedDict() for i in s: if i not in od: od[i]=1 else: od[i]+=1 for k,v in od.items(): if v==1: return k return '_'
def user_csv(): userData = {} with open("syslog.log", "r") as file: for line in file.readlines(): val = line[line.find("(") + 1:line.find(")")] if val not in userdata: userData[val] = [0] * 2 if line.find("ERROR"): errVal = userData.get(val)[1] + 1 if line.find("INFO"): infVal = userData.get(Val[0]) + 1 userdata[val] = [infVal, errVal] sorted_userData = collections.orderedDict( sorted(userData.items(), key=operator.itemgetter(0))) with open("user_statistics.csv", "w") as f: [ f.write("{0}, {1}\n".format(key, value)) for key, value in sorted_userData.items() ] return sorted_userData
def error_csv(): errors = {} with open("syslog.log", "r") as file: for line in file.readlines(): val = re.search(r"ERROR ([\w ']*)", line) if val: val = val.group(1)[:-1] if val == None: continue if val not in errors: errors[val] = 1 else: errors[val] = errors.get(val) + 1 sorted_errors = collections.orderedDict( sorted(errors.items(), key=operator.itemgetter(1), reverse=True)) with open("error_message.csv", "w") as f: writer = csv.DictWriter(f, fieldnames=["Error", "Count"]) writer.writeheader() [ f.write("{0}, {1}\n".format(key, value)) for key, value in sorted_errors.items() ] return sorted_errors
def __init__(self, **arguments): ############################ ######### PARSING ########## ############################ ###Rest of the Files### #parse all the things! #### *.struct file parser parser_struct_handle = open(arguments['file_struct'], 'r').readlines() parser_struct_handle = b_PyParse.MainStructParser(parser_struct_handle) parser_struct_handle.parse() #### *.scf file parser parser_scf_handle = open(arguments['file_scf'], 'r').readlines() parser_scf_handle = b_PyParse.MainSCFParser(parser_scf_handle) parser_scf_handle.parse() #### *.outputd parser parser_outputd_handle = open(arguments['file_outputd'], 'r').readlines() parser_outputd_handle = b_PyParse.MainOutputDParser(parser_outputd_handle) parser_outputd_handle.parse() #### *.outputst parser parser_outputst_handle = open(arguments['file_outputst'], 'r').readlines() parser_outputst_handle = b_PyParse.MainOutputstParser(parser_outputst_handle) parser_outputst_handle.parse() ##################################### ############ END Parsing ############ ##################################### ############################# ###### Getting Values ####### ############################# self._calculationValues = orderedDict(); #### *.struct handle # - determine name of atoms # - determine MULT for each atom self._calculationValues['Atom Listing'] = parser_struct_handle['Atom Listing'] #### *.scf handle # - Cell Volume self._calculationValues['Cell Volume in bohr^3'] = parser_scf_handle['Cell Volume'] self._calculationValues['Cell Volume in m^3'] = bohrToMeters(self._calculationValues['Cell Volume in bohr^3'],3) #### *.outputd handle # - BR2_DIR matrix (v_x, v_y, v_z) # - number of atoms in cell # - Lattice Constants (x,y,z) laticematrix=parser_outputd_handle['BR2_DIR Matrix'] latticematrixa1=laticematrix[0] self._calculationValues['Lattice Matrix a1 in bohr']=latticematrixa1 latticematrixa2=laticematrix[1] self._calculationValues['Lattice Matrix a2 in bohr']=latticematrixa2 latticematrixa3=laticematrix[2] self._calculationValues['Lattice Matrix a3 in bohr']=latticematrixa3 self._calculationValues['Lattice Matrix in bohr'] = parser_outputd_handle['BR2_DIR Matrix'] self._calculationValues['Lattice Matrix in m'] = [[ bohrToMeters(i) for i in j ] for j in self._calculationValues['Lattice Matrix in bohr']] self._calculationValues['Number of Atoms in Unit Cell'] = parser_outputd_handle['Number of Atoms in Unit Cell'] self._calculationValues['Lattice Constants in bohr'] = parser_outputd_handle['Lattice Constants'] self._calculationValues['Lattice Constants in m'] = [ bohrToMeters(i) for i in self._calculationValues['Lattice Constants in bohr']] #### *.outputst handle # for each element: # - Core Value # - Spin Value 1 # - Spin Value 2 self._calculationValues['Element Listing'] = parser_outputst_handle['Element List'] #### #### PATHPHASE #### #*.pathphases parsers #get text strings from each file phaseFilesList = [ arguments['file_pathphase_x'], arguments['file_pathphase_y'], arguments['file_pathphase_z'], ] #read from files phaseTextStringsList = [ open(i,'r').readlines() for i in phaseFilesList ] #parse the values phaseValues = [ b_PyParse.MainPathphaseParser(i) for i in phaseTextStringsList ] for i in phaseValues: i.parse() #send to pathphasecalculation for correction phaseObjects = [ PathphaseCalculation(values=i['values']) for i in phaseValues ] #receive mean values value_phaseCorrectedValues = [ i.getCorrectedValues() for i in phaseObjects ] self.value_phaseMeanValues = value_phaseMeanValues = [ i.getMeanValue() for i in phaseObjects ] #print self.value_phaseMeanValues #constants #electron charge / unit volume self.ELEC_BY_VOL_CONST = ELECTRON_CHARGE / bohrToMeters(self._calculationValues['Cell Volume in bohr^3'], dimension = 3.) #perform necessary calculations self.determineElectronPolarization() self.determineIonPolarization() self.calculateNetPolarizationEnergy()
def __init__(self, **arguments): ############################ ######### PARSING ########## ############################ ###Rest of the Files### #parse all the things! #### *.struct file parser parser_struct_handle = open(arguments['file_struct'], 'r').readlines() parser_struct_handle = b_PyParse.MainStructParser(parser_struct_handle) parser_struct_handle.parse() #### *.scf file parser parser_scf_handle = open(arguments['file_scf'], 'r').readlines() parser_scf_handle = b_PyParse.MainSCFParser(parser_scf_handle) parser_scf_handle.parse() #### *.outputd parser parser_outputd_handle = open(arguments['file_outputd'], 'r').readlines() parser_outputd_handle = b_PyParse.MainOutputDParser( parser_outputd_handle) parser_outputd_handle.parse() #### *.outputst parser parser_outputst_handle = open(arguments['file_outputst'], 'r').readlines() parser_outputst_handle = b_PyParse.MainOutputstParser( parser_outputst_handle) parser_outputst_handle.parse() ##################################### ############ END Parsing ############ ##################################### ############################# ###### Getting Values ####### ############################# self._calculationValues = orderedDict() #### *.struct handle # - determine name of atoms # - determine MULT for each atom self._calculationValues['Atom Listing'] = parser_struct_handle[ 'Atom Listing'] #### *.scf handle # - Cell Volume self._calculationValues['Cell Volume in bohr^3'] = parser_scf_handle[ 'Cell Volume'] self._calculationValues['Cell Volume in m^3'] = bohrToMeters( self._calculationValues['Cell Volume in bohr^3'], 3) #### *.outputd handle # - BR2_DIR matrix (v_x, v_y, v_z) # - number of atoms in cell # - Lattice Constants (x,y,z) laticematrix = parser_outputd_handle['BR2_DIR Matrix'] latticematrixa1 = laticematrix[0] self._calculationValues['Lattice Matrix a1 in bohr'] = latticematrixa1 latticematrixa2 = laticematrix[1] self._calculationValues['Lattice Matrix a2 in bohr'] = latticematrixa2 latticematrixa3 = laticematrix[2] self._calculationValues['Lattice Matrix a3 in bohr'] = latticematrixa3 self._calculationValues[ 'Lattice Matrix in bohr'] = parser_outputd_handle['BR2_DIR Matrix'] self._calculationValues['Lattice Matrix in m'] = [[ bohrToMeters(i) for i in j ] for j in self._calculationValues['Lattice Matrix in bohr']] self._calculationValues[ 'Number of Atoms in Unit Cell'] = parser_outputd_handle[ 'Number of Atoms in Unit Cell'] self._calculationValues[ 'Lattice Constants in bohr'] = parser_outputd_handle[ 'Lattice Constants'] self._calculationValues['Lattice Constants in m'] = [ bohrToMeters(i) for i in self._calculationValues['Lattice Constants in bohr'] ] #### *.outputst handle # for each element: # - Core Value # - Spin Value 1 # - Spin Value 2 self._calculationValues['Element Listing'] = parser_outputst_handle[ 'Element List'] #### #### PATHPHASE #### #*.pathphases parsers #get text strings from each file phaseFilesList = [ arguments['file_pathphase_x'], arguments['file_pathphase_y'], arguments['file_pathphase_z'], ] #read from files phaseTextStringsList = [ open(i, 'r').readlines() for i in phaseFilesList ] #parse the values phaseValues = [ b_PyParse.MainPathphaseParser(i) for i in phaseTextStringsList ] for i in phaseValues: i.parse() #send to pathphasecalculation for correction self.phaseValues = phaseValues phaseObjects = [ PathphaseCalculation(values=i['values']) for i in phaseValues ] self.value_phaseConsistentDomainValues = [ i.getConsistentDomainValues() for i in phaseObjects ] self.value_phaseConsistentDomainValues2 = [ i.getConsistentDomainValues2() for i in phaseObjects ] self.value_phaseCorrectedValues = [ i.getCorrectedValues() for i in phaseObjects ] self.value_phaseCorrectedValues2 = [ i.getCorrectedValues2() for i in phaseObjects ] #receive mean values self.value_phaseMeanValues = value_phaseMeanValues = [ i.getMeanValue() for i in phaseObjects ] #constants #electron charge / unit volume self.ELEC_BY_VOL_CONST = ELECTRON_CHARGE / bohrToMeters( self._calculationValues['Cell Volume in bohr^3'], dimension=3.) #perform necessary calculations self.determineElectronPolarization() self.determineIonPolarization() self.calculateNetPolarizationEnergy()
def wordlist(self): print(self.words) def getWC(self,findwords): for word in findwords: self.count=0 for w in self.words: if w==word: self.count+=1 #print('Occurence of ',word,' in the file is ',self.count) self.worddict[word] = self.count return self.worddict t = TextReader('E:\\Documents\\PythonProjects\\1_Basics\\DataForFiles\\file1.txt') #print(t.text) #print(t.lines) #print(t.wordcount) #t.display() t.wordlist() # Sorting the given elements in the alphabetic order import collections print("words and their counnts in the sorted order : ") x=t.words od = collections.orderedDict(sorted(t.getWC(x).items())) print(od)
def __init__(self, **args): # spin polarization: yes/no spCalc = args['sp'] ############################ ######### PARSING ########## ############################ ###Rest of the Files### #parse all the things! #### *.struct file parser parser_struct_handle = open(args['file_struct'], 'r').readlines() parser_struct_handle = b_PyParse.MainStructParser(parser_struct_handle) parser_struct_handle.parse() #### *.scf file parser parser_scf_handle = open(args['file_scf'], 'r').readlines() parser_scf_handle = b_PyParse.MainSCFParser(parser_scf_handle) parser_scf_handle.parse() #### *.outputd parser parser_outputd_handle = open(args['file_outputd'], 'r').readlines() parser_outputd_handle = b_PyParse.MainOutputDParser( parser_outputd_handle) parser_outputd_handle.parse() #### *.outputst parser parser_outputst_handle = open(args['file_outputst'], 'r').readlines() parser_outputst_handle = b_PyParse.MainOutputstParser( parser_outputst_handle) parser_outputst_handle.parse() ##################################### ############ END Parsing ############ ##################################### ############################# ###### Getting Values ####### ############################# self._calculationValues = orderedDict() #### *.struct handle # - determine name of atoms # - determine MULT for each atom self._calculationValues['Atom Listing'] = \ parser_struct_handle['Atom Listing'] #### *.scf handle # - Cell Volume self._calculationValues['Cell Volume in bohr^3'] = \ parser_scf_handle['Cell Volume'] self._calculationValues['Cell Volume in m^3'] = \ bohrToMeters(self._calculationValues['Cell Volume in bohr^3'],3) #### *.outputd handle # - BR2_DIR matrix (v_x, v_y, v_z) # - number of atoms in cell # - Lattice Constants (x,y,z) laticematrix = parser_outputd_handle['BR2_DIR Matrix'] latticematrixa1 = laticematrix[0] self._calculationValues['Lattice Matrix a1 in bohr'] = \ latticematrixa1 latticematrixa2 = laticematrix[1] self._calculationValues['Lattice Matrix a2 in bohr'] = \ latticematrixa2 latticematrixa3 = laticematrix[2] self._calculationValues['Lattice Matrix a3 in bohr'] = \ latticematrixa3 self._calculationValues['Lattice Matrix in bohr'] = \ parser_outputd_handle['BR2_DIR Matrix'] self._calculationValues['Lattice Matrix in m'] = \ [[ bohrToMeters(i) for i in j ] for j in \ self._calculationValues['Lattice Matrix in bohr']] self._calculationValues['Number of Atoms in Unit Cell'] = \ parser_outputd_handle['Number of Atoms in Unit Cell'] self._calculationValues['Lattice Constants in bohr'] = \ parser_outputd_handle['Lattice Constants'] self._calculationValues['Lattice Constants in m'] = \ [ bohrToMeters(i) for i in \ self._calculationValues['Lattice Constants in bohr']] #### *.outputst handle # for each element: # - Core Value # - Spin Value 1 # - Spin Value 2 self._calculationValues['Element Listing'] = \ parser_outputst_handle['Element List'] #### ######################## # get electronic phase # ######################## # get raw list [k-points, phase] phaseDirSpinPathRaw = args['phases'] # wrap phases in the range [-pi ... +pi] phaseDirSpinPathWrp11 = self.wrpPhase(phaseDirSpinPathRaw, \ self.wrp11) # print nice print "\n","Initial Berry phases and their", \ "wrapped values in the range [-pi ... +pi]" print "=" * 87 print " "*30, "| init k-point", "| phase raw (rad)", \ "| phase wrap. (rad)" icoord = -1 for coord in phaseDirSpinPathRaw: icoord += 1 print "-" * 87 print "direction(%u)" % int(icoord + 1) ispin = -1 for spin in coord: ispin += 1 print " " * 12, "spin(%u)" % int(ispin + 1) ipath = -1 for path in spin: ipath += 1 # perform wraping using the method privided in input kpt = phaseDirSpinPathRaw[icoord][ispin][ipath][0] ph = phaseDirSpinPathRaw[icoord][ispin][ipath][1] phwrp = phaseDirSpinPathWrp11[icoord][ispin][ipath][1] print " "*20, "path(%4d) %4d % e % e" \ % (ipath+1, kpt, ph, phwrp) print "=" * 87 print "\n", "CALCULATION OF ELECTRONIC POLARIZATION" print "=" * 87 print "Value", " "*25, "| spin ", "| ", "dir(1) ", \ "| ", "dir(2) ", "| ", "dir(3)" print "-" * 87 # find path-average phase phaseDirSpinWrp11 = self.pathAvrgPhase(phaseDirSpinPathWrp11) # wrap the average phase again as it can go out of bounds [-pi..+pi] phaseDirSpinWrp11 = self.wrp11(phaseDirSpinWrp11) nspins = numpy.shape(phaseDirSpinWrp11)[1] for spinIndex in range(0, nspins): print "Berry phase (rad) [-pi ... +pi] sp(%1i)" \ % (spinIndex+1), \ " [% e, % e, % e]" % tuple(phaseDirSpinWrp11[:,spinIndex]) if not spCalc and not args[ 'so']: # in case of non-SP or non-SO calculation... phaseDirSpinWrp11 = 2 * phaseDirSpinWrp11 # account for the spin degeneracy nspins = numpy.shape(phaseDirSpinWrp11)[1] if nspins != 1: # double check print "Inconsistency detected in the number of spins" print "Is it spin-polarized calculation? spCalc =", spCalc print "Number of spins in the electronic phase array", \ nspins print "Expected 1 spin" print "Decision is taken to EXIT" sys.exit(2) print "Berry phase (rad) up+dn "+ \ "[% e, % e, % e]" % tuple(phaseDirSpinWrp11) # wrap phases again [-pi ... +pi] phaseDirSpinWrp11 = self.wrp11(phaseDirSpinWrp11) print "Berry phase (rad) [-pi ... +pi] " +\ " up+dn [% e, % e, % e]" \ % tuple(phaseDirSpinWrp11) #electron charge / cell volume self.ELEC_BY_VOL_CONST = ELECTRON_CHARGE / \ bohrToMeters(self._calculationValues['Cell Volume in bohr^3'], \ dimension = 3.) # electronic polarization (C/m2) elP = self.elPolarization(phaseDirSpinWrp11,self._calculationValues, \ self.ELEC_BY_VOL_CONST) # ionic polarization (C/m2) ionP = self.determineIonPolarization(self.wrp11, args) # Total polarization (C/m2) will be returned # when calling mainCalculation() self._totalPolarizationVal = self.totalPolarization(elP, ionP)
import statistics statistics.mean ([3, 5, 7, 10]) statistics.median ([3, 5, 7, 10]) statistics.mode ([3, 5, 7, 7, 10]) #most common value #collections and namedtuple import collections player = collections.namedtuple ("player", ["name", "age", "team"]) p1 = player ("Salah", 27, "Egypt") print(p1.name) print(p1.age) print.(p1.team) #collections and ordered dict dict1 = collections.orderedDict() dict1["First:"] = 35 dict1["Second:"] = 40 dict1["Third:"] = 45 dict1["Fourth:"] = 50 for k,v in dict.items(): # k=key v=value print(k,v) #deque function dq = collections.deque ([20, 25, 30, 35]) dq.appendleft(15) dq.appendright(40) q.pop() q.popleft q.popright
def __init__(self, **args): # spin polarization: yes/no spCalc = args['sp'] ############################ ######### PARSING ########## ############################ ###Rest of the Files### #parse all the things! #### *.struct file parser parser_struct_handle = open(args['file_struct'], 'r').readlines() parser_struct_handle = b_PyParse.MainStructParser(parser_struct_handle) parser_struct_handle.parse() #### *.inc parser parser_inc_handle = open(args['file_inc'], 'r').readlines() parser_inc_handle = b_PyParse.MainIncParser(parser_inc_handle) parser_inc_handle.parse() ##################################### ############ END Parsing ############ ##################################### ############################# ###### Getting Values ####### ############################# self.calcVal = orderedDict() #### *.struct handle # - name of atoms # - MULT for each atom # - coordinates # - nuclear charge self.calcVal['Atom Listing'] = \ parser_struct_handle['Atom Listing'] # - lattice type (P,F,B,CXY,CYZ,CXZ,R,H) self.calcVal['lattice type'] = \ parser_struct_handle['lattice type'] # - lattice orthogonal (T/F) self.calcVal['lattice ortho'] = \ parser_struct_handle['lattice ortho'] # - Cell Volume self.calcVal['Cell Volume in bohr^3'] = \ parser_struct_handle['cell volume'] # - Lattice Constants (a,b,c) self.calcVal['Lattice Constants in bohr'] = \ parser_struct_handle['lattice constants'] # - lattice vectors BR1_DIR matrix (v_x, v_y, v_z) self.calcVal['Real conventional lat vectors in bohr'] = \ parser_struct_handle['real space conventional lattice vectors'] # - lattice vectors BR2_DIR matrix (v_x, v_y, v_z) self.calcVal['Real primitive lat vectors in bohr'] = \ parser_struct_handle['real space primitive lattice vectors'] ### *.inc handle # - core charge for each non-eqivalent atom self.calcVal['Atom core charges'] = \ parser_inc_handle['core charges'] # check consistency of case.struct and case.inc files if len(self.calcVal['Atom core charges']) != \ len(self.calcVal['Atom Listing']): print("Number of non-equivalent atoms in case.struct:", \ len(self.calcVal['Atom Listing'])) print("Number of non-equivalent atoms in case.inc:", \ len(self.calcVal['Atom core charges'])) raise Exception("Inconsistent number of non-equivalent atoms") # list of pi-wrapping functions that will be applied to wrap the phase wrpFnList = [self.wrp02, self.wrp11] for wrpFn in wrpFnList: # iterate over various wrapping functions if wrpFn == self.wrp11: print("\n\n~~~~~~~~~~~~~~~~~~~~ " +\ "phases are wrapped in the range [-pi .. +pi]" +\ " ~~~~~~~~~~~~~~~~~~~~~~") elif wrpFn == self.wrp02: print("\n\n~~~~~~~~~~~~~~~~~~~~ " +\ "phases are wrapped in the range [0 .. +2pi] " +\ " ~~~~~~~~~~~~~~~~~~~~~") ######################## # get electronic phase # ######################## # get raw list [k-points, phase] phaseDirSpinPathRaw = args['phases'] # wrap phases in the range [-pi ... +pi] phaseDirSpinPathWrp = self.wrpPhase(phaseDirSpinPathRaw, \ wrpFn) # print nice print("\n","Initial Berry phases and their", \ "wrapped values") print("=" * 87) print(" "*30, "| init k-point", "| phase raw (rad)", \ "| phase wrap. (rad)") icoord = -1 for coord in phaseDirSpinPathRaw: icoord += 1 print("-" * 87) print("direction(%u)" % int(icoord + 1)) ispin = -1 for spin in coord: ispin += 1 print(" " * 12, "spin(%u)" % int(ispin + 1)) ipath = -1 for path in spin: ipath += 1 # perform wraping using the method privided in input kpt = phaseDirSpinPathRaw[icoord][ispin][ipath][0] ph = phaseDirSpinPathRaw[icoord][ispin][ipath][1] phwrp = phaseDirSpinPathWrp[icoord][ispin][ipath][1] print(" "*20, "path(%4d) %4d % e % e" \ % (ipath+1, kpt, ph, phwrp)) print("=" * 87) print("\n\nCALCULATION OF ELECTRONIC POLARIZATION",\ "(primitive lattice coordinates)") print("=" * 87) print("Value", " "*25, "| spin ", "| ", "dir(1) ", \ "| ", "dir(2) ", "| ", "dir(3)") print("-" * 87) # find path-average phase phaseDirSpinWrp = self.pathAvrgPhase(phaseDirSpinPathWrp) # wrap the average phase again as it can go out of bounds [-pi..+pi] phaseDirSpinWrp = wrpFn(phaseDirSpinWrp) nspins = numpy.shape(phaseDirSpinWrp)[1] for spinIndex in range(0, nspins): print("Berry phase wrapped (rad) sp(%1i)" \ % (spinIndex+1), \ " [% e, % e, % e]" % tuple(phaseDirSpinWrp[:,spinIndex])) if not spCalc and not args[ 'so']: # in case of non-SP or non-SO calculation... phaseDirSpinWrp = 2 * phaseDirSpinWrp # account for the spin degeneracy nspins = numpy.shape(phaseDirSpinWrp)[1] if nspins != 1: # double check print("Inconsistency detected in the number of spins") print("Is it spin-polarized calculation? spCalc =", spCalc) print("Number of spins in the electronic phase array", \ nspins) print("Expected 1 spin") print("Decision is taken to EXIT") sys.exit(2) print("Berry phase (rad) up+dn "+ \ "[% e, % e, % e]" % tuple(phaseDirSpinWrp)) # wrap phases again [-pi ... +pi] phaseDirSpinWrp = wrpFn(phaseDirSpinWrp) print("Berry phase wrapped (rad)" +\ " up+dn [% e, % e, % e]" \ % tuple(phaseDirSpinWrp)) #electron charge / cell volume self.ELEC_BY_VOL_CONST = ELECTRON_CHARGE / \ bohrToMeters(self.calcVal['Cell Volume in bohr^3'], \ dimension = 3.) # electronic polarization (C/m2) elP = self.elPolarization(phaseDirSpinWrp,self.calcVal, \ self.ELEC_BY_VOL_CONST) # convert elP from primitive basis to Cart. coordinates # WIEN2k always uses primitive latt. vec. in constructing Brillouin zone print("\nThe electronic polarization vector is presented in",\ "this coord. system:") latVec = numpy.zeros((3, 3)) for i in range(3): # gather lattice vectors into a (3x3) array latVec[i, :] = self.calcVal[ 'Real primitive lat vectors in bohr'][i] print(" "*4, "dir(%1i) =" % (i+1), \ "[% e, % e, % e] bohr" % tuple(latVec[i,:])) print("and will be transformed into Cartesian coordinates.") for i in range(elP.shape[0]): # loop over spin channels elP[i, :] = vec2cart(elP[i, :], latVec) # prim -> Cartesian ############################# # ionic polarization (C/m2) # ############################# ionP = self.determineIonPolarization(wrpFn, args) # convert ionP from conventional to Cart. coordinates # WIEN2k always uses conventional latt. vec. for ionic positions print("\nThe ionic positions and associated polarization vector is",\ "presented in this coord. system:") latVec = numpy.zeros((3, 3)) for i in range(3): # gather lattice vectors into a (3x3) array latVec[i, :] = self.calcVal[ 'Real conventional lat vectors in bohr'][i] print(" "*4, "dir(%1i) =" % (i+1), \ "[% e, % e, % e] bohr" % tuple(latVec[i,:])) for i in range(ionP.shape[0]): # loop over spin channels ionP[i, :] = vec2cart(ionP[i, :], latVec) # conventional -> Cartesian ############################# # total polarization (C/m2) # ############################# # Total polarization (C/m2) will be returned # when calling mainCalculation() self._totalPolarizationVal = self.totalPolarization(elP, ionP) # Prepare transform polarization from lattice vectors to Cartesian # coordinates (totP -> totPcart latVec = numpy.zeros((3, 3)) # END iterate over various wrapping functions print(''' Notes: (1) When lattice vectors are _not_ aligned with Cartesian coordinates, an additional transformation is required to present the polarization vector in Cartesian coordinates. This can be important when calculating Born effective charges Z*_i,j = (Omega/e) * dP_i/dr_j, where i, j are Cartesian components, Omega is the cell volume (see output above), and e is the elementary charge. The total polarization vector is presented in Cartesian coordinates and should be used to determine dP_i. It is, however, up to the user to transform the atom displacement vector components dr_j into Cartesian coordinates. The change in fractional coordinated should be converted into dr_j using lattice vectors dir(1,2,3) used in calculation of the ionic polarization (see above). An Octave/Matlab sctipt can be found in https://github.com/spichardo/BerryPI/wiki/Tutorial-3:-Non-orthogonal-lattice-vectors (2) Results are presented for two pi-wrapping options [-pi .. +pi] and [0 .. +2pi] separated by ~~~~~~. It is designed to assist in situations when a sudden change in the Berry phase (and associated polarization) occurs due to a pi-wrapping artefact (see discussion pertaining Fig. 2 in Ref. [1]). It is up to the user to select the most relevant option. This decision should be made based on comparing results for _two_ different structures. The goal is to ensure a smooth change in the phase in response to a small perturbation.''')
def __init__(self, **args): # spin polarization: yes/no spCalc = args['sp'] ############################ ######### PARSING ########## ############################ ###Rest of the Files### #parse all the things! #### *.struct file parser parser_struct_handle = open(args['file_struct'], 'r').readlines() parser_struct_handle = b_PyParse.MainStructParser(parser_struct_handle) parser_struct_handle.parse() #### *.scf file parser parser_scf_handle = open(args['file_scf'], 'r').readlines() parser_scf_handle = b_PyParse.MainSCFParser(parser_scf_handle) parser_scf_handle.parse() #### *.outputd parser parser_outputd_handle = open(args['file_outputd'], 'r').readlines() parser_outputd_handle = b_PyParse.MainOutputDParser(parser_outputd_handle) parser_outputd_handle.parse() #### *.outputst parser parser_outputst_handle = open(args['file_outputst'], 'r').readlines() parser_outputst_handle = b_PyParse.MainOutputstParser(parser_outputst_handle) parser_outputst_handle.parse() ##################################### ############ END Parsing ############ ##################################### ############################# ###### Getting Values ####### ############################# self._calculationValues = orderedDict(); #### *.struct handle # - determine name of atoms # - determine MULT for each atom self._calculationValues['Atom Listing'] = \ parser_struct_handle['Atom Listing']; #### *.scf handle # - Cell Volume self._calculationValues['Cell Volume in bohr^3'] = \ parser_scf_handle['Cell Volume']; self._calculationValues['Cell Volume in m^3'] = \ bohrToMeters(self._calculationValues['Cell Volume in bohr^3'],3); #### *.outputd handle # - BR2_DIR matrix (v_x, v_y, v_z) # - number of atoms in cell # - Lattice Constants (x,y,z) laticematrix=parser_outputd_handle['BR2_DIR Matrix'] latticematrixa1=laticematrix[0] self._calculationValues['Lattice Matrix a1 in bohr'] = \ latticematrixa1; latticematrixa2=laticematrix[1] self._calculationValues['Lattice Matrix a2 in bohr'] = \ latticematrixa2; latticematrixa3=laticematrix[2] self._calculationValues['Lattice Matrix a3 in bohr'] = \ latticematrixa3; self._calculationValues['Lattice Matrix in bohr'] = \ parser_outputd_handle['BR2_DIR Matrix']; self._calculationValues['Lattice Matrix in m'] = \ [[ bohrToMeters(i) for i in j ] for j in \ self._calculationValues['Lattice Matrix in bohr']]; self._calculationValues['Number of Atoms in Unit Cell'] = \ parser_outputd_handle['Number of Atoms in Unit Cell']; self._calculationValues['Lattice Constants in bohr'] = \ parser_outputd_handle['Lattice Constants']; self._calculationValues['Lattice Constants in m'] = \ [ bohrToMeters(i) for i in \ self._calculationValues['Lattice Constants in bohr']]; #### *.outputst handle # for each element: # - Core Value # - Spin Value 1 # - Spin Value 2 self._calculationValues['Element Listing'] = \ parser_outputst_handle['Element List']; #### ######################## # get electronic phase # ######################## # get raw list [k-points, phase] phaseDirSpinPathRaw = args['phases'] # wrap phases in the range [-pi ... +pi] phaseDirSpinPathWrp11 = self.wrpPhase(phaseDirSpinPathRaw, \ self.wrp11); # print nice print "\n","Initial Berry phases and their", \ "wrapped values in the range [-pi ... +pi]"; print "="*87 print " "*30, "| init k-point", "| phase raw (rad)", \ "| phase wrap. (rad)" icoord = -1 for coord in phaseDirSpinPathRaw: icoord += 1 print "-"*87 print "direction(%u)" % int(icoord + 1) ispin = -1 for spin in coord: ispin += 1 print " "*12, "spin(%u)" % int(ispin + 1) ipath = -1 for path in spin: ipath += 1 # perform wraping using the method privided in input kpt = phaseDirSpinPathRaw[icoord][ispin][ipath][0] ph = phaseDirSpinPathRaw[icoord][ispin][ipath][1] phwrp = phaseDirSpinPathWrp11[icoord][ispin][ipath][1] print " "*20, "path(%4d) %4d % e % e" \ % (ipath+1, kpt, ph, phwrp) print "="*87 print "\n","CALCULATION OF ELECTRONIC POLARIZATION" print "="*87 print "Value", " "*25, "| spin ", "| ", "dir(1) ", \ "| ", "dir(2) ", "| ", "dir(3)" print "-"*87 # find path-average phase phaseDirSpinWrp11 = self.pathAvrgPhase(phaseDirSpinPathWrp11); # wrap the average phase again as it can go out of bounds [-pi..+pi] phaseDirSpinWrp11 = self.wrp11(phaseDirSpinWrp11); nspins = numpy.shape(phaseDirSpinWrp11)[1] for spinIndex in range(0,nspins): print "Berry phase (rad) [-pi ... +pi] sp(%1i)" \ % (spinIndex+1), \ " [% e, % e, % e]" % tuple(phaseDirSpinWrp11[:,spinIndex]); if not spCalc and not args['so']: # in case of non-SP or non-SO calculation... phaseDirSpinWrp11 = 2*phaseDirSpinWrp11 # account for the spin degeneracy nspins = numpy.shape(phaseDirSpinWrp11)[1] if nspins != 1: # double check print "Inconsistency detected in the number of spins" print "Is it spin-polarized calculation? spCalc =", spCalc print "Number of spins in the electronic phase array", \ nspins; print "Expected 1 spin" print "Decision is taken to EXIT" sys.exit(2) print "Berry phase (rad) up+dn "+ \ "[% e, % e, % e]" % tuple(phaseDirSpinWrp11); # wrap phases again [-pi ... +pi] phaseDirSpinWrp11 = self.wrp11(phaseDirSpinWrp11) print "Berry phase (rad) [-pi ... +pi] " +\ " up+dn [% e, % e, % e]" \ % tuple(phaseDirSpinWrp11); #electron charge / cell volume self.ELEC_BY_VOL_CONST = ELECTRON_CHARGE / \ bohrToMeters(self._calculationValues['Cell Volume in bohr^3'], \ dimension = 3.); # electronic polarization (C/m2) elP = self.elPolarization(phaseDirSpinWrp11,self._calculationValues, \ self.ELEC_BY_VOL_CONST); # ionic polarization (C/m2) ionP = self.determineIonPolarization(self.wrp11,args) # Total polarization (C/m2) will be returned # when calling mainCalculation() self._totalPolarizationVal = self.totalPolarization(elP, ionP)
def __init__(self, **args): # spin polarization: yes/no spCalc = args['sp'] ############################ ######### PARSING ########## ############################ ###Rest of the Files### #parse all the things! #### *.struct file parser parser_struct_handle = open(args['file_struct'], 'r').readlines() parser_struct_handle = b_PyParse.MainStructParser(parser_struct_handle) parser_struct_handle.parse() #### *.inc parser parser_inc_handle = open(args['file_inc'], 'r').readlines() parser_inc_handle = b_PyParse.MainIncParser(parser_inc_handle) parser_inc_handle.parse() ##################################### ############ END Parsing ############ ##################################### ############################# ###### Getting Values ####### ############################# self._calculationValues = orderedDict() #### *.struct handle # - name of atoms # - MULT for each atom # - coordinates # - nuclear charge self._calculationValues['Atom Listing'] = \ parser_struct_handle['Atom Listing'] # - Cell Volume self._calculationValues['Cell Volume in bohr^3'] = \ parser_struct_handle['cell volume'] # - Lattice Constants (a,b,c) self._calculationValues['Lattice Constants in bohr'] = \ parser_struct_handle['lattice constants'] # - lattice vectors BR2_DIR matrix (v_x, v_y, v_z) self._calculationValues['Lattice Matrix in bohr'] = \ parser_struct_handle['real space lattice vectors'] ### *.inc handle # - core charge for each non-eqivalent atom self._calculationValues['Atom core charges'] = \ parser_inc_handle['core charges'] # check consistency of case.struct and case.inc files if len(self._calculationValues['Atom core charges']) != \ len(self._calculationValues['Atom Listing']): print("Number of non-equivalent atoms in case.struct:", \ len(self._calculationValues['Atom Listing'])) print("Number of non-equivalent atoms in case.inc:", \ len(self._calculationValues['Atom core charges'])) raise Exception("Inconsistent number of non-equivalent atoms") ######################## # get electronic phase # ######################## # get raw list [k-points, phase] phaseDirSpinPathRaw = args['phases'] # wrap phases in the range [-pi ... +pi] phaseDirSpinPathWrp11 = self.wrpPhase(phaseDirSpinPathRaw, \ self.wrp11) # print nice print("\n","Initial Berry phases and their", \ "wrapped values in the range [-pi ... +pi]") print("=" * 87) print(" "*30, "| init k-point", "| phase raw (rad)", \ "| phase wrap. (rad)") icoord = -1 for coord in phaseDirSpinPathRaw: icoord += 1 print("-" * 87) print("direction(%u)" % int(icoord + 1)) ispin = -1 for spin in coord: ispin += 1 print(" " * 12, "spin(%u)" % int(ispin + 1)) ipath = -1 for path in spin: ipath += 1 # perform wraping using the method privided in input kpt = phaseDirSpinPathRaw[icoord][ispin][ipath][0] ph = phaseDirSpinPathRaw[icoord][ispin][ipath][1] phwrp = phaseDirSpinPathWrp11[icoord][ispin][ipath][1] print(" "*20, "path(%4d) %4d % e % e" \ % (ipath+1, kpt, ph, phwrp)) print("=" * 87) print("\n", "CALCULATION OF ELECTRONIC POLARIZATION") print("=" * 87) print("Value", " "*25, "| spin ", "| ", "dir(1) ", \ "| ", "dir(2) ", "| ", "dir(3)") print("-" * 87) # find path-average phase phaseDirSpinWrp11 = self.pathAvrgPhase(phaseDirSpinPathWrp11) # wrap the average phase again as it can go out of bounds [-pi..+pi] phaseDirSpinWrp11 = self.wrp11(phaseDirSpinWrp11) nspins = numpy.shape(phaseDirSpinWrp11)[1] for spinIndex in range(0, nspins): print("Berry phase (rad) [-pi ... +pi] sp(%1i)" \ % (spinIndex+1), \ " [% e, % e, % e]" % tuple(phaseDirSpinWrp11[:,spinIndex])) if not spCalc and not args[ 'so']: # in case of non-SP or non-SO calculation... phaseDirSpinWrp11 = 2 * phaseDirSpinWrp11 # account for the spin degeneracy nspins = numpy.shape(phaseDirSpinWrp11)[1] if nspins != 1: # double check print("Inconsistency detected in the number of spins") print("Is it spin-polarized calculation? spCalc =", spCalc) print("Number of spins in the electronic phase array", \ nspins) print("Expected 1 spin") print("Decision is taken to EXIT") sys.exit(2) print("Berry phase (rad) up+dn "+ \ "[% e, % e, % e]" % tuple(phaseDirSpinWrp11)) # wrap phases again [-pi ... +pi] phaseDirSpinWrp11 = self.wrp11(phaseDirSpinWrp11) print("Berry phase (rad) [-pi ... +pi] " +\ " up+dn [% e, % e, % e]" \ % tuple(phaseDirSpinWrp11)) #electron charge / cell volume self.ELEC_BY_VOL_CONST = ELECTRON_CHARGE / \ bohrToMeters(self._calculationValues['Cell Volume in bohr^3'], \ dimension = 3.) # electronic polarization (C/m2) elP = self.elPolarization(phaseDirSpinWrp11,self._calculationValues, \ self.ELEC_BY_VOL_CONST) # ionic polarization (C/m2) ionP = self.determineIonPolarization(self.wrp11, args) # Total polarization (C/m2) will be returned # when calling mainCalculation() self._totalPolarizationVal = self.totalPolarization(elP, ionP)