Exemple #1
0
def preprocess(feature_abstract_method):
    # X_raw = raw_data.iloc[:, 1:]
    # y_raw = raw_data['label']
    # X_train, X_test, y_train, y_test = train_test_split(X_raw, y_raw, test_size=0.2)
    # X_train.to_csv('x_train.csv')
    # X_test.to_csv('x_test.csv')
    # y_train.to_csv('y_train.csv')
    # y_test.to_csv('y_test.csv')
    X_train = pd.read_csv('x_train.csv', index_col=0)
    X_test = pd.read_csv('x_test.csv', index_col=0)
    y_train = pd.read_csv('y_train.csv', index_col=0, header=None)
    y_test = pd.read_csv('y_test.csv', index_col=0, header=None)
    if (feature_abstract_method == 'LBP'):
        X_train = LBP.lbp_extract(X_train)
        X_test = LBP.lbp_extract(X_test)
    elif (feature_abstract_method == 'PCA'):
        X_train, X_test = PCA.PCA_extract(X_train, X_test)
    elif (feature_abstract_method == 'skeleton'):
        X_train = SKELETON.skeleton_extract(X_train)
        X_test = SKELETON.skeleton_extract(X_test)
    elif (feature_abstract_method == 'grid'):
        X_train = GRID.grid_extract(X_train)
        X_test = GRID.grid_extract(X_test)
    elif (feature_abstract_method == 'hog'):
        X_train = HOG.hog_extract(X_train)
        X_test = HOG.hog_extract(X_test)
    return X_train, X_test, y_train, y_test
Exemple #2
0
def plot_wf_rad(rmin,rmax,npoints,coeffs,rgrid,nlobs,nbins,nvecs):
    """plot the selected wavefunctions functions"""
    """ Only radial part is plotted"""

    r = np.linspace(rmin,rmax,npoints,endpoint=True,dtype=float)

    x=np.zeros(nlobs)
    w=np.zeros(nlobs)
    x,w=GRID.gauss_lobatto(nlobs,14)
    w=np.array(w)
    x=np.array(x) # convert back to np arrays
    nprint = 1 #how many functions to print

    y = np.zeros(len(r))
    theta0 = 0.0
    phi0 = 0.0

    #counter = 0

    for ivec in range(nvecs):
        y = np.zeros(len(r))
        for ipoint in coeffs:

            y +=  ipoint[5][ivec] * chi(ipoint[0],ipoint[1],r,rgrid,w,nlobs,nbins) * spharm(ipoint[3], ipoint[4], theta0, phi0).real


        plt.plot(r, np.abs(y)**2/max(np.abs(y)**2), '-',label=str(ivec)) 

    plt.xlabel('r/a.u.')
    plt.ylabel('Radial eigenfunction')
    plt.legend()   
    plt.show()     
Exemple #3
0
def plot_chi(rmin,rmax,npoints,rgrid,nlobs,nbins):
    """plot the selected radial basis functions"""
    r = np.linspace(rmin, rmax, npoints, endpoint=True, dtype=float)

    x=np.zeros(nlobs)
    w=np.zeros(nlobs)
    x,w=GRID.gauss_lobatto(nlobs,14)
    w=np.array(w)
    x=np.array(x) # convert back to np arrays

    y = np.zeros((len(r), nbins * nlobs))

    counter = 0
    wcounter = 0
    for i in range(nbins):
        for n in range(nlobs-1):
            y[:,counter] = chi(i, n, r, rgrid ,w, nlobs, nbins) #* w[wcounter]**(0.5)
            counter += 1
        wcounter +=1

    figLob = plt.figure()
    plt.xlabel('r/a.u.')
    plt.ylabel('Lobatto basis function')
    plt.legend()   

    plt.plot(r, y) 
    plt.show()     
Exemple #4
0
def plot_wf_angrad_int_XY(rmin,rmax,npoints,nlobs,nbins,psi,maparray,Gr,params,t,flist,irun):
    #================ radial-angular in real space ===============#

    coeff_thr = 1e-6
    ncontours = 100

    fig = plt.figure(figsize=(4, 4), dpi=200, constrained_layout=True)
    spec = gridspec.GridSpec(ncols=1, nrows=1, figure=fig)
    axradang_r = fig.add_subplot(spec[0, 0], projection='polar')

    rang = np.linspace(rmin, rmax, npoints, endpoint=True, dtype=float)
    unity_vec = np.linspace(0.0, 1.0, npoints, endpoint=True, dtype=float)
    gridphi1d = 2 * np.pi * unity_vec

    rmesh, thetamesh = np.meshgrid(rang, gridphi1d)

    x   =  np.zeros(nlobs)
    w   =  np.zeros(nlobs)
    x,w =  GRID.gauss_lobatto(nlobs,14)
    w   =  np.array(w)
    x   =  np.array(x) # convert back to np arrays

    y = np.zeros((len(rang),len(rang)), dtype=complex)

    theta0 = np.pi/2 #fixed azimuthal angle

    #here we can do phi-averaging
    
    for ielem, elem in enumerate(maparray):
        if np.abs(psi[ielem]) > coeff_thr:
            #print(str(elem) + str(psi[ielem]))

            chir = flist[elem[2]-1](rang) #labelled by xi

            for i in range(len(rang)):
                y[i,:] +=  psi[ielem]  * spharm(elem[3], elem[4], theta0, gridphi1d[i]) * \
                           chir #chi(elem[0], elem[1], rang[:], Gr, w, nlobs, nbins) 

    line_angrad_r = axradang_r.contourf(thetamesh, rmesh, np.abs(y)/np.max(np.abs(y)), 
                                        ncontours, cmap = 'jet', vmin=0.0, vmax=1.0) #vmin=0.0, vmax=1.0cmap = jet, gnuplot, gnuplot2
    #plt.colorbar(line_angrad_r, ax=axradang_r, aspect=30)
    axradang_r.set_rlabel_position(100)
    #axradang_r.set_yticklabels(list(str(np.linspace(rmin,rmax,5.0)))) # set radial tick label
    #plt.legend()   
    #plt.show()  
    if params["save_snapthots"] == True:
        if params['field_type']['function_name'] == "fieldCPL":
            if params['field_type']['typef'] == "LCPL":
                helicity = "L"
            elif params['field_type']['typef'] == "RCPL":
                helicity = "R"
        else:
            helicity = "0"
        fig.savefig( params['job_directory']  + "/animation/" + helicity + "_angrad_XY" + "_" + str(irun) + "_t=" +\
                     str("%4.1f"%(t/np.float64(1.0/24.188)))+"_.png" ,\
                     bbox_inches='tight')
    plt.close()
Exemple #5
0
def plot_initial_orbitals(params,maparray,orbitals):
    maparray = np.asarray(maparray)

    nlobs = params['bound_nlobs']
    nbins = params['bound_nbins'] 
    npoints = 360
    rmax    = nbins * params['bound_binw']
    rmin = 0.0
    Gr_all, Nr_all = GRID.r_grid_prim( params['bound_nlobs'], nbins , params['bound_binw'],  params['bound_rshift'] )

    maparray_chi, Nbas_chi = MAPPING.GENMAP_FEMLIST( params['FEMLIST'],  0, \
                                params['map_type'], params['job_directory'] )

    flist = interpolate_chi(Gr_all, params['bound_nlobs'], nbins, params['bound_binw'], maparray_chi)
    
    for iorb in range(params['ivec']+2):
        psi = orbitals[:,iorb]
        plot_iorb(rmin,rmax,npoints,nlobs,nbins,psi,maparray,params,flist,iorb)
Exemple #6
0
def calc_wf_xyzgrid_int(params,ivec,Gr,wffile,grid):

    nlobs = params['bound_nlobs']
    nbins = params['bound_nbins']
    binw = params['bound_binw']
    
    coeffs = read_coeffs(wffile,ivec+1)

    xl      =   np.zeros(nlobs)
    w       =   np.zeros(nlobs)
    xl,w    =   GRID.gauss_lobatto(nlobs,14)
    w       =   np.array(w)

    X, Y, Z = grid[0], grid[1], grid[2]
    #print(X.shape)
    val = np.zeros((X.shape[0] * X.shape[0] * X.shape[0]), dtype = complex)

    chilist = PLOTS.interpolate_chi(    Gr_prim, 
                                        params['bound_nlobs'], 
                                        params['bound_nbins'], 
                                        params['bound_binw'], 
                                        maparray_chi)


    rx,thetax,phix  = cart2sph(X,Y,Z)
    r               = rx.flatten()
    theta           = thetax.flatten()
    phi             = phix.flatten()

    #print(theta.shape)
    #print(np.shape(coeffs))
    #print(type(coeffs))


    for icount, ipoint in enumerate(coeffs):
        print(icount)
        #print(ipoint[5][ivec])
        if np.abs(ipoint[5][ivec]) > 1e-3:
            val +=  ipoint[5][ivec] * chi(ipoint[0], ipoint[1],r,Gr,w,nlobs,nbins) * spharm(ipoint[3], ipoint[4], theta, phi)

    #val *= np.sin(theta) 
    #val.real/(np.max(val))#
    return  np.abs(val)**2/ (np.max(np.abs(val)**2))
Exemple #7
0
def plot_wf_ang(r0,coeffs,rgrid, nlobs,nbins):
    """plot the angular basis"""
    theta_1d = np.linspace(0,   np.pi,  2*91) # 
    phi_1d   = np.linspace(0, 2*np.pi, 2*181) # 

    theta_2d, phi_2d = np.meshgrid(theta_1d, phi_1d)
    xyz_2d = np.array([np.sin(theta_2d) * np.sin(phi_2d), np.sin(theta_2d) * np.cos(phi_2d), np.cos(theta_2d)]) #2D grid of cartesian coordinates

    colormap = cm.ScalarMappable( cmap=plt.get_cmap("cool") )
    colormap.set_clim(-.45, .45)
    limit = .5

    plt.figure()
    ax = plt.gca(projection = "3d")
    
    x=np.zeros(nlobs)
    w=np.zeros(nlobs)
    x,w=GRID.gauss_lobatto(nlobs,14)
    w=np.array(w)
    x=np.array(x) # convert back to np arrays
    nprint = 1 #how many functions to print

    #counter = 0

    y = np.zeros((362,182))
    #for ipoint in coeffs:

        #y  = spharm(ipoint[3], ipoint[4], theta_2d, phi_2d).real #+=  ipoint[5][2] * chi(ipoint[0],ipoint[1],r0,rgrid,w,nlobs,nbins) *
    y = spharm(1, 0, theta_2d, phi_2d).real
    r = np.abs(y.real)*xyz_2d #calculate a point in 3D cartesian space for each value of spherical harmonic at (theta,phi)
    
    ax.plot_surface(r[0], r[1], r[2], facecolors=colormap.to_rgba(y.real), rstride=1, cstride=1)
    ax.set_xlim(-limit,limit)
    ax.set_ylim(-limit,limit)
    ax.set_zlim(-limit,limit)
    #ax.set_aspect("equal")
    #ax.set_axis_off()
    
            
    plt.show()
    plt.close()
Exemple #8
0
def interpolate_chi(Gr,nlobs,nbins,binw,maparray):

    w       =  np.zeros(nlobs)
    xx,w    =  GRID.gauss_lobatto(nlobs,14)
    w       =  np.array(w)

    interpolation_step = binw/200.0
    x = np.arange(0.0, nbins * binw + 0.10, interpolation_step)

    chilist  = []

    for i, elem in enumerate(maparray):
        chilist.append( interpolate.interp1d(x, chi(elem[0], elem[1], x, Gr, w, nlobs, nbins) ) )

    #xnew  = np.arange(0.02, nbins * binw, 0.01)
    #ynew = chilist[1](xnew)   # use interpolation function returned by `interp1d`
    #for s in range((nlobs-1) * nbins - 1):
    #    ynew = chilist[s](xnew)   # use interpolation function returned by `interp1d`
    #    plt.plot(x, chilist[s](x), 'o', xnew, ynew, '-')
    #plt.show()
    
    return chilist
Exemple #9
0
def BUILD_ESP_MAT_EXACT_ROT(params, Gs, Gr, mol_xyz, irun):

    r_array = Gr.flatten()

    VG = []
    counter = 0
    if params[
            'molec_name'] == "chiralium":  # test case for chiralium. We have analytic potential on the radial grid and we want to use Lebedev quadratures for matrix elements

        # 1. Read potential

        start_time = time.time()
        vLM, rgrid_anton = read_potential(params)
        end_time = time.time()

        lmax_multi = params['multi_lmax']

        for k in range(len(r_array) - 1):
            sph = np.zeros(Gs[k].shape[0], dtype=complex)
            print("No. spherical quadrature points  = " + str(Gs[k].shape[0]) +
                  " at grid point " + str('{:10.3f}'.format(r_array[k])))
            for s in range(Gs[k].shape[0]):

                #entire potential block
                for L in range(0, lmax_multi + 1):
                    for M in range(-L, L + 1):

                        #Gs[k][s,0] = theta
                        sph[s] += vLM[k, L, L + M] * sph_harm(
                            M, L, Gs[k][s, 1] + np.pi, Gs[k][s, 0])
                counter += 1

            VG.append(sph)

        return VG

    if os.path.isfile(params['job_directory'] + "esp/" + str(irun) + "/" +
                      params['file_esp']):
        print(params['file_esp'] + " file exist")

        #os.remove(params['working_dir'] + "esp/" + params['file_esp'])

        if os.path.getsize(params['job_directory'] + "esp/" + str(irun) + "/" +
                           params['file_esp']) == 0:

            print("But the file is empty.")
            os.remove(params['job_directory'] + "esp/" + str(irun) + "/" +
                      params['file_esp'])
            os.remove(params['job_directory'] + "esp" + str(irun) + "/" +
                      "grid.dat")

            grid_xyz = GRID.GEN_XYZ_GRID(
                Gs, Gr, params['job_directory'] + "esp/" + str(irun) + "/")
            grid_xyz = np.asarray(grid_xyz)
            V = GRID.CALC_ESP_PSI4(
                params['job_directory'] + "esp/" + str(irun) + "/", params)
            V = -1.0 * np.asarray(V)
            esp_grid = np.hstack((grid_xyz, V[:, None]))
            fl = open(
                params['job_directory'] + "esp/" + str(irun) + "/" +
                params['file_esp'], "w")
            np.savetxt(fl, esp_grid, fmt='%10.6f')

        else:
            print("The file is not empty.")
            flpot1 = open(
                params['job_directory'] + "esp/" + str(irun) + "/" +
                params['file_esp'], "r")
            V = []
            for line in flpot1:
                words = line.split()
                potval = float(words[3])
                V.append(potval)
            V = np.asarray(V)

    else:
        print(params['file_esp'] + " file does not exist")

        #os.remove(params['working_dir'] + "esp/grid.dat")

        grid_xyz = GRID.GEN_XYZ_GRID(
            Gs, Gr, params['job_directory'] + "esp/" + str(irun) + "/")
        grid_xyz = np.asarray(grid_xyz)
        V = GRID.CALC_ESP_PSI4_ROT(
            params['job_directory'] + "esp/" + str(irun) + "/", params,
            mol_xyz)
        V = -1.0 * np.asarray(V)

        esp_grid = np.hstack((grid_xyz, V[:, None]))
        fl = open(
            params['job_directory'] + "esp/" + str(irun) + "/" +
            params['file_esp'] + "_" + str(irun), "w")
        np.savetxt(fl, esp_grid, fmt='%10.6f')

    r_array = Gr.flatten()

    VG = []
    counter = 0
    if params['molec_name'] == "h":  # test case of shifted hydrogen
        r0 = 1.0
        for k in range(len(r_array) - 1):
            sph = np.zeros(Gs[k].shape[0], dtype=float)
            print("No. spherical quadrature points  = " + str(Gs[k].shape[0]) +
                  " at grid point " + str('{:10.3f}'.format(r_array[k])))
            for s in range(Gs[k].shape[0]):
                sph[s] = -1.0 / np.sqrt(r_array[k]**2 + r0**2 - 2.0 *
                                        r_array[k] * r0 * np.cos(Gs[k][s, 0]))
                #sph[s] = -1.0 / (r_array[k])
                counter += 1

            VG.append(sph)

    else:
        for k in range(len(r_array) - 1):
            sph = np.zeros(Gs[k].shape[0], dtype=float)
            print("No. spherical quadrature points  = " + str(Gs[k].shape[0]) +
                  " at grid point " + str('{:10.3f}'.format(r_array[k])))
            for s in range(Gs[k].shape[0]):
                sph[s] = V[counter]
                counter += 1

            VG.append(sph)

    return VG
Exemple #10
0
def BUILD_ESP_MAT_EXACT(params, Gs, Gr):

    if os.path.isfile(params['working_dir'] + "esp/" + params['file_esp']):
        print(params['file_esp'] + " file exist")

        #os.remove(params['working_dir'] + "esp/" + params['file_esp'])

        if os.path.getsize(params['job_directory'] + "esp/" +
                           params['file_esp']) == 0:

            print("But the file is empty.")
            os.remove(params['working_dir'] + "esp/" + params['file_esp'])
            os.remove(params['working_dir'] + "esp/grid.dat")

            grid_xyz = GRID.GEN_XYZ_GRID(Gs, Gr,
                                         params['job_directory'] + "esp/")
            grid_xyz = np.asarray(grid_xyz)
            V = GRID.CALC_ESP_PSI4(params['job_directory'] + "esp/", params)
            V = -1.0 * np.asarray(V)
            esp_grid = np.hstack((grid_xyz, V[:, None]))
            fl = open(params['job_directory'] + "esp/" + params['file_esp'],
                      "w")
            np.savetxt(fl, esp_grid, fmt='%10.6f')

        else:
            print("The file is not empty.")
            flpot1 = open(params['working_dir'] + "esp/" + params['file_esp'],
                          "r")
            V = []
            for line in flpot1:
                words = line.split()
                potval = float(words[3])
                V.append(potval)
            V = np.asarray(V)

    else:
        print(params['file_esp'] + " file does not exist")

        #os.remove(params['working_dir'] + "esp/grid.dat")

        grid_xyz = GRID.GEN_XYZ_GRID(Gs, Gr, params['working_dir'] + "esp/")
        grid_xyz = np.asarray(grid_xyz)
        V = GRID.CALC_ESP_PSI4(params['working_dir'] + "esp/", params)
        V = -1.0 * np.asarray(V)

        esp_grid = np.hstack((grid_xyz, V[:, None]))
        fl = open(params['working_dir'] + "esp/" + params['file_esp'], "w")
        np.savetxt(fl, esp_grid, fmt='%10.6f')

    r_array = Gr.flatten()

    VG = []
    counter = 0
    for k in range(len(r_array) - 1):
        sph = np.zeros(Gs[k].shape[0], dtype=float)
        print("No. spherical quadrature points  = " + str(Gs[k].shape[0]) +
              " at grid point " + str(r_array[k]))
        for s in range(Gs[k].shape[0]):
            sph[s] = V[counter]
            counter += 1

        VG.append(sph)
    return VG
Exemple #11
0
    maparray0, Nbas0 = MAPPING.GENMAP_FEMLIST(  params['FEMLIST'],
                                                            params['bound_lmax'],
                                                            params['map_type'],
                                                            params['job_directory'] )


    maparray, Nbas = MAPPING.GENMAP_FEMLIST(  params['FEMLIST_PROP'],
                                                            params['bound_lmax'],
                                                            params['map_type'],
                                                            params['job_directory'] )

    save_map(maparray0,params['job_directory'] + 'map0.dat')
    save_map(maparray,params['job_directory'] + 'map_global.dat')

    Gr0, Nr0                       = GRID.r_grid(             params['bound_nlobs'], 
                                                            params['bound_nbins'] , 
                                                            params['bound_binw'],  
                                                            params['bound_rshift'] )

    Gr, Nr                       = GRID.r_grid(             params['bound_nlobs'], 
                                                            params['prop_nbins'] , 
                                                            params['bound_binw'],  
                                                            params['bound_rshift'] )

    """ Read grid of Euler angles"""
    grid_euler  = read_euler_grid()

    grid_euler = grid_euler.reshape(-1,3)     

    N_Euler = grid_euler.shape[0]

    N_per_batch = int(N_Euler/params['N_batches'])
Exemple #12
0
    
    #plot_pad_polar(params['k_list_pad'],0)

    wffile = params['job_directory'] + params['file_psi_init']+"_0"  # "psi0_h2o_1_12_30.0_4_uhf_631Gss.dat"# "psi_init_h2o_3_24_20.0_2_uhf_631Gss.dat"#+ "psi0_h2o_1_20_10.0_4_uhf_631Gss.dat"
    nvecs = 10 #how many vectors to load?
    ivec = params['ivec'] #which vector to plot?
    
    coeffs = read_coeffs(wffile,nvecs)

    #psi = np.zeros(len(coeffs), dtype = complex)
    #print(psi.shape)
    #for ielem,elem in enumerate(coeffs):
    #    psi[ielem] = elem[5][ivec]

    #Gr, Nr = GRID.r_grid( params['bound_nlobs'], nbins , params['bound_binw'],  params['bound_rshift'] )
    Gr, Nr = GRID.r_grid_prim( params['bound_nlobs'], params['bound_nbins']  , params['bound_binw'],  params['bound_rshift'] )
    #maparray, Nbas = MAPPING.GENMAP( params['bound_nlobs'], params['bound_nbins'], params['bound_lmax'], \
    #                                 params['map_type'], params['working_dir'] )

    #maparray_chi, Nbas_chi = MAPPING.GENMAP_FEMLIST( params['FEMLIST'],  0, \
    #                                 params['map_type'], params['working_dir'] )


    #flist = interpolate_chi(Gr,params['bound_nlobs'],nbins,params['bound_binw'] ,maparray_chi)
    #exit()

    """ plot radial basis """
    #plot_chi(0.0,params['bound_binw']*params['bound_nbins'],1000,Gr,params['bound_nlobs'], params['bound_nbins'])
    #exit()

    """ plot radial wavefunction at a given ray=(theta,phi) """