def compute_toverlaps_in_parallel( step ):
    """
    Function used for the making the computation of time-overlaps parallel via python multiprocessing 
    """
    st_sd = step3.mapping.ovlp_mat_arb(  sd_states_reindexed_sorted[step], sd_states_reindexed_sorted[step+1], St_ks[0][step], use_minimal=False )
    st_sd = data_conv.MATRIX2nparray(st_sd)
    return st_sd
예제 #2
0
def run_nbra_namd_wrapper(hvib, istate, outfile_name, params):
    """
    A small wrapper function to run the nbra namd dynamics. 
        hvib ( list of list of matrices ): The vibronic hamiltonian for all timesteps
        istate ( int ): Index of the initial state. This index is from 0
        outfile ( string ): The name of the output file
        params ( dict ): A dictionary of important dynamical parameters
    returns: A list of energy values that is the electronic energy vs time. Returned energy is in eV
    """

    print("decoherence_method = ", params["decoherence_method"])
    params["outfile"] = outfile_name
    params["nstates"] = hvib[0].num_of_rows
    params["istate"] = istate
    res_nbra_namd = step4.run([hvib], params)
    nbra_namd = data_conv.MATRIX2nparray(res_nbra_namd)
    # For SH energies
    energy_nbra_namd = (nbra_namd[:, 3 * params["nstates"] + 2] -
                        nbra_namd[:, 1]) * units.au2ev
    return energy_nbra_namd
예제 #3
0
def run_bllz_wrapper( hvib, istate, outfile_name, params ):
    """
    A small wrapper function to run the bllz dynamics. 
        hvib ( list of list of matrices ): The vibronic hamiltonian for all timesteps
        istate ( int ): Index of the initial state. This index is from 0
        outfile ( string ): The name of the output file
        params ( dict ): A dictionary of important dynamical parameters
    returns: A list of energy values that is the electronic energy vs time. Returned energy is in eV
    """

    params["outfile"]  = outfile_name
    params["nstates"]  = hvib[0].num_of_rows
    params["istate"]   = istate
    res_bllz, P = lz.run( [hvib], params )
    bllz_namd   = data_conv.MATRIX2nparray( res_bllz )
    # Recall that for bllz, we use the schrodiger not the surface hopping energy
    energy_bllz = ( bllz_namd[:,3*params["nstates"]+1] - bllz_namd[:,1] )*units.au2ev
    # for bllz surface hopping energy
    #energy_bllz = ( bllz_namd[:,3*params["nstates"]+2] - bllz_namd[:,1] )*units.au2ev
    return energy_bllz
예제 #4
0
def run_cp2k_xtb_step2(params):
    """
    This function runs the step2 for computing the MO overlaps for xTB calculations and saves them as sparse 
    matrices using scipy.sparse library. In order to load the saved sparse matrices you need to use
    scipy.sparse.load_npz command.

    Args:

        params (dictionary): A dictionary containing the following parameters:

                             res_dir (string): The directory for saving the MO overlaps.

                             all_logfiles (string): The directory to save all log files.

                             all_pdosfiles (string): The directory to save all pdos files.

                             istep (integer): The initial step.

                             fstep (integer): The final step.

                             init_state (integer): The initial state.

                             final_state (integer): The final state.

                             is_spherical (bool): Flag for spherical coordinates.

                             remove_molden (bool): Flag for removing the molden files after computing the MO overlaps.

                             nprocs (integer): Number of processors.

                             cp2k_ot_input_template (string): The CP2K OT input template file name.

                             cp2k_diag_input_template (string): The CP2K diagonalization input template file name.

                             trajectory_xyz_filename (string): The trajectory xyz file name.

                             step (integer): The time step.

                             cp2k_exe (string): The full path to CP2K executable.

    """
    # Making the required directories for gatherig all the information needed
    # including the overlap data and pdos files. The logfiles do not contain
    # specific data but we finally move them to all_logfiles
    if not os.path.exists(params['res_dir']):
        os.mkdir(params['res_dir'])
    if not os.path.exists(params['all_logfiles']):
        os.mkdir(params['all_logfiles'])
    if not os.path.exists(params['all_pdosfiles']):
        os.mkdir(params['all_pdosfiles'])
    # setting up the initial step and final step
    istep = params['istep']
    fstep = params['fstep']
    # spherical or cartesian GTOs
    is_spherical = params['is_spherical']
    # number of processors
    nprocs = params['nprocs']
    # the counter for a job steps, this counter is needed for not reading
    # the data of a molden file twice
    counter = 0
    print('-----------------------Start-----------------------')
    for step in range(istep, fstep):
        # a timer for all the procedure
        t1_all = time.time()
        print('-----------------------Step %d-----------------------' % step)
        params['step'] = step
        # timer for CP2K
        t1 = time.time()
        CP2K_methods.run_cp2k_xtb(params)
        print('Done with step', step, 'Elapsed time:', time.time() - t1)
        # now if the counter is equal to zero
        # just compute the MO overlap of that step.
        if counter == 0:
            t1 = time.time()
            print('Creating shell...')
            shell_1, l_vals = molden_methods.molden_file_to_libint_shell('Diag_%d-libra-1_0.molden'%step,\
                                                                          is_spherical)
            print('Done with creating shell. Elapsed time:', time.time() - t1)
            t1 = time.time()
            print('Reading energies and eigenvectors....')
            eig_vect_1, energies_1 = molden_methods.eigenvectors_molden('Diag_%d-libra-1_0.molden'%step,\
                                                                        nbasis(shell_1),l_vals)
            print('Done with reading energies and eigenvectors. Elapsed time:',
                  time.time() - t1)
            if params['remove_molden']:
                os.system('rm Diag_%d-libra-1_0.molden' % step)
            print('Computing atomic orbital overlap matrix...')
            t1 = time.time()
            AO_S = compute_overlaps(shell_1, shell_1, nprocs)
            print('Done with computing atomic orbital overlaps. Elapsed time:',
                  time.time() - t1)
            t1 = time.time()
            print('Turning the MATRIX to numpy array...')
            AO_S = data_conv.MATRIX2nparray(AO_S)
            print('Done with transforming MATRIX 2 numpy array. Elapsed time:',
                  time.time() - t1)
            istate = params['init_state']
            fstate = params['final_state']
            ## Now, we need to resort the eigenvectors based on the new indices
            print('Resorting eigenvectors elements...')
            t1 = time.time()
            new_indices = CP2K_methods.resort_molog_eigenvectors(l_vals)
            eigenvectors_1 = []
            for j in range(len(eig_vect_1)):
                # the new and sorted eigenvector
                eigenvector_1 = eig_vect_1[j]
                eigenvector_1 = eigenvector_1[new_indices]
                # append it to the eigenvectors list
                eigenvectors_1.append(eigenvector_1)
            eigenvectors_1 = np.array(eigenvectors_1)
            print('Done with resorting eigenvectors elements. Elapsed time:',
                  time.time() - t1)
            ##
            t1 = time.time()
            print('Computing and saving molecular orbital overlaps...')
            # Note that we choose the data from istate to fstate
            # the values for istate and fstate start from 1
            S = np.linalg.multi_dot([eigenvectors_1, AO_S,
                                     eigenvectors_1.T])[istate - 1:fstate - 1,
                                                        istate - 1:fstate - 1]
            # creating zero matrix
            mat_block_size = len(S)
            zero_mat = np.zeros((mat_block_size, mat_block_size))
            S_step = data_conv.form_block_matrix(S, zero_mat, zero_mat, S)
            # Since a lot of the data are zeros we save them as sparse matrices
            S_step_sparse = scipy.sparse.csc_matrix(S_step)
            E_step = data_conv.form_block_matrix(np.diag(energies_1)[istate-1:fstate-1,istate-1:fstate-1],\
                                                 zero_mat,zero_mat,\
                                                 np.diag(energies_1)[istate-1:fstate-1,istate-1:fstate-1])
            E_step_sparse = scipy.sparse.csc_matrix(E_step)
            scipy.sparse.save_npz(params['res_dir'] + '/S_ks_%d.npz' % step,
                                  S_step_sparse)
            scipy.sparse.save_npz(params['res_dir'] + '/E_ks_%d.npz' % step,
                                  E_step_sparse)
            print(
                'Done with computing molecular orbital overlaps. Elapsed time:',
                time.time() - t1)
            print('Done with step %d.' % step, 'Elapsed time:',
                  time.time() - t1_all)
        else:
            # The same procedure as above but now we compute time-overlaps as well
            t1 = time.time()
            print('Creating shell...')
            shell_2, l_vals = molden_methods.molden_file_to_libint_shell('Diag_%d-libra-1_0.molden'%step,\
                                                                          is_spherical)
            print('Done with creating shell. Elapsed time:', time.time() - t1)
            t1 = time.time()
            print('Reading energies and eigenvectors....')
            eig_vect_2, energies_2 = molden_methods.eigenvectors_molden('Diag_%d-libra-1_0.molden'%step,\
                                                                        nbasis(shell_2),l_vals)
            print('Done with reading energies and eigenvectors. Elapsed time:',
                  time.time() - t1)
            if params['remove_molden']:
                os.system('rm Diag_%d-libra-1_0.molden' % step)
            print('Computing atomic orbital overlap matrix...')
            t1 = time.time()
            AO_S = compute_overlaps(shell_2, shell_2, nprocs)
            AO_St = compute_overlaps(shell_1, shell_2, nprocs)
            print('Done with computing atomic orbital overlaps. Elapsed time:',
                  time.time() - t1)
            t1 = time.time()
            print('Turning the MATRIX to numpy array...')
            AO_S = data_conv.MATRIX2nparray(AO_S)
            AO_St = data_conv.MATRIX2nparray(AO_St)
            print('Done with transforming MATRIX 2 numpy array. Elapsed time:',
                  time.time() - t1)
            ## Now, we need to resort the eigenvectors based on the new indices
            print('Resorting eigenvectors elements...')
            t1 = time.time()
            new_indices = CP2K_methods.resort_molog_eigenvectors(l_vals)
            eigenvectors_2 = []
            for j in range(len(eig_vect_2)):
                # the new and sorted eigenvector
                eigenvector_2 = eig_vect_2[j]
                eigenvector_2 = eigenvector_2[new_indices]
                # append it to the eigenvectors list
                eigenvectors_2.append(eigenvector_2)
            eigenvectors_2 = np.array(eigenvectors_2)
            print('Done with resorting eigenvectors elements. Elapsed time:',
                  time.time() - t1)
            ##
            t1 = time.time()
            print('Computing and saving molecular orbital overlaps...')
            S = np.linalg.multi_dot([eigenvectors_2, AO_S,
                                     eigenvectors_2.T])[istate - 1:fstate - 1,
                                                        istate - 1:fstate - 1]
            St = np.linalg.multi_dot([eigenvectors_1, AO_S,
                                      eigenvectors_2.T])[istate - 1:fstate - 1,
                                                         istate - 1:fstate - 1]
            S_step = data_conv.form_block_matrix(S, zero_mat, zero_mat, S)
            St_step = data_conv.form_block_matrix(St, zero_mat, zero_mat, St)
            S_step_sparse = scipy.sparse.csc_matrix(S_step)
            St_step_sparse = scipy.sparse.csc_matrix(St_step)
            E_step = data_conv.form_block_matrix(np.diag(energies_2)[istate-1:fstate-1,istate-1:fstate-1],\
                                                 zero_mat,zero_mat,\
                                                 np.diag(energies_2)[istate-1:fstate-1,istate-1:fstate-1])
            E_step_sparse = scipy.sparse.csc_matrix(E_step)
            scipy.sparse.save_npz(params['res_dir'] + '/S_ks_%d.npz' % step,
                                  S_step_sparse)
            scipy.sparse.save_npz(
                params['res_dir'] + '/St_ks_%d.npz' % (step - 1),
                St_step_sparse)
            scipy.sparse.save_npz(params['res_dir'] + '/E_ks_%d.npz' % step,
                                  E_step_sparse)
            print(
                'Done with computing molecular orbital overlaps. Elapsed time:',
                time.time() - t1)
            shell_1 = shell_2
            energies_1 = energies_2
            eigenvectors_1 = eigenvectors_2
            print('Removing unnecessary wfn files...')
            os.system('rm OT_%d-RESTART*' % (step - 1))
            os.system('rm Diag_%d-RESTART*' % (step - 1))
            print('Done with step %d.' % step, 'Elapsed time:',
                  time.time() - t1_all)
        counter += 1
    # Finally move all the pdos and log files to all_pdosfiles and all_logfiles
    os.system('mv *pdos %s/.' % params['all_pdosfiles'])
    os.system('mv *log %s/.' % params['all_logfiles'])
    print('Done with the job!!!')
예제 #5
0
clrs_index = ["11", "21", "31", "41", "12", "22", "32", "13", "23", "14", "24"]

E_f = 2.1608
spd = ["s", "p", "d"]
all_atoms = list(range(1, 67))

Cs = [spd, all_atoms, ["Cs"]]
Sn = [spd, all_atoms, ["Sn"]]
Br = [spd, all_atoms, ["Br"]]
projections = [Cs, Sn, Br]

E, pdosa, pdosb = pdos.QE_pdos("pdos/x.pdos_atm#", -10.0, 10.0, 0.1, projections,\
                               E_f, "pdos_", 1, 0.01, 0.1, nspin=1)

e_grid = data_conv.MATRIX2nparray(E)
proja = data_conv.MATRIX2nparray(pdosa)
projb = data_conv.MATRIX2nparray(pdosb)

print(e_grid.shape, proja.shape, projb.shape)


def plot(_energy, _pdosa, _pdosb):

    plt.rc('axes', titlesize=18)  # fontsize of the axes title
    plt.rc('axes', labelsize=18)  # fontsize of the x and y labels
    plt.rc('legend', fontsize=12)  # legend fontsize
    plt.rc('xtick', labelsize=18)  # fontsize of the tick labels
    plt.rc('ytick', labelsize=18)  # fontsize of the tick labels

    plt.ylim(-5.0, 5.0)
예제 #6
0
from libra_py import CP2K_methods
from libra_py import molden_methods
from libra_py import data_conv

# number of processors
nprocs = 4
# set up the timer
t1 = time.time()
# creating the shell for the molden file
shells_1, l_vals = molden_methods.molden_file_to_libint_shell('CdSe13-CdSe13-1_0.molden',True)
# extracting the eigenvectors and energies from molden file
eig1, ener1 = molden_methods.eigenvectors_molden('CdSe13-CdSe13-1_0.molden',nbasis(shells_1),l_vals)
# compute the AO overlap matrix
AO = compute_overlaps(shells_1,shells_1,nprocs)
# turn it into a numpy array
AO = data_conv.MATRIX2nparray(AO)
# new indices for the the MOLog eigenvectors 
new_indices = CP2K_methods.resort_molog_eigenvectors(l_vals)
# making all the reindexed eigenvectors
eigenvectors = []
for i in range(len(eig1)):
    # the new and sorted eigenvector
    eigenvector = eig1[i]
    eigenvector = eigenvector[new_indices]
    # append it to the eigenvectors list
    eigenvectors.append(eigenvector)
# make it a numpy array to be able to work with    
eigs = np.array(eigenvectors)
# compute the MO overlap
S = np.linalg.multi_dot([eigs, AO ,eigs.T])
# print out the diagonal element of the MO overlap matrix
예제 #7
0
ANN.init_weights_biases_uniform(rnd, -0.1, 0.1, -0.1, 0.1)
params = {
    "num_epochs": 100,
    "steps_per_epoch": 10000,
    "epoch_size": 32,
    "learning_rate": 0.05,
    "verbosity": 1
}
ANN.train(rnd, params, inputs1, targets1)
Y_train = ANN.propagate(inputs1)
Y_test = ANN.propagate(inputs2)
#sys.exit(0)

#x_train = data_conv.MATRIX2nparray(inputs1)[0][:]
#x_test = data_conv.MATRIX2nparray(inputs2)[0][:]
y_train = data_conv.MATRIX2nparray(Y_train[2])[0][:]
y_test = data_conv.MATRIX2nparray(Y_test[2])[0][:]
eg_target1 = data_conv.MATRIX2nparray(targets1)[0][:]
eg_target2 = data_conv.MATRIX2nparray(targets2)[0][:]
time1 = np.array(time1)
time2 = np.array(time2)
#print(x.shape, y.shape, eg_target2.shape)
#sys.exit(0)

plt.figure(num=None,
           figsize=(3.21, 2.41),
           dpi=300,
           edgecolor='black',
           frameon=True)
plt.subplot(1, 1, 1)
plt.title('Lumo Energy - Training',
예제 #8
0
def myfunc_st( step ):
    st_sd = step3.mapping.ovlp_mat_arb(  sd_states_reindexed_sorted[step], sd_states_reindexed_sorted[step+1], St_ks_job[0][step], use_minimal=False )
    #print(step, "st_sd as CMATRIX  <1|1> = ", st_sd.get(1,1) )
    st_sd = data_conv.MATRIX2nparray(st_sd)
    #print(step, "st_sd as np.array <1|1> = ", st_sd[1,1])
    return st_sd
예제 #9
0
def myfunc(subtraj):

    start_time = subtraj * subtraj_increment

    print("\nsubtraj ", subtraj)
    print("start time = ", start_time)
    print("end time   = ", start_time + subtraj_len)

    md_time = [i for i in range(subtraj_len)]
    md_time = np.array(md_time) * params["dt"] * units.au2fs

    # Obtain the subtrajectory
    for i in range(start_time, start_time + subtraj_len):
        hvib_mb_subtrajs[subtraj].append(hvib_mb[0][i])
        hvib_sd_subtrajs[subtraj].append(hvib_sd[0][i])

    # Compute mb energy gaps and decoherence times
    params["nsteps"] = subtraj_len
    params["init_times"] = [0]
    tau_mb, rates_mb = decoherence_times.decoherence_times(
        hvib_mb_subtrajs[subtraj])
    dE_mb = decoherence_times.energy_gaps(hvib_mb_subtrajs[subtraj])
    avg_deco_mb = tau_mb * units.au2fs
    print("Finished gather data for MD time",
          params["init_times"][0] + params["nsteps"], "steps.")
    print("Dephasing time between mb states 0 and 1 is:",
          tau_mb.get(0, 1) * units.au2fs, "fs")

    # Compute sd energy gaps and decoherence times
    params["nsteps"] = subtraj_len
    params["init_times"] = [0]
    tau_sd, rates_sd = decoherence_times.decoherence_times(
        hvib_sd_subtrajs[subtraj])
    dE_sd = decoherence_times.energy_gaps(hvib_sd_subtrajs[subtraj])
    avg_deco_sd = tau_sd * units.au2fs
    print("Finished gather data for MD time",
          params["init_times"][0] + params["nsteps"], "steps.")
    print("Dephasing time between sd states 0 and 1 is:",
          tau_sd.get(0, 1) * units.au2fs, "fs")

    # Compute mb energies
    mb_subtraj_energy = []
    params["nstates"] = 31
    for mb_index in range(params["nstates"]):
        mb_subtraj_energy.append([])
        for step in range(params["nsteps"]):
            mb_subtraj_energy[mb_index].append(
                hvib_mb_subtrajs[subtraj][step].get(mb_index, mb_index).real -
                hvib_mb_subtrajs[subtraj][step].get(0, 0).real)
    mb_subtraj_energy = np.array(mb_subtraj_energy)
    tmp_mb_energies.append(mb_subtraj_energy)

    # Compute sd energies
    params["nstates"] = 64
    sd_subtraj_energy = []
    for sd_index in range(params["nstates"]):
        sd_subtraj_energy.append([])
        for step in range(params["nsteps"]):
            sd_subtraj_energy[sd_index].append(
                hvib_sd_subtrajs[subtraj][step].get(sd_index, sd_index).real -
                hvib_sd_subtrajs[subtraj][step].get(0, 0).real)
    sd_subtraj_energy = np.array(sd_subtraj_energy)
    tmp_sd_energies.append(sd_subtraj_energy)

    ###############################################
    ###############################################
    # Now it is time to run the NAMD
    params["T"] = 300.0
    params["ntraj"] = 250
    params["sh_method"] = 1
    params["Boltz_opt"] = 1

    params["nsteps"] = subtraj_len
    params["init_times"] = [0]

    istates = [14, 18]

    for istate in istates:

        params["istate"] = istate  # Recall index from 0

        ### FSSH
        params["decoherence_method"] = 0
        start = time.time()
        # mb fssh
        params["outfile"] = "_out_mb_fssh_subtraj_" + str(
            subtraj) + "_istate" + str(istate) + ".txt"
        params["nstates"] = 31  # total number of mb electronic states
        res_mb_fssh = step4.run([hvib_mb_subtrajs[subtraj]], params)
        mb_nbra_namd = data_conv.MATRIX2nparray(res_mb_fssh)
        tmp_fssh_mb.append(mb_nbra_namd)
        mb_hot_energy_fssh = (mb_nbra_namd[:, 95] -
                              mb_nbra_namd[:, 1]) * units.au2ev
        #sys.exit(0)

        #sd fssh
        params["outfile"] = "_out_sd_fssh_subtraj_" + str(
            subtraj) + "_istate" + str(istate) + ".txt"
        params["nstates"] = 64  # total number of sd electronic states
        res_sd_fssh = step4.run([hvib_sd_subtrajs[subtraj]], params)
        sd_nbra_namd = data_conv.MATRIX2nparray(res_sd_fssh)
        tmp_fssh_sd.append(sd_nbra_namd)
        sd_hot_energy_fssh = (sd_nbra_namd[:, 194] -
                              sd_nbra_namd[:, 1]) * units.au2ev
        end = time.time()
        print("Time to run NBRA NAMD = ", end - start)

        ### IDA
        params["decoherence_method"] = 1
        start = time.time()
        # mb ida
        params["outfile"] = "_out_mb_ida_subtraj_" + str(
            subtraj) + "_istate" + str(istate) + ".txt"
        params["nstates"] = 31  # total number of mb electronic states
        res_mb_ida = step4.run([hvib_mb_subtrajs[subtraj]], params)
        mb_nbra_namd = data_conv.MATRIX2nparray(res_mb_ida)
        tmp_ida_mb.append(mb_nbra_namd)
        mb_hot_energy_ida = (mb_nbra_namd[:, 95] -
                             mb_nbra_namd[:, 1]) * units.au2ev

        #sd ida
        params["outfile"] = "_out_sd_ida_subtraj_" + str(
            subtraj) + "_istate" + str(istate) + ".txt"
        params["nstates"] = 64  # total number of sd electronic states
        res_sd_ida = step4.run([hvib_sd_subtrajs[subtraj]], params)
        sd_nbra_namd = data_conv.MATRIX2nparray(res_sd_ida)
        tmp_ida_sd.append(sd_nbra_namd)
        sd_hot_energy_ida = (sd_nbra_namd[:, 194] -
                             sd_nbra_namd[:, 1]) * units.au2ev
        end = time.time()
        print("Time to run NBRA NAMD = ", end - start)

        ### mSDM
        params["decoherence_method"] = 2
        start = time.time()
        # mb msdm
        params["outfile"] = "_out_mb_msdm_subtraj_" + str(
            subtraj) + "_istate" + str(istate) + ".txt"
        params["nstates"] = 31  # total number of mb electronic states
        res_mb_msdm = step4.run([hvib_mb_subtrajs[subtraj]], params)
        mb_nbra_namd = data_conv.MATRIX2nparray(res_mb_msdm)
        tmp_msdm_mb.append(mb_nbra_namd)
        mb_hot_energy_msdm = (mb_nbra_namd[:, 95] -
                              mb_nbra_namd[:, 1]) * units.au2ev

        #sd msdm
        params["outfile"] = "_out_sd_msdm_subtraj_" + str(
            subtraj) + "_istate" + str(istate) + ".txt"
        params["nstates"] = 64  # total number of sd electronic states
        res_sd_msdm = step4.run([hvib_sd_subtrajs[subtraj]], params)
        sd_nbra_namd = data_conv.MATRIX2nparray(res_sd_msdm)
        tmp_msdm_sd.append(sd_nbra_namd)
        sd_hot_energy_msdm = (sd_nbra_namd[:, 194] -
                              sd_nbra_namd[:, 1]) * units.au2ev
        end = time.time()
        print("Time to run NBRA NAMD = ", end - start)

        plt.figure(num=None,
                   figsize=(3.21, 2.41),
                   dpi=300,
                   edgecolor='black',
                   frameon=True)
        plt.subplot(1, 1, 1)
        plt.title('(CdSe)$_{33}$ MB traj' + str(subtraj) + ' istate' +
                  str(istate) + '',
                  fontsize=10)
        plt.xlabel('Time, fs', fontsize=10)
        plt.ylabel('Energy, eV', fontsize=10)
        plt.ylim(0, 3.5)
        plt.yticks([0, 1, 2, 3])
        for sd_index in range(31):
            plt.plot(md_time,
                     mb_subtraj_energy[sd_index] * units.au2ev,
                     label="",
                     linewidth=1,
                     color="gray")
        plt.plot(md_time,
                 mb_hot_energy_fssh,
                 linewidth=2.5,
                 color="red",
                 label="FSSH")
        plt.plot(md_time,
                 mb_hot_energy_ida,
                 linewidth=2.5,
                 color="green",
                 label="IDA")
        plt.plot(md_time,
                 mb_hot_energy_msdm,
                 linewidth=2.5,
                 color="blue",
                 label="mSDM")
        plt.tight_layout()
        plt.legend(fontsize=8, ncol=3, loc="lower left")
        plt.savefig("CdSe33_MB_Dyn_" + str(subtraj) + "_" + str(istate) +
                    ".png",
                    dpi=300)

        plt.figure(num=None,
                   figsize=(3.21, 2.41),
                   dpi=300,
                   edgecolor='black',
                   frameon=True)
        plt.subplot(1, 1, 1)
        plt.title('(CdSe)$_{33}$ SP traj' + str(subtraj) + ' istate' +
                  str(istate) + '',
                  fontsize=10)
        plt.xlabel('Time, fs', fontsize=10)
        plt.ylabel('Energy, eV', fontsize=10)
        plt.ylim(0, 3.5)
        plt.yticks([0, 1, 2, 3])
        for sd_index in range(64):
            plt.plot(md_time,
                     sd_subtraj_energy[sd_index] * units.au2ev,
                     label="",
                     linewidth=1,
                     color="gray")
        plt.plot(md_time,
                 sd_hot_energy_fssh,
                 linewidth=2.5,
                 color="red",
                 label="FSSH")
        plt.plot(md_time,
                 sd_hot_energy_ida,
                 linewidth=2.5,
                 color="green",
                 label="IDA")
        plt.plot(md_time,
                 sd_hot_energy_msdm,
                 linewidth=2.5,
                 color="blue",
                 label="mSDM")
        plt.tight_layout()
        plt.legend(fontsize=8, ncol=3, loc="lower left")
        plt.savefig("CdSe33_" + str(subtraj) + "_SP_Dyn_" + str(istate) +
                    ".png",
                    dpi=300)
예제 #10
0
def plot_training(_plt,
                  _ann,
                  _training_input,
                  _training_target,
                  mode1=0,
                  mode2=2,
                  filename="ANN_training.png"):
    """
    Args: 
        _plt (matplotlib instance)
        _ann (NeuralNetwork object)
        _training_input ( MATRIX(n_inputs, n_patterns )
        _training_target ( MATRIX(n_outputs, n_patterns )

    """

    last_indx = _ann.Nlayers - 1

    # Predict
    # There is only 1 output in this case - we take the first index
    training_out = _ann.propagate(_training_input)
    y_predict = data_conv.MATRIX2nparray(training_out[last_indx])[0, :]

    #print(F"len(training_out) = {len(training_out)}")
    #print(F"len(y_predict) = {len(y_predict)}")

    # Given targets
    # Targets also have only 1 components in this case
    y_targets = data_conv.MATRIX2nparray(_training_target)[0, :]

    #print(F"len(y_targets) = {len(y_targets)}")

    nsteps = len(y_predict)  # one less, so it would work for NACs too
    steps_train = list(range(nsteps))

    #print(F"nsteps = {nsteps}")
    #print(F"steps_trian = {steps_train}")

    x_mode1 = data_conv.MATRIX2nparray(_training_input)[mode1, :]

    x_mode2 = data_conv.MATRIX2nparray(_training_input)[mode2, :]

    #print(x_mode1)
    #print(x_mode2)

    _plt.rc('axes', titlesize=12)  # fontsize of the axes title
    _plt.rc('axes', labelsize=12)  # fontsize of the x and y labels
    _plt.rc('legend', fontsize=10)  # legend fontsize
    _plt.rc('xtick', labelsize=8)  # fontsize of the tick labels
    _plt.rc('ytick', labelsize=8)  # fontsize of the tick labels
    _plt.rc('figure.subplot', left=0.2)
    _plt.rc('figure.subplot', right=0.95)
    _plt.rc('figure.subplot', bottom=0.13)
    _plt.rc('figure.subplot', top=0.88)

    figure = _plt.figure(num=None,
                         figsize=(3.21 * 3, 2.41),
                         dpi=300,
                         edgecolor='black',
                         frameon=True)

    _plt.subplot(1, 3, 1)
    _plt.xlabel('Timestep', fontsize=10)
    _plt.ylabel('Property', fontsize=10)
    _plt.plot(steps_train,
              y_predict[:nsteps],
              color="black",
              label="ANN",
              linewidth=2)
    _plt.plot(steps_train,
              y_targets[:nsteps],
              color="green",
              label="reference",
              linewidth=2)
    _plt.legend(fontsize=6.75, ncol=1, loc='upper left')

    _plt.subplot(1, 3, 2)
    _plt.xlabel(F'Mode {mode1}', fontsize=10)
    _plt.ylabel('Property', fontsize=10)
    x_mode1 = data_conv.MATRIX2nparray(_training_input)[mode1, :]
    _plt.plot(x_mode1[:nsteps],
              y_predict[:nsteps],
              color="black",
              label="ANN",
              linewidth=2)
    _plt.plot(x_mode1[:nsteps],
              y_targets[:nsteps],
              color="green",
              label="reference",
              linewidth=2)
    _plt.legend(fontsize=6.75, ncol=1, loc='upper left')

    _plt.subplot(1, 3, 3)
    _plt.xlabel(F'Mode {mode2}', fontsize=10)
    _plt.ylabel('Property', fontsize=10)
    x_mode2 = data_conv.MATRIX2nparray(_training_input)[mode2, :]
    _plt.plot(x_mode2[:nsteps],
              y_predict[:nsteps],
              color="black",
              label="ANN",
              linewidth=2)
    _plt.plot(x_mode2[:nsteps],
              y_targets[:nsteps],
              color="green",
              label="reference",
              linewidth=2)
    _plt.legend(fontsize=6.75, ncol=1, loc='upper left')

    _plt.tight_layout()
    _plt.savefig(filename, dpi=300)
    _plt.show()