def difference_this(file_zero_abs, wave, output_file_name): ''' given the three paths, this will create the difference in wavepacket ''' zero = readWholeH5toDict(file_zero_abs) other = readWholeH5toDict(wave) zero_wf = zero['WF'] other_wf = other['WF'] zero_time = zero['Time'] other_time = other['Time'] zero_pop = qp.abs2(zero_wf) other_pop = qp.abs2(other_wf) difference = zero_pop - other_pop outputDict = {'WF': difference, 'Time0': zero_time, 'Time1': other_time} print('{} cube is done: {} {}'.format(os.path.basename(wave), np.amax(difference), np.amin(difference))) qp.writeH5fileDict(output_file_name, outputDict)
def correctThis(elem, oneDarray, rootNameE, rootNameO, cutAt, first=None): ''' This is the corrector. Go go go elem :: String <- the label of the h5 file oneDarray :: np.array(NSTATES) <- this is the 1D vector that tells us how sign changed in LAST CALCULATION ''' first = first or False dataToGet = ['ROOT_ENERGIES', 'OVERLAP', 'DIPOLES', 'NAC'] fileN = rootNameO + elem + '.all.h5' # I add a string LOL in front of elem to make it equal to a normal file name, but elem here # is just the three labels (small dirty fix) # stringTransformation3d changes the UNITS of the labels, it is not anymore a simple tofloat phiA, _, gammaA, _, thetA, _ = stringTransformation3d("LOL_" + elem) [enerAll, overlapsM, dipolesAll, nacAll] = retrieve_hdf5_data(fileN, dataToGet) if first: (_, nstates, _) = dipolesAll.shape overlapsAll = np.identity(nstates) else: (nstates, _) = overlapsM.shape overlapsAll = overlapsM # leave this here for now nacCUT = 8 # let's cut something energies = enerAll[:cutAt] dipoles = dipolesAll[:, :cutAt, :cutAt] overlaps = overlapsAll[:cutAt, :cutAt] nacs = nacAll[:nacCUT, :nacCUT] correctionArray1DABS, overlap_one_zero = createOneAndZero( overlaps, oneDarray) correctionMatrix = createTabellineFromArray(correctionArray1DABS) new_dipoles = dipoles * correctionMatrix # here I use the fact that correctionMatrix is ALWAYS 2d # so I loop over the it new_nacs = np.empty_like(nacs) for i in range(nacCUT): for j in range(nacCUT): new_nacs[i, j] = nacs[i, j] * correctionMatrix[i, j] print('\n') print('This is overlap:') printMatrix2D(overlaps, 2) print('\n\n') print('from Previous\n {}\neffective correction:\n {}'.format( oneDarray, correctionArray1DABS)) print('\n\n') print('this is correction Matrix') printMatrix2D(correctionMatrix, 2) print('\n\n') print('These are the old dipoles:') printMatrix2D(dipoles[0], 2) print('\n\n') print('These are the new dipoles:') printMatrix2D(new_dipoles[0], 2) print('\n\n') print('These are the old NACS:') printMatrix2D(nacs[:, :, 9, 1], 2) print('\n\n') print('These are the new NACS:') printMatrix2D(new_nacs[:, :, 9, 1], 2) # file handling corrFNO = rootNameE + elem + '.corrected.h5' allValues = readWholeH5toDict(fileN) allValues['DIPOLES'] = new_dipoles allValues['NAC'] = new_nacs allValues['ABS_CORRECTOR'] = correctionArray1DABS allValues['OVERLAPONEZERO'] = overlap_one_zero allValues['KINETIC_COEFFICIENTS'] = calc_g_G(phiA, gammaA, thetA) allValues['ROOT_ENERGIES'] = energies writeH5fileDict(corrFNO, allValues) print('\n\nfile {} written'.format(corrFNO))
def refineStuffs(folderO, folderE, folderOUTPUT, fn1, fn2): ''' There is a folder, folderO, where there are NAC calculated but the dipoles are not corrected. Then there is a folder folderE that has the correct dipoles, but nacs are 0. I use the sign of the dipoles in folderE to correct the NAC when putting them into the new grid ''' phis1, gammas1, thetas1 = readDirectionFile(fn1) phis2, gammas2, thetas2 = readDirectionFile(fn2) rootNameO = os.path.join(folderO, 'zNorbornadiene') rootNameE = os.path.join(folderE, 'zNorbornadiene') rootNameOut = os.path.join(folderOUTPUT, 'zNorbornadiene') flat_range_Phi = phis1[::-1] + phis2[1:] flat_range_Gamma = gammas1[::-1] + gammas2[1:] flat_range_Theta = (thetas1[::-1] + thetas2[1:])[::-1] print('{}\n{}\n{}\n'.format(flat_range_Phi, flat_range_Gamma, flat_range_Theta)) dataToGet = ['DIPOLES', 'NAC'] phiL = len(flat_range_Phi) gamL = len(flat_range_Gamma) debug = False for p, phiLab in enumerate(flat_range_Phi[:]): for g, gamLab in enumerate(flat_range_Gamma[:]): for t, theLab in enumerate(flat_range_Theta[:]): elemT = '{}_{}_{}'.format(phiLab, gamLab, theLab) THIS = '{}_{}.all.h5'.format(rootNameO, elemT) NEXT = '{}_{}.corrected.h5'.format(rootNameE, elemT) OUTN = '{}_{}.refined.h5'.format(rootNameOut, elemT) [dipolesAllT, nacAllT] = retrieve_hdf5_data(THIS, dataToGet) [dipolesAllN, nacAllN] = retrieve_hdf5_data(NEXT, dataToGet) _, nstates, _ = dipolesAllT.shape cutStates = 8 # I want out of diagonal pairs, so the double loop is correct like this, # where 0,0 and 1,1 and 2,2 are not taken and corrected. for i in range(cutStates): for j in range(i): uno = dipolesAllT[0, i, j] due = dipolesAllN[0, i, j] if debug: strin = '\np {} g {} t {} i {} j {} 1 {} 2 {}' print( strin.format(phiLab, gamLab, theLab, i, j, uno, due)) if np.sign(uno) == np.sign(due): nacAllN[i, j] = nacAllT[i, j] nacAllN[j, i] = -nacAllT[i, j] else: nacAllN[i, j] = -nacAllT[i, j] nacAllN[j, i] = nacAllT[i, j] # file handling allValues = readWholeH5toDict(NEXT) allValues['DIPOLES'] = dipolesAllN[:, :cutStates, :cutStates] allValues['NAC'] = nacAllN writeH5fileDict(OUTN, allValues) printProgressBar(p * gamL + g, gamL * phiL, prefix='H5 refined:')
def main(): ''' This will launch a 3d wavepacket propagation. ''' default = single_inputs(".", None) # input file inputs = read_single_arguments(default) fn = inputs.inputFile if os.path.exists(fn): ff = loadInputYAML(fn) inputAU = bring_input_to_AU(ff) # create subfolder name with yml file name filename, file_extension = os.path.splitext(fn) projfolder = os.path.join(inputAU['outFol'], filename) inputAU['outFol'] = projfolder print('\nNEW PROPAGATION') if inputs.restart != None: restart_folder = inputs.restart # read hdf5 input projfolder = os.path.abspath(restart_folder) h5_data_file = os.path.join(projfolder, 'allInput.h5') inputAU['outFol'] = projfolder dictionary_data = readWholeH5toDict(h5_data_file) restart_propagation(dictionary_data, inputAU) else: # not a restart if 'dataFile' in inputAU: # is there a data file? name_data_file = inputAU['dataFile'] # LAUNCH THE PROPAGATION, BITCH if name_data_file[-3:] == 'npy': data = np.load(name_data_file) # [()] <- because np.load returns a numpy wrapper on the dictionary dictionary_data = data[()] propagate3D(dictionary_data, inputAU) elif name_data_file[-3:] == 'kle': with open(name_data_file, "rb") as input_file: dictionary_data = pickle.load(input_file) propagate3D(dictionary_data, inputAU) else: # if not, guess you should create it... good('data file creation in progress...') phis, gams, thes = readDirections(inputAU['directions1'], inputAU['directions2']) # read the first one to understand who is the seed of the cube and take numbers phi1, gam1, the1 = readDirectionFile(inputAU['directions1']) ext = 'all.h5' ext = '.corrected.h5' ext = '.refined.h5' prjlab = inputAU['proj_label'] first_file = inputAU['proj_label'] + phi1[0] + '_' + gam1[ 0] + '_' + the1[0] + ext fnh5 = os.path.join(inputAU['inputFol'], first_file) nstates = len(retrieve_hdf5_data(fnh5, 'ROOT_ENERGIES')) natoms = len(retrieve_hdf5_data(fnh5, 'CENTER_COORDINATES')) lengths = '\nnstates: {}\nnatoms: {}\nphi: {}\ngamma: {}\ntheta: {}' phiL, gamL, theL = len(phis), len(gams), len(thes) output = lengths.format(nstates, natoms, phiL, gamL, theL) nacLength = 8 # start to allocate the vectors potCUBE = np.empty((phiL, gamL, theL, nacLength)) kinCUBE = np.empty((phiL, gamL, theL, 9, 3)) dipCUBE = np.empty((phiL, gamL, theL, 3, nacLength, nacLength)) geoCUBE = np.empty((phiL, gamL, theL, natoms, 3)) nacCUBE = np.empty( (phiL, gamL, theL, nacLength, nacLength, natoms, 3)) for p, phi in enumerate(phis): for g, gam in enumerate(gams): for t, the in enumerate(thes): labelZ = prjlab + phi + '_' + gam + '_' + the + ext fnh5 = os.path.join(inputAU['inputFol'], labelZ) if os.path.exists(fnh5): potCUBE[p, g, t] = retrieve_hdf5_data( fnh5, 'ROOT_ENERGIES')[:nacLength] kinCUBE[p, g, t] = retrieve_hdf5_data( fnh5, 'KINETIC_COEFFICIENTS') dipCUBE[p, g, t] = retrieve_hdf5_data( fnh5, 'DIPOLES') geoCUBE[p, g, t] = retrieve_hdf5_data( fnh5, 'CENTER_COORDINATES') nacCUBE[p, g, t] = retrieve_hdf5_data(fnh5, 'NAC') else: err('{} does not exist'.format(labelZ)) printProgressBar(p * gamL + g, phiL * gamL, prefix='H5 data loaded:') data = { 'kinCube': kinCUBE, 'potCube': potCUBE, 'dipCUBE': dipCUBE, 'geoCUBE': geoCUBE, 'nacCUBE': nacCUBE, 'phis': phis, 'gams': gams, 'thes': thes } np.save('data' + filename, data) with open(fn, 'a') as f: stringAdd = 'dataFile : data' + filename + '.npy' f.write(stringAdd) print('\n...done!\n') else: filename, file_extension = os.path.splitext(fn) if file_extension == '': fn = fn + '.yml' good('File ' + fn + ' does not exist. Creating a skel one') with open(fn, 'w') as f: f.write(defaultYaml)
def main(): ''' This will launch the postprocessing thing ''' a = read_single_arguments() folder_root = a.f folder_Gau = os.path.join(os.path.abspath(a.f), 'Gaussian') all_h5 = os.path.join(os.path.abspath(a.f), 'allInput.h5') output_of_Grid = os.path.join(os.path.abspath(a.f), 'output') output_of_this = os.path.join(os.path.abspath(a.f), 'Output_Abs') output_regions = os.path.join(os.path.abspath(a.f), 'Output_Regions.csv') output_regionsA = os.path.join(os.path.abspath(a.f), 'Output_Regions') if a.o != None: output_dipole = a.o center_subcube = (22, 22, 110) extent_subcube = (7, 7, 20) default_tuple_for_cube = (22 - 7, 22 + 7, 22 - 7, 22 + 7, 110 - 20, 110 + 20) # this warning is with respect of NEXT '''if a.o != None:''' warning( 'Watch out, you are using an hardcoded dipole cut {} !!'.format( default_tuple_for_cube)) else: output_dipole = os.path.join(os.path.abspath(a.f), 'Output_Dipole') if a.t != None: # derivative mode print('I will calculate derivatives into {} every {} frames'.format( folder_root, a.t)) derivative_mode(os.path.abspath(a.f), a.t) elif a.d != None: # we need to enter Difference mode print('I will calculate differences with {}'.format(a.d)) difference_mode(a.d) elif a.m: print('We are in dipole mode') global_expression = folder_Gau + '*.h5' list_of_wavefunctions = sorted(glob.glob(global_expression)) start_from = 0 if os.path.isfile( output_dipole ): # I make sure that output exist and that I have same amount of lines... count_output_lines = len(open(output_of_Grid).readlines()) count_regions_lines = len(open(output_dipole).readlines()) count_h5 = len(list_of_wavefunctions) if count_regions_lines > count_h5: err('something strange {} -> {}'.format( count_h5, count_regions_lines)) start_from = count_regions_lines all_h5_dict = readWholeH5toDict(all_h5) print('This analysis will start from {}'.format(start_from)) for fn in list_of_wavefunctions[start_from:]: wf = qp.retrieve_hdf5_data(fn, 'WF') alltime = qp.retrieve_hdf5_data(fn, 'Time')[0] #dipx, dipy, dipz = calculate_dipole(wf, all_h5_dict) if a.o != None: dipx, dipy, dipz, diagx, diagy, diagz, oodiag_x, oodiag_y, oodiag_z = calculate_dipole_fast_wrapper( wf, all_h5_dict, default_tuple_for_cube) else: dipx, dipy, dipz, diagx, diagy, diagz, oodiag_x, oodiag_y, oodiag_z = calculate_dipole_fast_wrapper( wf, all_h5_dict) perm_x = ' '.join(['{}'.format(x) for x in diagx]) perm_y = ' '.join(['{}'.format(y) for y in diagy]) perm_z = ' '.join(['{}'.format(z) for z in diagz]) trans_x = ' '.join(['{}'.format(x) for x in oodiag_x]) trans_y = ' '.join(['{}'.format(y) for y in oodiag_y]) trans_z = ' '.join(['{}'.format(z) for z in oodiag_z]) out_string = '{} {} {} {} {} {} {} {} {} {}'.format( alltime, dipx, dipy, dipz, perm_x, perm_y, perm_z, trans_x, trans_y, trans_z) # print(output_dipole) with open(output_dipole, "a") as out_reg: out_reg.write(out_string + '\n') elif a.r != None: # If we are in REGIONS mode regions_file = os.path.abspath(a.r) if os.path.isfile(regions_file): global_expression = folder_Gau + '*.h5' list_of_wavefunctions = sorted(glob.glob(global_expression)) start_from = 0 if os.path.isfile(output_regionsA): count_output_lines = len(open(output_of_Grid).readlines()) count_regions_lines = len(open(output_regionsA).readlines()) count_h5 = len(list_of_wavefunctions) if count_regions_lines > count_h5: err('something strange {} -> {}'.format( count_h5, count_regions_lines)) start_from = count_regions_lines with open(regions_file, "rb") as input_file: cubess = pickle.load(input_file) regionsN = len(cubess) print('\n\nI will start from {}\n\n'.format(start_from)) for fn in list_of_wavefunctions[start_from:]: allwf = qp.retrieve_hdf5_data(fn, 'WF') alltime = qp.retrieve_hdf5_data(fn, 'Time')[0] outputString_reg = "" for r in range(regionsN): uno = allwf[:, :, :, 0] # Ground state due = cubess[r]['cube'] value = np.linalg.norm(uno * due)**2 outputString_reg += " {} ".format(value) with open(output_regionsA, "a") as out_reg: print(outputString_reg) out_reg.write(outputString_reg + '\n') else: err('I do not see the regions file'.format(regions_file)) else: # regions mode or not? check_output_of_Grid(output_of_Grid) global_expression = folder_Gau + '*.h5' list_of_wavefunctions = sorted(glob.glob(global_expression)) start_from = 0 if os.path.isfile(output_of_this): count_output_lines = len(open(output_of_Grid).readlines()) count_abs_lines = len(open(output_of_this).readlines()) count_h5 = len(list_of_wavefunctions) if count_abs_lines > count_h5: err('something strange {} -> {} -> {}'.format( count_h5, count_abs_lines, count_output_lines)) # if Abs file is there, I need to skip all the wavefunctions I already calculated. start_from = count_abs_lines all_h5_dict = readWholeH5toDict(all_h5) for single_wf in list_of_wavefunctions[start_from:]: wf_dict = readWholeH5toDict(single_wf) calculate_stuffs_on_WF(wf_dict, all_h5_dict, output_of_this)
def restart_propagation(inp, inputDict): ''' This function restarts a propagation that has been stopped ''' import glob nameRoot = inputDict['outFol'] list_wave_h5 = sorted(glob.glob(nameRoot + '/Gaussian*.h5')) last_wave_h5 = list_wave_h5[-1] wf = retrieve_hdf5_data(last_wave_h5, 'WF') t = retrieve_hdf5_data(last_wave_h5, 'Time')[1] # [1] is atomic units kind = inp['kind'] deltasGraph = inputDict['deltasGraph'] counter = len(list_wave_h5) - 1 dt = inputDict['dt'] fulltime = inputDict['fullTime'] fulltimeSteps = int(fulltime / dt) outputFile = os.path.join(nameRoot, 'output') outputFileP = os.path.join(nameRoot, 'outputPopul') outputFileA = os.path.join(nameRoot, 'Output_Abs') if (inputDict['fullTime'] == inp['fullTime']): good('Safe restart with same fulltime') #h5_data_file = os.path.join(nameRoot,'allInput.h5') else: h5_data_file = os.path.join(nameRoot, 'allInput.h5') dict_all_data = readWholeH5toDict(h5_data_file) dict_all_data['fullTime'] = inputDict['fullTime'] writeH5fileDict(h5_data_file, dict_all_data) good('different fullTime detected and allInput updated') print('\ntail -f {}\n'.format(outputFileP)) CEnergy, Cpropagator = select_propagator(kind) good('Cpropagator version: {}'.format(version_Cpropagator())) ii_initial = counter * deltasGraph print('I will do {} more steps.\n'.format(fulltimeSteps - ii_initial)) if True: print( 'Calculation restart forced on me... I assume you did everything you need' ) else: warning('Did you restart this from a finished calculation?') strout = "rm {}\nsed -i '$ d' {}\nsed -i '$ d' {}\n" print(strout.format(last_wave_h5, outputFile, outputFileP)) input("Press Enter to continue...") strOUT = '{} {} {}'.format(ii_initial, counter, fulltimeSteps) good(strOUT) for ii in range(ii_initial, fulltimeSteps): #print('ii = {}'.format(ii)) if ((ii % deltasGraph) == 0 or ii == fulltimeSteps - 1): # async is awesome. But it is not needed in 1d and maybe in 2d. if kind == '3D': asyncFun(doAsyncStuffs, wf, t, ii, inp, inputDict, counter, outputFile, outputFileP, outputFileA, CEnergy) else: doAsyncStuffs(wf, t, ii, inp, inputDict, counter, outputFile, outputFileP, outputFileA, CEnergy) counter += 1 wf = Crk4Ene3d(Cpropagator, t, wf, inp) t = t + dt