def check_output_of_Grid(fn): ''' checks if this file first line has 11 number of fields if it is 12... this means that this calculation is useless ''' with open(fn, 'r') as f: first_line = f.readline() number_of_line = len(first_line.split(' ')) if number_of_line != 11: err('Watch out. File output already have good format...')
def kinAnalysis(globalExp, coorGraphs): ''' Takes h5 files from global expression and calculates first derivative and second along this coordinate for an attempt at kinetic energy For now it only draw graphics... ''' allH5 = sorted(glob.glob(globalExp)) dime = len(allH5) if dime == 0: err("no files in {}".format(globalExp)) allH5First = allH5[0] nstates = len(retrieve_hdf5_data(allH5First, 'SFS_ENERGIES')) natoms = len(retrieve_hdf5_data(allH5First, 'CENTER_COORDINATES')) labels = retrieve_hdf5_data(allH5First, 'CENTER_LABELS') stringLabels = [b[:1].decode("utf-8") for b in labels] print('\nnstates: {} \ndimension: {}'.format(nstates, dime)) bigArrayC = np.empty((dime, natoms, 3)) bigArrayE = np.empty((dime, nstates)) bigArrayA1 = np.empty((dime)) # fill bigArrayC array ind = 0 for fileN in allH5: singleCoord = retrieve_hdf5_data(fileN, 'CENTER_COORDINATES') energies = retrieve_hdf5_data(fileN, 'SFS_ENERGIES') coords = translateInCM(singleCoord, labels) bigArrayC[ind] = coords bigArrayE[ind] = energies bigArrayA1[ind] = calcAngle(coords, 2, 3, 4) ind += 1 # true because we are in bohr and saveTaj is like that saveTraj(bigArrayC, stringLabels, 'scanGeometriesCMfixed', True) fileNameGraph = 'EnergiesAlongScan' makeJustAnother2DgraphMULTI(bigArrayA1, bigArrayE, fileNameGraph, 'State', 1.0) print('\nEnergy graph created:\n\neog ' + fileNameGraph + '.png\n') # make graphs if coorGraphs: for alpha in range(3): axes = ['X', 'Y', 'Z'] lab1 = axes[alpha] for atomN in range(natoms): lab2 = stringLabels[atomN] + str(atomN + 1) name = 'coord_' + lab1 + '_' + lab2 makeJustAnother2Dgraph(np.arange(dime), bigArrayC[:, atomN, alpha], name, name)
def main(): #geom1='CI12.xyz' #xf='x' #yf='y' #circles = 20 ''' circles works like: generateGeomsAroundConical.py -v CI12.xyz x y -c 20 0.1 0.2 0.3 0.4 the command geom v1 v2 howmany list of Rs ''' o_inputs = single_inputs("","","",[],[],"","") # defaults inp = read_single_arguments(o_inputs) #print(inp) if inp == o_inputs: err("You should use this with some arguments... you know... try -h") if inp.graphsGlob == "": if inp.globExp == "": displaceGeom(inp.fileXYZ,inp.vectorX,inp.vectorY,inp.linearDisplacement, inp.circleScan) else: scalarProds(inp.globExp,inp.vectorX,inp.vectorY) else: graphScan(inp.graphsGlob)
def calculate_stuffs_on_WF(single_wf, inp, outputFile): ''' This function is a standalone function that recreates the output file counting also the absorbing potential ''' counter = 0 nstates = inp['nstates'] ii = 0 wf = single_wf['WF'] t_fs, t = single_wf['Time'] kind = inp['kind'] if kind != '3d': err('This function is implemented only in 3d code') CEnergy, Cpropagator = select_propagator(kind) kin, pot, pul, absS = CEnergy(t, wf, inp) kinetic = np.vdot(wf, kin) potential = np.vdot(wf, pot) pulse_interaction = np.vdot(wf, pul) absorbing_potential = np.vdot(wf, absS) absorbing_potential_thing = np.real(-2j * absorbing_potential) total = kinetic + potential + pulse_interaction initialTotal = inp['initialTotal'] norm_wf = np.linalg.norm(wf) outputStringS = ' {:04d} |{:10d} |{:11.4f} | {:+e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+10.3e} | {:+10.3e} | {:+10.3e} | {:+10.3e} |' outputString = outputStringS.format(counter, ii, t * 0.02418884, 1 - norm_wf, fromHartoEv(kinetic.real), fromHartoEv(potential.real), fromHartoEv(total.real), fromHartoEv(initialTotal - total.real), fromHartoEv(pulse_interaction.real), pulZe(t, inp['pulseX']), pulZe(t, inp['pulseY']), pulZe(t, inp['pulseZ']), absorbing_potential_thing) print(outputString) kind = inp['kind'] outputStringA = "{:11.4f} {:+7.5e}".format(t, absorbing_potential_thing) for i in range(nstates): if kind == '3d': singleStatewf = wf[:, :, :, i] singleAbspote = absS[:, :, :, i] norm_loss_this_step = np.real( -2j * np.vdot(singleStatewf, singleAbspote)) if kind == 'GamThe': err('no 2d here') elif kind == 'Phi' or kind == 'Gam' or kind == 'The': err('no 1d here') outputStringA += " {:+7.5e} ".format(norm_loss_this_step) with open(outputFile, "a") as oof: outputStringS2 = '{}' outputString2 = outputStringS2.format(outputStringA) oof.write(outputString2 + '\n')
def read_single_arguments(single_inputs): ''' This funcion reads the command line arguments ''' d = "Create the goemetry scan and the circle graphic." parser = ArgumentParser(formatter_class=RawTextHelpFormatter, description=d) parser.add_argument("-v", "--vectors", dest="v", nargs='+', help="the 3 files: geometry and branching plane vectors") parser.add_argument("-s", "--scalarProd", dest="s", nargs='+', help="to calculate scalar product between scan \ geometries (given by globalexpression) and branching plane vectors") parser.add_argument("-l", "--linear", dest="l", nargs='+', help="parameters for the linear displacement.\n" "Distance :: Double\n" "Number of points :: Int\n") parser.add_argument("-c", "--circular", dest="c", nargs='+', help="parameters for the circular displacement.\n" "Number of ponts in the circle :: Int\n" "List of radii :: [Double]") parser.add_argument("-g", "--globalPattern", dest="g", type=str, help="it is the global pattern of output rasscf h5 files\n" "to create the gnuplot graphic") args = parser.parse_args() if args.s != None: if len(args.s) == 3: [globE,grad,der] = args.s single_inputs = single_inputs._replace(globExp=globE) single_inputs = single_inputs._replace(vectorX=grad) single_inputs = single_inputs._replace(vectorY=der) else: err('this takes 3 arguments: the geometry global expression and the two vectors') if args.v != None: if len(args.v) == 3: [geom,grad,der] = args.v single_inputs = single_inputs._replace(fileXYZ=geom) single_inputs = single_inputs._replace(vectorX=grad) single_inputs = single_inputs._replace(vectorY=der) else: err('this takes 3 arguments: the single geometry and the two vectors') if args.l != None: if len(args.l) == 2: single_inputs = single_inputs._replace(linearDisplacement=args.l) else: err('this takes 2 arguments: number of points and distance') if args.c != None: # without controls because we feel brave single_inputs = single_inputs._replace(circleScan=args.c) if args.g != None: single_inputs = single_inputs._replace(graphsGlob=args.g) return single_inputs
def read_single_arguments(single_inputs): ''' This funcion reads the command line arguments ''' parser = ArgumentParser() parser.add_argument( '-l', '--list', nargs='+', help='Values of phi, gamma and theta', ) parser.add_argument( '-n', '--newlist', nargs='+', help='Values of phi, gamma and theta, where phi is linear', ) parser.add_argument( '-i', '--info', dest="i", type=str, help='gives info on a certain geometry', ) args = parser.parse_args() if args.i != None: single_inputs = single_inputs._replace(geomfile=args.i) if args.list != None: if len(args.list) == 9: single_inputs = single_inputs._replace(phi0=float(args.list[0])) single_inputs = single_inputs._replace(phiF=float(args.list[1])) single_inputs = single_inputs._replace(phiD=float(args.list[2])) single_inputs = single_inputs._replace(gamma0=float(args.list[3])) single_inputs = single_inputs._replace(gammaF=float(args.list[4])) single_inputs = single_inputs._replace(gammaD=float(args.list[5])) single_inputs = single_inputs._replace(theta0=float(args.list[6])) single_inputs = single_inputs._replace(thetaF=float(args.list[7])) single_inputs = single_inputs._replace(thetaD=float(args.list[8])) elif len(args.list) == 3: single_inputs = single_inputs._replace(phi0=float(args.list[0])) single_inputs = single_inputs._replace(gamma0=float(args.list[1])) single_inputs = single_inputs._replace(theta0=float(args.list[2])) else: err("WTF? This takes 3 numbers (single point) or 9 (for a line/box)" ) if args.newlist != None: single_inputs = single_inputs._replace(linearphi=True) if len(args.newlist) == 9: single_inputs = single_inputs._replace(phi0=float(args.newlist[0])) single_inputs = single_inputs._replace(phiF=float(args.newlist[1])) single_inputs = single_inputs._replace(phiD=float(args.newlist[2])) single_inputs = single_inputs._replace( gamma0=float(args.newlist[3])) single_inputs = single_inputs._replace( gammaF=float(args.newlist[4])) single_inputs = single_inputs._replace( gammaD=float(args.newlist[5])) single_inputs = single_inputs._replace( theta0=float(args.newlist[6])) single_inputs = single_inputs._replace( thetaF=float(args.newlist[7])) single_inputs = single_inputs._replace( thetaD=float(args.newlist[8])) elif len(args.newlist) == 3: single_inputs = single_inputs._replace(phi0=float(args.newlist[0])) single_inputs = single_inputs._replace( gamma0=float(args.newlist[1])) single_inputs = single_inputs._replace( theta0=float(args.newlist[2])) else: err("WTF? This takes 3 numbers (single point) or 9 (for a line/box)" ) return single_inputs
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 graphMultiRassi(globalExp, poolSize): ''' collects rassi data and create the elementwise graphs ''' allH5 = sorted(glob.glob(globalExp)) dime = len(allH5) if dime == 0: err("no files in {}".format(globalExp)) allH5First = allH5[0] nstates = len(retrieve_hdf5_data(allH5First, 'ROOT_ENERGIES')) natoms = len(retrieve_hdf5_data(allH5First, 'CENTER_LABELS')) bigArray = np.empty((dime, 3, nstates, nstates)) bigArrayNAC = np.empty((dime, nstates, nstates, natoms, 3)) ind = 0 for fileN in allH5: [properties, NAC, ene] = retrieve_hdf5_data(fileN, ['DIPOLES', 'NAC', 'ROOT_ENERGIES']) dmMat = properties # here... bigArray[ind] = dmMat print(NAC[0, 1, 9, 1], NAC[0, 1, 8, 1], NAC[0, 1, 3, 1]) bigArrayNAC[ind] = NAC ind += 1 std = np.std(bigArray[:, 0, 0, 0]) allstd = np.average(np.abs(bigArray), axis=0) fn = 'heatMap.png' transp = False my_dpi = 150 ratio = (9, 16) fig, ax1 = plt.subplots(figsize=ratio) xticks = np.arange(nstates) + 1 yticks = np.arange(nstates) + 1 plt.subplot(311) plt.imshow(allstd[0], cmap='hot', interpolation='nearest') plt.subplot(312) plt.imshow(allstd[1], cmap='hot', interpolation='nearest') plt.subplot(313) plt.imshow(allstd[2], cmap='hot', interpolation='nearest') #plt.savefig(fn, bbox_inches='tight', dpi=my_dpi, transparent=transp) plt.savefig(fn, bbox_inches='tight', dpi=my_dpi) plt.close('all') # I first want to make a graph of EACH ELEMENT elems = [[x, y, z] for x in range(3) for y in range(nstates) for z in range(nstates)] pool = mp.Pool(processes=poolSize) #pool.map(doThisToEachElement, zip(elems, repeat(dime), repeat(bigArray))) rows = [[x, y] for x in range(3) for y in range(nstates)] #for row in rows: # doDipoToEachRow(row, dime, bigArray) # For some reason the perallel version of this does not work properly. pool.map(doDipoToEachRow, zip(rows, repeat(dime), repeat(bigArray))) for i in np.arange(2) + 1: lab = 'NacElement' + str(i) makeJustAnother2Dgraph(lab, lab, bigArrayNAC[:, 0, i, 9, 1])
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 propagate3D(dataDict, inputDict): ''' Two dictionaries, one from data file and one from input file it starts and run the 3d propagation of the wavefunction... ''' printDict(inputDict) printDictKeys(dataDict) printDictKeys(inputDict) #startState = inputDict['states'] _, _, _, nstates = dataDict['potCube'].shape phiL, gamL, theL, natoms, _ = dataDict['geoCUBE'].shape # INITIAL WF default values if 'factor' in inputDict: factor = inputDict['factor'] warning('WF widened using factor: {}'.format(factor)) else: factor = 1 if 'displ' in inputDict: displ = inputDict['displ'] else: displ = (0, 0, 0) if 'init_mom' in inputDict: init_mom = inputDict['init_mom'] else: init_mom = (0, 0, 0) if 'initial_state' in inputDict: initial_state = inputDict['initial_state'] warning( 'Initial gaussian wavepacket in state {}'.format(initial_state)) else: initial_state = 0 wf = np.zeros((phiL, gamL, theL, nstates), dtype=complex) print(initial_state) wf[:, :, :, initial_state] = initialCondition3d(wf[:, :, :, initial_state], dataDict, factor, displ, init_mom) # Take values array from labels (radians already) phis, gams, thes = fromLabelsToFloats(dataDict) # take step dphi = phis[0] - phis[1] dgam = gams[0] - gams[1] dthe = thes[0] - thes[1] inp = { 'dt': inputDict['dt'], 'fullTime': inputDict['fullTime'], 'phiL': phiL, 'gamL': gamL, 'theL': theL, 'natoms': natoms, 'phis': phis, 'gams': gams, 'thes': thes, 'dphi': dphi, 'dgam': dgam, 'dthe': dthe, 'potCube': dataDict['potCube'], 'kinCube': dataDict['kinCube'], 'dipCube': dataDict['dipCUBE'], 'nacCube': dataDict['smoCube'], 'pulseX': inputDict['pulseX'], 'pulseY': inputDict['pulseY'], 'pulseZ': inputDict['pulseZ'], 'nstates': nstates, 'kind': inputDict['kind'], } ######################################### # Here the cube expansion/interpolation # ######################################### inp = expandcube(inp) ######################################## # Potentials to Zero and normalization # ######################################## inp['potCube'] = dataDict['potCube'] - np.amin(dataDict['potCube']) norm_wf = np.linalg.norm(wf) good('starting NORM deviation : {}'.format(1 - norm_wf)) # magnify the potcube if 'enePot' in inputDict: enePot = inputDict['enePot'] inp['potCube'] = inp['potCube'] * enePot if enePot == 0: warning('This simulation is done with zero Potential energy') elif enePot == 1: good('Simulation done with original Potential energy') else: warning('The potential energy has been magnified {} times'.format( enePot)) # constant the kinCube kinK = False if kinK: kokoko = 1000 inp['kinCube'] = inp['kinCube'] * kokoko warning('kincube divided by {}'.format(kokoko)) if 'multiply_nac' in inputDict: # this keyword can be used to multiply NACs. It works with a float or a list of triplet # multiply_nac : 10 -> will multiply all by 10 # multiply_nac : [[1,2,10.0],[3,4,5.0]] -> will multiply 1,2 by 10 and 3,4 by 5 nac_multiplier = inputDict['multiply_nac'] if type(nac_multiplier) == int or type(nac_multiplier) == float: warning('all Nacs are multiplied by {}'.format(nac_multiplier)) inp['nacCube'] = inp['nacCube'] * nac_multiplier if type(nac_multiplier) == list: warning('There is a list of nac multiplications, check input') for state_one, state_two, multiply_factor in nac_multiplier: inp['nacCube'][:, :, :, state_one, state_two, :] = inp[ 'nacCube'][:, :, :, state_one, state_two, :] * multiply_factor inp['nacCube'][:, :, :, state_two, state_one, :] = inp[ 'nacCube'][:, :, :, state_two, state_one, :] * multiply_factor warning( 'NACS corresponding of state {} and state {} are multiplied by {}' .format(state_one, state_two, multiply_factor)) inp['Nac_multiplier'] = nac_multiplier nameRoot = create_enumerated_folder(inputDict['outFol']) inputDict['outFol'] = nameRoot inp['outFol'] = nameRoot numStates = inputDict['states'] ################### # Absorbing Thing # ################### if 'absorb' in inputDict: good('ABSORBING POTENTIAL is taken from file') file_absorb = inputDict['absorb'] print('{}'.format(file_absorb)) inp['absorb'] = retrieve_hdf5_data(file_absorb, 'absorb') else: good('NO ABSORBING POTENTIAL') inp['absorb'] = np.zeros_like(inp['potCube']) ################ # slice states # ################ kind = inp['kind'] # Take equilibrium points from directionFile # warning('This is a bad equilibriumfinder') # gsm_phi_ind, gsm_gam_ind, gsm_the_ind = equilibriumIndex(inputDict['directions1'],dataDict) gsm_phi_ind, gsm_gam_ind, gsm_the_ind = (29, 28, 55) warning('You inserted equilibrium points by hand: {} {} {}'.format( gsm_phi_ind, gsm_gam_ind, gsm_the_ind)) inp['nstates'] = numStates if kind == '3d': inp['potCube'] = inp['potCube'][:, :, :, :numStates] inp['kinCube'] = inp['kinCube'][:, :, :] inp['dipCube'] = inp['dipCube'][:, :, :, :, :numStates, :numStates] wf = wf[:, :, :, :numStates] good('Propagation in 3D.') print( '\nDimensions:\nPhi: {}\nGam: {}\nThet: {}\nNstates: {}\nNatoms: {}\n' .format(phiL, gamL, theL, numStates, natoms)) elif kind == 'GamThe': inp['potCube'] = inp['potCube'][gsm_phi_ind, :, :, :numStates] inp['kinCube'] = inp['kinCube'][gsm_phi_ind, :, :] inp['dipCube'] = inp['dipCube'][ gsm_phi_ind, :, :, :, :numStates, :numStates] wf = wf[gsm_phi_ind, :, :, :numStates] good('Propagation in GAM-THE with Phi {}'.format(gsm_phi_ind)) print('Shapes: P:{} K:{} W:{} D:{}'.format(inp['potCube'].shape, inp['kinCube'].shape, wf.shape, inp['dipCube'].shape)) print('\nDimensions:\nGam: {}\nThe: {}\nNstates: {}\nNatoms: {}\n'. format(gamL, theL, numStates, natoms)) norm_wf = np.linalg.norm(wf) wf = wf / norm_wf elif kind == 'Phi': inp['potCube'] = inp['potCube'][:, gsm_gam_ind, gsm_the_ind, :numStates] inp['kinCube'] = inp['kinCube'][:, gsm_gam_ind, gsm_the_ind] inp['dipCube'] = inp['dipCube'][:, gsm_gam_ind, gsm_the_ind, :, :numStates, :numStates] wf = wf[:, gsm_gam_ind, gsm_the_ind, :numStates] good('Propagation in PHI with Gam {} and The {}'.format( gsm_gam_ind, gsm_the_ind)) print('Shapes: P:{} K:{} W:{} D:{}'.format(inp['potCube'].shape, inp['kinCube'].shape, wf.shape, inp['dipCube'].shape)) print('\nDimensions:\nPhi: {}\nNstates: {}\nNatoms: {}\n'.format( phiL, numStates, natoms)) norm_wf = np.linalg.norm(wf) wf = wf / norm_wf elif kind == 'Gam': inp['potCube'] = inp['potCube'][gsm_phi_ind, :, gsm_the_ind, :numStates] inp['kinCube'] = inp['kinCube'][gsm_phi_ind, :, gsm_the_ind] inp['dipCube'] = inp['dipCube'][gsm_phi_ind, :, gsm_the_ind, :, :numStates, :numStates] wf = wf[gsm_phi_ind, :, gsm_the_ind, :numStates] good('Propagation in GAM with Phi {} and The {}'.format( gsm_phi_ind, gsm_the_ind)) print('Shapes: P:{} K:{} W:{} D:{}'.format(inp['potCube'].shape, inp['kinCube'].shape, wf.shape, inp['dipCube'].shape)) print('\nDimensions:\nGam: {}\nNstates: {}\nNatoms: {}\n'.format( gamL, numStates, natoms)) norm_wf = np.linalg.norm(wf) wf = wf / norm_wf elif kind == 'The': sposta = False if sposta: gsm_phi_ind = 20 gsm_gam_ind = 20 warning('Phi is {}, NOT EQUILIBRIUM'.format(gsm_phi_ind)) warning('Gam is {}, NOT EQUILIBRIUM'.format(gsm_gam_ind)) inp['potCube'] = inp['potCube'][gsm_phi_ind, gsm_gam_ind, :, :numStates] inp['absorb'] = inp['absorb'][gsm_phi_ind, gsm_gam_ind, :, :numStates] inp['kinCube'] = inp['kinCube'][gsm_phi_ind, gsm_gam_ind, :] inp['dipCube'] = inp['dipCube'][ gsm_phi_ind, gsm_gam_ind, :, :, :numStates, :numStates] inp['nacCube'] = inp['nacCube'][ gsm_phi_ind, gsm_gam_ind, :, :numStates, :numStates, :] wf = wf[gsm_phi_ind, gsm_gam_ind, :, :numStates] # doubleGridPoints doubleThis = False if doubleThis: warning('POINTS DOUBLED ALONG THETA') inp['thes'] = doubleAxespoins(inp['thes']) inp['theL'] = inp['thes'].size inp['dthe'] = inp['thes'][0] - inp['thes'][1] inp['potCube'] = np.array( [doubleAxespoins(x) for x in inp['potCube'].T]).T newWf = np.empty((inp['theL'], numStates), dtype=complex) for ssssss in range(numStates): newWf[:, ssssss] = doubleAxespoins(wf[:, ssssss]) wf = newWf newNac = np.empty((inp['theL'], numStates, numStates, 3)) for nnn in range(2): for mmm in range(2): for aaa in range(3): newNac[:, nnn, mmm, aaa] = doubleAxespoins(inp['nacCube'][:, nnn, mmm, aaa]) inp['nacCube'] = newNac newKin = np.empty((inp['theL'], 9, 3)) for nnn in range(9): for mmm in range(3): newKin[:, nnn, mmm] = doubleAxespoins(inp['kinCube'][:, nnn, mmm]) inp['kinCube'] = newKin good('Propagation in THE with Phi {} and Gam {}'.format( gsm_phi_ind, gsm_gam_ind)) print('Shapes: P:{} K:{} W:{} D:{}'.format(inp['potCube'].shape, inp['kinCube'].shape, wf.shape, inp['dipCube'].shape)) print('\nDimensions:\nThe: {}\nNstates: {}\nNatoms: {}\n'.format( theL, numStates, natoms)) norm_wf = np.linalg.norm(wf) wf = wf / norm_wf else: err('I do not recognize the kind') initial_time_simulation = 0.0 # take a wf from file (and not from initial condition) if 'initialFile' in inputDict: warning('we are taking initial wf from file') wffn = inputDict['initialFile'] print('File -> {}'.format(wffn)) wf_not_norm = retrieve_hdf5_data(wffn, 'WF') initial_time_simulation = retrieve_hdf5_data(wffn, 'Time')[1] # in hartree #wf = wf_not_norm/np.linalg.norm(wf_not_norm) wf = wf_not_norm ############################# # PROPAGATOR SELECTION HERE # ############################# CEnergy, Cpropagator = select_propagator(kind) good('Cpropagator version: {}'.format(version_Cpropagator())) # INITIAL DYNAMICS VALUES dt = inp['dt'] if 'reverse_time' in inputDict: warning('Time is reversed !!') dt = -dt Cpropagator = Cderivative3dMu_reverse_time t = initial_time_simulation counter = 0 fulltime = inp['fullTime'] fulltimeSteps = int(fulltime / abs(dt)) deltasGraph = inputDict['deltasGraph'] print('I will do {} steps.\n'.format(fulltimeSteps)) outputFile = os.path.join(nameRoot, 'output') outputFileP = os.path.join(nameRoot, 'outputPopul') outputFileA = os.path.join(nameRoot, 'Output_Abs') print('\ntail -f {}\n'.format(outputFileP)) if inputDict['readme']: outputFilereadme = os.path.join(nameRoot, 'README') with open(outputFilereadme, "w") as oofRR: oofRR.write(inputDict['readme']) print('file readme written') # calculating initial total/potential/kinetic kin, pot, pul, absS = CEnergy(t, wf, inp) kinetic = np.vdot(wf, kin) potential = np.vdot(wf, pot) pulse_interaction = np.vdot(wf, pul) initialTotal = kinetic + potential + pulse_interaction inp['initialTotal'] = initialTotal.real # to give the graph a nice range inp['vmax_value'] = abs2(wf).max() # graph the pulse graphic_Pulse(inp) # saving input data in h5 file dataH5filename = os.path.join(nameRoot, 'allInput.h5') writeH5fileDict(dataH5filename, inp) # print top of table header = ' Coun | step N | fs | NORM devia. | Kin. Energy | Pot. Energy | Total Energy | Tot devia. | Pulse_Inter. | Pulse X | Pulse Y | Pulse Z | Norm Loss |' bar = ('-' * (len(header))) print('Energies in ElectronVolt \n{}\n{}\n{}'.format(bar, header, bar)) for ii in range(fulltimeSteps): 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