示例#1
0
def graphScan(globalExp):
    '''
    So, this one takes the global expression of rasscf h5 files and creates the
    circle graph. This assumes that you used the {:+08.3f} convention to create this
    file.
          RingP000-100_AngleP000-000
    glob :: string <- global pattern "*.*"
    '''
    allH5 = sorted(glob.glob(globalExp))
    dime = len(allH5)
    allH5First = allH5[0]
    nstates = len(retrieve_hdf5_data(allH5First,'ROOT_ENERGIES'))
    bigArrayE = np.empty((dime,nstates))
    bigArray1 = np.empty(dime)
    bigArray2 = np.empty(dime)
    ind=0
    for fileN in allH5:
        (dim1,dim2) = transformString(fileN)
        energies = retrieve_hdf5_data(fileN,'ROOT_ENERGIES')
        bigArrayE[ind] = energies
        bigArray1[ind] = dim1
        bigArray2[ind] = dim2
        ind += 1
#    print(bigArray1,bigArray2)
#    mathematicaListGenerator(bigArray1,bigArray2,bigArrayE)
    gnuSplotCircle(bigArray1,bigArray2,bigArrayE)
示例#2
0
def fourdThing(fn):
    '''
    we try myavi
    '''
    a = qp.retrieve_hdf5_data(fn, 'WF')[:, :, :, 0]
    time = qp.retrieve_hdf5_data(fn, 'Time')[0]
    fig = figure(size=(600, 600), fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    contour3d(qp.abs2(a), contours=10, transparent=True, opacity=0.8)
    #title('Time - {:5.2f}'.format(time))
    xlabel('phi')
    ylabel('gam')
    zlabel('the')
    #view(132.05741302902214, 62.73780301264113, 187.6797494627067, np.array([ 15.00000048, 11., 1087643]))
    view(47.01, 79.90, 105.94, np.array([15.00, 11.00, 15.00]))
    savefig(fn + '.a.png')

    view(0.0, 90.0, 87.034, np.array([15., 11., 15.]))
    savefig(fn + '.b.png')

    view(90.0, 90.0, 87.034, np.array([15., 11., 15.]))
    savefig(fn + '.c.png')

    view(0.0, 0.0, 87.034, np.array([15., 11., 15.]))
    savefig(fn + '.d.png')
    close()
示例#3
0
def matrixApproach(globalExp, proc):
    '''

    Shitty shitty function, but I need to see if Blender is working

    I try this new way of taking the data. First I watch in the folder, then I
    create a square grid, then I see who is present who is not. This can be
    better to import data in blender and draw surfaces

    globalExp :: String <- with the global expression of the h5 files
    proc :: Int number of processors in case this become heavy and I need to
    parallelize
    '''
    allH5 = sorted(glob.glob(globalExp))
    dime = len(allH5)
    allH5First = allH5[0]
    nstates = len(retrieve_hdf5_data(allH5First,'ROOT_ENERGIES'))
    natoms = len(retrieve_hdf5_data(allH5First,'CENTER_COORDINATES'))
    print('\nnstates: {} \ndimension: {}'.format(nstates,dime))
    newdime = (dime * 2)-1
    bigArrayLab1 =  np.empty((dime), dtype=object)
    bigArrayLab2 =  np.empty((dime), dtype=object)
    ind = 0
    for fileN in allH5:
        (axis1,str1) = stringTransformation(fileN,2,3)
        (axis2,str2) = stringTransformation(fileN,4,5)
        bigArrayLab1[ind] = str1
        bigArrayLab2[ind] = str2
        ind += 1
    labelsAxis1 = np.unique(bigArrayLab1)
    labelsAxis2 = np.unique(bigArrayLab2)
    #allLabels = [ ax1 + '_' + ax2 for ax1 in labelsAxis1 for ax2 in labelsAxis2 ]
    blenderArray = np.empty((labelsAxis1.size,labelsAxis2.size,nstates))
    ind = 0
    for Iax1 in range(labelsAxis1.size):
        ax1 = labelsAxis1[Iax1]
        for Iax2 in range(labelsAxis2.size):
            ax2 = labelsAxis2[Iax2]
            singleLabel = ax1 + '_' + ax2
            fileN = re.sub('\*\.', 'Grid_' + singleLabel + '.', globalExp)
            exisT = os.path.exists(fileN)
            if exisT:
               energies = retrieve_hdf5_data(fileN,'ROOT_ENERGIES')
            else:
               energies = np.repeat(-271.0,nstates)
            blenderArray[Iax1,Iax2] = energies
    axFloat1 = np.array([ float(a) for a in labelsAxis1 ])
    axFloat2 = np.array([ float(b) for b in labelsAxis2 ])

    print(axFloat1.shape, axFloat2.shape, blenderArray.shape)
    axFloat1.tofile('fullA.txt')
    axFloat2.tofile('fullB.txt')
    blenderArray.tofile('fullC.txt')
示例#4
0
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)
示例#5
0
def correctorFromDirection(folderO, folderE, fn1, fn2):
    '''
    This function is the corrector that follows the direction files...
    suuuuper problem bound
    '''
    phis1, gammas1, thetas1 = readDirectionFile(fn1)
    phis2, gammas2, thetas2 = readDirectionFile(fn2)
    #phis = phis[0:3]
    #gammas = gammas[0:3]
    #thetas = thetas[0:3]
    rootNameO = os.path.join(folderO, 'zNorbornadiene_')
    rootNameE = os.path.join(folderE, 'zNorbornadiene_')
    graph1, revgraph1, first = makeCubeGraph(phis1, gammas1, thetas1)
    graph2, revgraph2, _ = makeCubeGraph(phis2, gammas1, thetas1)
    graph3, revgraph3, _ = makeCubeGraph(phis1, gammas2, thetas1)
    graph4, revgraph4, _ = makeCubeGraph(phis2, gammas2, thetas1)
    graph5, revgraph5, _ = makeCubeGraph(phis1, gammas1, thetas2)
    graph6, revgraph6, _ = makeCubeGraph(phis2, gammas1, thetas2)
    graph7, revgraph7, _ = makeCubeGraph(phis1, gammas2, thetas2)
    graph8, revgraph8, _ = makeCubeGraph(phis2, gammas2, thetas2)
    cutAt = 14
    # correct first point here - True means "I am the first"
    print('\n\n----------THIS IS INITIAL -> cut at {}:\n'.format(cutAt))
    newsign = np.ones(cutAt)
    correctThis(first, newsign, rootNameE, rootNameO, cutAt, True)
    # correct the other here key is file to be corrected VALUE the one where to
    # take the correction
    #print("{}\n{}\n{}".format(phis,gammas,thetas))
    #print(' ')
    #printDict(graph)
    #print(' ')
    #printDict(revgraph)
    revgraphSum = {
        **revgraph8,
        **revgraph7,
        **revgraph6,
        **revgraph5,
        **revgraph4,
        **revgraph3,
        **revgraph2,
        **revgraph1
    }
    #print(len(revgraphSum))
    for key, value in revgraphSum.items():
        fnIn = rootNameO + key + '.all.h5'
        if os.path.isfile(fnIn):
            print('\n\n----------THIS IS {} from {} -> cut at {}:\n'.format(
                key, value, cutAt))
            fnE = rootNameE + value + '.corrected.h5'
            newsign = retrieve_hdf5_data(fnE, 'ABS_CORRECTOR')
            correctThis(key, newsign, rootNameE, rootNameO, cutAt)
    good('Hey, you are using an hardcoded direction file')
示例#6
0
def twoDGraph(globalExp, proc):
    '''
    This function expects a global expression of multiple rassi files
    it will organize them to call a 3d plotting function

    globalExp :: String <- with the global expression of the h5 files
    proc :: Int number of processors in case this become heavy and I need to
    parallelize

    '''
    allH5 = sorted(glob.glob(globalExp))
    dime = len(allH5)
    allH5First = allH5[0]
    nstates = len(retrieve_hdf5_data(allH5First,'ROOT_ENERGIES'))
    natoms = len(retrieve_hdf5_data(allH5First,'CENTER_COORDINATES'))
    print('\nnstates: {} \ndimension: {}'.format(nstates,dime))

    bigArrayD = np.empty((dime,3,nstates,nstates))
    bigArrayE = np.empty((dime,nstates))
    bigArrayC = np.empty((dime,natoms,3))
    bigArrayLab1 =  np.empty((dime), dtype=object)
    bigArrayLab2 =  np.empty((dime), dtype=object)
    bigArrayAxis1 =  np.empty((dime))
    bigArrayAxis2 =  np.empty((dime))
    newdime = (dime * 2)-1
    bigArrayE2 = np.empty((newdime,nstates))
    bigArrayAxis1_2 = np.empty((newdime))
    bigArrayAxis2_2 = np.empty((newdime))
    ind=0
    for fileN in allH5:
        dmMat = retrieve_hdf5_data(fileN,'DIPOLES')
        energies = retrieve_hdf5_data(fileN,'ROOT_ENERGIES')
        coords = retrieve_hdf5_data(fileN,'CENTER_COORDINATES')
        (axis1,str1) = stringTransformation(fileN,2,3)
        (axis2,str2) = stringTransformation(fileN,4,5)
        bigArrayD[ind] = dmMat
        bigArrayE[ind] = energies
        bigArrayE2[ind] = energies
        bigArrayAxis1_2[ind] = axis1
        bigArrayAxis2_2[ind] = axis2
        bigArrayLab1[ind] = str1
        bigArrayLab2[ind] = str2
        if axis2 != 0.0:
           bigArrayE2[ind+(dime-1)] = energies
           bigArrayAxis1_2[ind+(dime-1)] = axis1
           bigArrayAxis2_2[ind+(dime-1)] = -axis2
        else:
           bigArrayE2[ind+(dime-1)] = energies
           bigArrayAxis1_2[ind+(dime-1)] = axis1
           bigArrayAxis2_2[ind+(dime-1)] = axis2
        bigArrayC[ind] = coords
        bigArrayAxis1[ind] = axis1
        bigArrayAxis2[ind] = axis2
        ind += 1
    eneMin = np.min(bigArrayE)
    bigArrayEZero = bigArrayE - eneMin
    bigArrayE2Zero = bigArrayE2 - eneMin
    angleMin = np.min(bigArrayAxis1)
    bigArrayAxis1_2Zero = bigArrayAxis1_2 - angleMin
    labelsAxis1 = np.unique(bigArrayLab1)
    labelsAxis2 = np.unique(bigArrayLab2)
    #print(labelsAxis1,labelsAxis2)
    #[a,b,c] = [bigArrayB1[0:4], bigArrayB2[0:4], bigArrayE[0:4]]
    #print(a,b,c)
    #[a,b,c] = [bigArrayAxis1, bigArrayAxis2, bigArrayE]
    print(bigArrayD.shape)
    [a,b,c] = [bigArrayAxis1, bigArrayAxis2, bigArrayD[:,0,0,:]]
    #[a,b,c] = [bigArrayAxis1_2Zero, bigArrayAxis2_2, bigArrayE2Zero]
    #np.savetxt('1.txt', a)
    #np.savetxt('2.txt', b)
    #np.savetxt('3.txt', c)
    # (313,) (313,) (313, 14)
    #gnuSplotCircle(a,b,c)
    #plotlyZ(a,b,c)
    #print(a.shape, b.shape, c.shape)
    mathematicaListGenerator(a,b,c)
    print(a.shape, b.shape, c.shape)
示例#7
0
def matrixApproach(globalExp, proc, processed_states):
    '''
    Create blender files from 3d data... meraviglia
    '''
    allH5 = sorted(glob.glob(globalExp))
    dime = len(allH5)
    allH5First = allH5[0]
    nstates = len(retrieve_hdf5_data(allH5First, 'ROOT_ENERGIES'))
    natoms = len(retrieve_hdf5_data(allH5First, 'CENTER_COORDINATES'))
    print('\nnstates: {} \ndimension: {}'.format(nstates, dime))
    newdime = (dime * 2) - 1
    bigArrayLab1 = np.empty((dime), dtype=object)
    bigArrayLab2 = np.empty((dime), dtype=object)
    bigArrayLab3 = np.empty((dime), dtype=object)
    ind = 0
    for fileN in allH5:
        (axis1, str1, axis2, str2, axis3, str3) = stringTransformation3d(fileN)
        bigArrayLab1[ind] = str1
        bigArrayLab2[ind] = str2
        bigArrayLab3[ind] = str3
        ind += 1
    labelsAxis1_b = np.unique(bigArrayLab1)
    # I want ordered phi labels like if they're numbers
    orderedphi = [x for x in labelsAxis1_b if x[0] == 'N'
                  ][::-1] + [x for x in labelsAxis1_b if x[0] == 'P']
    labelsAxis1 = np.array(orderedphi, dtype=object)
    labelsAxis2 = np.unique(bigArrayLab2)
    labelsAxis3 = np.unique(bigArrayLab3)
    blenderArray = np.empty(
        (labelsAxis1.size, labelsAxis2.size, labelsAxis3.size, nstates))
    blenderArrayDipo = np.empty((3, processed_states, labelsAxis1.size,
                                 labelsAxis2.size, labelsAxis3.size, nstates))
    folder = ('/').join(globalExp.split('/')[:-1])
    if folder == '':
        folder = '.'
    ind = 0
    for Iax1 in range(labelsAxis1.size):
        ax1 = labelsAxis1[Iax1]
        for Iax2 in range(labelsAxis2.size):
            ax2 = labelsAxis2[Iax2]
            for Iax3 in range(labelsAxis3.size):
                ax3 = labelsAxis3[Iax3]
                singleLabel = ax1 + '_' + ax2 + '_' + ax3
                #fileNonly = 'zNorbornadiene_' + singleLabel + '.all.h5'
                fileNonly = 'zNorbornadiene_' + singleLabel + '.corrected.h5'
                #fileNonly = 'zNorbornadiene_' + singleLabel + '.refined.h5'
                fileN = folder + '/' + fileNonly
                exisT = os.path.exists(fileN)
                #print(exisT)
                if exisT:
                    energies = retrieve_hdf5_data(fileN, 'ROOT_ENERGIES')
                    dipole = retrieve_hdf5_data(fileN, 'DIPOLES')
                else:
                    energies = np.repeat(-271.0, nstates)
                    print(fileN + ' does not exist...')
                blenderArray[Iax1, Iax2, Iax3] = energies
                for xyz in np.arange(3):
                    for sss in np.arange(processed_states):
                        blenderArrayDipo[xyz, sss, Iax1, Iax2,
                                         Iax3] = dipole[xyz, sss, :]
    axFloat1 = np.array([labTranform(a) for a in labelsAxis1])
    axFloat2 = np.array([labTranform(b) for b in labelsAxis2])
    axFloat3 = np.array([labTranform(c) for c in labelsAxis3])
    axFloat1.tofile('fullA.txt')
    axFloat2.tofile('fullB.txt')
    axFloat3.tofile('fullC.txt')
    blenderArray.tofile('fullE.txt')
    for xyz in np.arange(3):
        for sss in np.arange(processed_states):
            elementSlice = blenderArrayDipo[xyz, sss, :]
            labl = {0: 'x', 1: 'y', 2: 'z'}
            name = 'fullD_' + labl[xyz] + '_' + str(sss) + '.txt'
            elementSlice.tofile(name)
示例#8
0
def createOutputFile(tupleI):
    '''
    given a projectname, creates single outFile (not yet corrected)
    tupleI :: (String,String) <- is composed by (fold,outFol)
    fold :: String <- the folder of a single calculation
    outFol :: String <- the folder where the output is collected
    '''
    (fold, outFol) = tupleI
    #print('doing ' + fold)
    folder = os.path.dirname(fold)
    proj = os.path.basename(fold)
    root = folder + '/' + proj + '/' + proj
    oroot = os.path.join(outFol, proj)
    h5rasscf = root + '.rasscf.h5'
    h5dipole = root + '.transDip.h5'
    h5rassi = root + '.rassi.h5'
    h5out = root + '.out'
    a_exist = all([
        os.path.isfile(f) for f in
        #[h5rassi,h5rasscf,h5dipole]])   Soon we will not need out anymore
        [h5rassi, h5rasscf, h5out, h5dipole]
    ])
    if a_exist:
        log = proj + ': all files present'

        boolean = True

        [geom, aType, ener] = retrieve_hdf5_data(
            h5rasscf, ['CENTER_COORDINATES', 'CENTER_LABELS', 'ROOT_ENERGIES'])

        [dipoles, transDen
         ] = retrieve_hdf5_data(h5dipole,
                                ['SFS_EDIPMOM', 'SFS_TRANSITION_DENSITIES'])
        [overlap] = retrieve_hdf5_data(h5rassi, ['ORIGINAL_OVERLAPS'])
        nstates = ener.size
        nstatesNAC = 8  # states for nac are actually 8
        natoms = aType.size
        # I want to save only the low left corner of overlap [nstates:,:nstates]
        if True:
            NAC = parseNAC(h5out, nstatesNAC, natoms)
        else:
            warning("NAC PARSING TURNED OFF")
            NAC = np.zeros((nstatesNAC, nstatesNAC, natoms, 3))

        outfile = oroot + '.all.h5'
        outTuple = [
            ('CENTER_COORDINATES', geom),
            ('CENTER_LABELS', aType),
            ('ROOT_ENERGIES', ener),
            ('DIPOLES', dipoles),
            #('CI_VECTORS', ciVect),
            #('TRANDENS',transDen),
            ('OVERLAP', overlap[nstates:, :nstates]),
            ('NAC', NAC)
        ]
        #print(overlap[nstates:,:nstates][:3,:3])
        #print(overlap)
        #try:
        #    if (overlap[nstates:,:nstates][:3,:3] == np.zeros((3,3))).all():
        #        log += 'dioK {}\n'.format(outfile)
        #except:
        #    err(oroot)

        try:
            writeH5file(outfile, outTuple)
        except "Unable to open file":
            print(outfile)
        # count_nonzero does not work anymore with the new thing
        log += ' -> ' + str(np.count_nonzero(NAC) / 2)
    else:
        log = proj + ': this calculation is not completed'
        boolean = False
    return (log, boolean)
示例#9
0
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))
示例#10
0
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:')
示例#11
0
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)
示例#12
0
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])
示例#13
0
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)
示例#14
0
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
示例#15
0
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