def follow(self, follow_atom = 0, num_neighbours = 3, step_size = 50):
        self.num_neighbours = num_neighbours # numbers of nearest neighbours to plot distance to

        #try:
        #    "%d" % follow_atom
        #except TypeError:
        #    print "Generating geometric mean"
        #    geo = self.traj.get_geometric_center((0,1))
        #    self.traj.remove_atom(0)
        #    self.traj.remove_atom(0)
        #    follow_atom = self.traj.add_atom(geo)

        print "Generating symmetric running mean..."
        self.pos[:,follow_atom] = symmetric_running_mean(self.pos[:,follow_atom],250)
        #pos[:,0] = symmetric_running_mean(pos[:,0],500)
        
        #import profile
        #profile.run('get_occupancies()')
        
        # Calculate occupancies, nearest site for atom x and distance to nearest site(s)
        self.step_size = step_size
        self.occupancies, self.followed_atom_site, self.followed_atom_r2 = self.get_occupancies( follow_atom = follow_atom)
Example #2
0
    def follow(self, follow_atom=0, num_neighbours=3, step_size=50):
        self.num_neighbours = num_neighbours  # numbers of nearest neighbours to plot distance to

        #try:
        #    "%d" % follow_atom
        #except TypeError:
        #    print "Generating geometric mean"
        #    geo = self.traj.get_geometric_center((0,1))
        #    self.traj.remove_atom(0)
        #    self.traj.remove_atom(0)
        #    follow_atom = self.traj.add_atom(geo)

        print "Generating symmetric running mean..."
        self.pos[:, follow_atom] = symmetric_running_mean(
            self.pos[:, follow_atom], 250)
        #pos[:,0] = symmetric_running_mean(pos[:,0],500)

        #import profile
        #profile.run('get_occupancies()')

        # Calculate occupancies, nearest site for atom x and distance to nearest site(s)
        self.step_size = step_size
        self.occupancies, self.followed_atom_site, self.followed_atom_r2 = self.get_occupancies(
            follow_atom=follow_atom)
Example #3
0
    def __init__(self, trajectory, atom = 0, step = 50):
        """
        DisplacementPlot class
        
        Parameters:
            - trajectory: a oppvasp.Trajectory object
            - atom: index of the atom to follow
            - step : step size
        """
        
        atpos = trajectory.get_positions( coords = 'cart', atom = atom )
        nsteps = atpos.shape[0]
        atpos = atpos - atpos[0]

        atpos = symmetric_running_mean(atpos,300) 
        #atpos = symmetric_running_mean(atpos,500) 

        print " atpos 0: ",atpos[0]
        print " atpos -1: ",atpos[-1]

        r = np.sqrt(np.sum(atpos**2,axis=1))

        self.x = trajectory.time[0:nsteps:step]/1000.
        self.y = r[0:nsteps:step]
    def __init__(self, trajectory, atom=0, step=50):
        """
        DisplacementPlot class
        
        Parameters:
            - trajectory: a oppvasp.Trajectory object
            - atom: index of the atom to follow
            - step : step size
        """

        atpos = trajectory.get_positions(coords='cart', atom=atom)
        nsteps = atpos.shape[0]
        atpos = atpos - atpos[0]

        atpos = symmetric_running_mean(atpos, 300)
        #atpos = symmetric_running_mean(atpos,500)

        print " atpos 0: ", atpos[0]
        print " atpos -1: ", atpos[-1]

        r = np.sqrt(np.sum(atpos**2, axis=1))

        self.x = trajectory.time[0:nsteps:step] / 1000.
        self.y = r[0:nsteps:step]
Example #5
0
    natoms = r.shape[0]
    T1[idx] = 1. / 3 * (np.sum(np.cos(fac * r[:, 0])) / natoms +
                        np.sum(np.cos(fac * r[:, 1])) / natoms +
                        np.sum(np.cos(fac * r[:, 2])) / natoms)

    kvec = np.array((8, 0, 0))  # 2**3 for 2x2x2 supercell
    s = 2 * np.pi * np.dot(r, kvec)

    #print "T2:",
    T2[idx] = np.sum(np.exp(np.complex(0, 1) * s)).real / natoms

    cossum = np.sum(np.cos(s)) / natoms
    sinsum = np.sum(np.sin(s)) / natoms
    T3[idx] = np.sqrt(cossum**2 + sinsum**2)

T1m = symmetric_running_mean(T1, 500)
T2m = symmetric_running_mean(T2, 500)
T3m = symmetric_running_mean(T3, 500)

## for each MD step
#for stepno in range(nsteps):

#    x = traj.positions[stepno,:,0]   # x coordinate of all atoms
#    y = traj.positions[stepno,:,1]   # y coordinate of all atoms
#    z = traj.positions[stepno,:,2]   # z coordinate of all atoms

#    lambda_x[stepno] += np.sum(np.cos(fac * x))
#    lambda_y[stepno] += np.sum(np.cos(fac * y))
#    lambda_z[stepno] += np.sum(np.cos(fac * z))

pbar.finish()
for idx, r in enumerate(pos):
    pbar.update(idx)
    natoms = r.shape[0]
    T1[idx] = 1./3 * (np.sum(np.cos(fac * r[:,0]))/natoms + np.sum(np.cos(fac * r[:,1]))/natoms + np.sum(np.cos(fac * r[:,2]))/natoms )

    kvec = np.array((8,0,0)) # 2**3 for 2x2x2 supercell
    s = 2*np.pi*np.dot(r, kvec)

    #print "T2:",
    T2[idx] = np.sum(np.exp(np.complex(0,1) * s)).real / natoms

    cossum = np.sum(np.cos(s))/natoms
    sinsum = np.sum(np.sin(s))/natoms
    T3[idx] = np.sqrt(cossum**2+sinsum**2)

T1m = symmetric_running_mean(T1, 500)
T2m = symmetric_running_mean(T2, 500)
T3m = symmetric_running_mean(T3, 500)

## for each MD step
#for stepno in range(nsteps):
    
#    x = traj.positions[stepno,:,0]   # x coordinate of all atoms
#    y = traj.positions[stepno,:,1]   # y coordinate of all atoms
#    z = traj.positions[stepno,:,2]   # z coordinate of all atoms
        
#    lambda_x[stepno] += np.sum(np.cos(fac * x))
#    lambda_y[stepno] += np.sum(np.cos(fac * y))
#    lambda_z[stepno] += np.sum(np.cos(fac * z))

p = [0.15, 0.15, 0.05, 0.05]  # margins: left, bottom, right, top. Height: 1-.15-.46 = .39
fig = plt.figure()
ax1 = fig.add_axes([ p[0], p[1], 1-p[2]-p[0], 1-p[3]-p[1] ])
ax1.set_xlabel(r'Time [ps]')
ax1.set_ylabel(ur'Si-P bond length [Å]')
ax1.set_ylim(2.0,3.0)
plotdata = []

#dp.ax1.legend(['%d' % (at) for at in include_atoms], loc='upper right', ncol=1, frameon = False)
#dp.ax1.set_ylabel(u'$r^2$ [Å]')

labels = []
lines = []
for i in nearest:
    d = dist[:,i]
    ds = symmetric_running_mean( d , 500 )
    #ax1.plot(traj.time[:], d, color = 'gray', alpha = 0.5)
    #line = ax1.plot(traj.time[:]/1.e3, ds )
    line = ax1.plot(traj.time[:]/1.e3, d )
    lines.append(line[0])
    print line
    print d.shape
    avg = np.sum(d)/d.shape[0]
    #ax1.axhline(y=avg, linestyle='dashed')
    print i,avg
    labels.append('No.%d' % (i))

print u"Shortest Si-P bond length at end of run:",dist[-1,nearest[0]],"Å for Si atom",nearest[0]
si = pos[nearest[0],-1]
p = pos[0,-1]
print "Si:",si
Example #8
0
#############################################################################
# (2) Plot

styles = [
        { 'color': 'gray', 'alpha': .5 },
        { 'color': 'black', 'linestyle': '--', 'dashes': (4,1), 'alpha': .8 }, # dashes: (ink on, ink off)
        { 'color': 'black' },
        { 'color': 'gray', 'alpha': .5 } # dashes: (ink on, ink off)
    ]

plotutils.prepare_canvas( width = '7 cm', fontsize = 9, fontsize_small = 8 ) 
fig = plt.figure()

toten = traj.total_energy[r_min:r_max]
toten_ra = plotutils.symmetric_running_mean(toten,250)

# Lower plot
p = [0.20, 0.20, 0.05, 0.52]  # margins: left, bottom, right, top. Height: 1-.15-.46 = .39
ax0 = fig.add_axes([ p[0], p[1], 1-p[2]-p[0], 1-p[3]-p[1] ])
ax0.plot(traj.time[r_min:r_max]/1.e3, toten, zorder=1, **styles[0])
ax0.plot(traj.time[r_min:r_max]/1.e3, toten_ra, zorder=1, **styles[2])
#ax0.plot(traj.time[r_min:r_max]/1.e3, poten_ra, zorder=1, **styles[1])
ax0.set_xlabel('Time [ps]')
ax0.set_ylabel('$E$ [eV]')
#ax0.set_yticks(np.arange(-340,-300,10))
ymean = np.mean(toten[-500:-1])
ax0.set_ylim(ymean-10, ymean+10)

for line in ax0.yaxis.get_ticklines(): # line is a Line2D instance
    line.set_markersize(3)
Example #9
0
import psutil


def norm(v):
    return np.sqrt(np.dot(v, v))


wdir = './'

basename = os.path.splitext(os.path.basename(sys.argv[0]))[0]
fig_filename = wdir + basename + '.pdf'
traj = read_trajectory(wdir, unwrap_pbcs=True)
poten = (traj.total_energy - traj.kinetic_energy) / traj.num_atoms
t = traj.time / 1.e3  # -> ps
poten_m = symmetric_running_mean(poten, 500)

styles = [{'color': 'black', 'alpha': 0.2}, {'color': 'black', 'alpha': 1.}]

fig = plt.figure()

# Main plot:
p = [0.15, 0.15, 0.05,
     0.05]  # margins: left, bottom, right, top. Height: 1-.15-.46 = .39
ax1 = fig.add_axes([p[0], p[1], 1 - p[2] - p[0], 1 - p[3] - p[1]])
ax1.grid(True, which='major', color='gray', alpha=0.5)
#ax1.set_ylim((-.2,1.0))
ax1.set_xlabel('Time [ps]')
ax1.set_ylabel('Potential energy per atom [eV]')
ax1.plot(t, poten, **styles[0])
ax1.plot(t, poten_m, **styles[1])
Example #10
0
     RotatingMarker, ReverseBar, SimpleProgress


import psutil 

def norm(v):
    return np.sqrt(np.dot(v,v))

wdir = './'

basename = os.path.splitext(os.path.basename(sys.argv[0]))[0]
fig_filename = wdir + basename + '.pdf'
traj = read_trajectory(wdir, unwrap_pbcs = True)
poten = (traj.total_energy - traj.kinetic_energy)/traj.num_atoms
t = traj.time/1.e3  # -> ps
poten_m = symmetric_running_mean(poten, 500)

styles = [
   { 'color': 'black', 'alpha': 0.2 },
   { 'color': 'black', 'alpha': 1. }
]

fig = plt.figure()

# Main plot:
p = [0.15, 0.15, 0.05, 0.05]  # margins: left, bottom, right, top. Height: 1-.15-.46 = .39
ax1 = fig.add_axes([ p[0], p[1], 1-p[2]-p[0], 1-p[3]-p[1] ])
ax1.grid(True, which='major', color = 'gray', alpha = 0.5)
#ax1.set_ylim((-.2,1.0))
ax1.set_xlabel('Time [ps]')
ax1.set_ylabel('Potential energy per atom [eV]')
Example #11
0
     0.05]  # margins: left, bottom, right, top. Height: 1-.15-.46 = .39
fig = plt.figure()
ax1 = fig.add_axes([p[0], p[1], 1 - p[2] - p[0], 1 - p[3] - p[1]])
ax1.set_xlabel(r'Time [ps]')
ax1.set_ylabel(ur'Si-P bond length [Å]')
ax1.set_ylim(2.0, 3.0)
plotdata = []

#dp.ax1.legend(['%d' % (at) for at in include_atoms], loc='upper right', ncol=1, frameon = False)
#dp.ax1.set_ylabel(u'$r^2$ [Å]')

labels = []
lines = []
for i in nearest:
    d = dist[:, i]
    ds = symmetric_running_mean(d, 500)
    #ax1.plot(traj.time[:], d, color = 'gray', alpha = 0.5)
    #line = ax1.plot(traj.time[:]/1.e3, ds )
    line = ax1.plot(traj.time[:] / 1.e3, d)
    lines.append(line[0])
    print line
    print d.shape
    avg = np.sum(d) / d.shape[0]
    #ax1.axhline(y=avg, linestyle='dashed')
    print i, avg
    labels.append('No.%d' % (i))

print u"Shortest Si-P bond length at end of run:", dist[
    -1, nearest[0]], "Å for Si atom", nearest[0]
si = pos[nearest[0], -1]
p = pos[0, -1]
Example #12
0
        'alpha': .8
    },  # dashes: (ink on, ink off)
    {
        'color': 'black'
    },
    {
        'color': 'gray',
        'alpha': .5
    }  # dashes: (ink on, ink off)
]

plotutils.prepare_canvas(width='7 cm', fontsize=9, fontsize_small=8)
fig = plt.figure()

toten = traj.total_energy[r_min:r_max]
toten_ra = plotutils.symmetric_running_mean(toten, 250)

# Lower plot
p = [0.20, 0.20, 0.05,
     0.52]  # margins: left, bottom, right, top. Height: 1-.15-.46 = .39
ax0 = fig.add_axes([p[0], p[1], 1 - p[2] - p[0], 1 - p[3] - p[1]])
ax0.plot(traj.time[r_min:r_max] / 1.e3, toten, zorder=1, **styles[0])
ax0.plot(traj.time[r_min:r_max] / 1.e3, toten_ra, zorder=1, **styles[2])
#ax0.plot(traj.time[r_min:r_max]/1.e3, poten_ra, zorder=1, **styles[1])
ax0.set_xlabel('Time [ps]')
ax0.set_ylabel('$E$ [eV]')
#ax0.set_yticks(np.arange(-340,-300,10))
ymean = np.mean(toten[-500:-1])
ax0.set_ylim(ymean - 10, ymean + 10)

for line in ax0.yaxis.get_ticklines():  # line is a Line2D instance
Example #13
0
    def __init__(self, trajectory, lattice, atom = 0, nn = 8, step = 50, remove_lattice_drift = True, cache = True):
        """
        DistanceFromLatticeSites class
        
        Parameters:
            - trajectory : oppvasp.Trajectory object
            - lattice    : oppvasp.Structure object describing the lattice sites
            - atom       : atom to follow
            - nn         : number of nearest sites
            - step       : step size
        """

        if trajectory.pbc_unwrapped:
            print "----"
            print "DistanceFromLatticeSites: Probably best to use a trajectory with PBCs (no unwrapping)"
            print "----"

        self.entered_site = Event()
        self.left_site = Event()
        self.bottombar_labels = {}
        self.bottombar_height = .5
        self.bottombar_colors = {}
        self.valid = True

        self.lattice = lattice
        self.traj = trajectory.get_selection(step = step)
        if self.traj.length <= 1:
            print "[DistanceFromLatticeSites ERROR] Trajectory selection is too short. Aborting"
            self.valid = False
            return

        ts = self.traj.time[1] - self.traj.time[0]
        print "[DistanceFromLatticeSites] Timestamp for trajectory selection is %.f fs" % ts

        p = trajectory.path.split('/')
        basename = p.pop()
        cache_file = '/'.join(p) + '/' + basename.rsplit('.',1)[0] + '_dist_from_lattice.pkl'
        print "cache file:",cache_file
        
        if cache and os.path.isfile(cache_file):
            pkl_file = open(cache_file, 'rb')
            data = pickle.load(pkl_file)
            pkl_file.close()
            self.x = data['x']
            self.y = data['y']
            self.sites = data['sites']
            print "[DistanceFromLatticeSites] Loaded from cache %s" % cache_file
            return
            #checks?
            
        
        if remove_lattice_drift:
            print "[DistanceFromLatticeSites] Calculating drift using AvgDistPlotter"
            avg = AvgDistPlotter(trajectory = self.traj, lattice = self.lattice, step = 1)
            drift = avg.y_smoothed

        
        pos = self.traj.get_positions(coords = 'direct')
        print "Min/max: %.2f / %.2f" % (np.min(pos), np.max(pos))

        print "[DistanceFromLatticeSites] Unwrapping PBCs before smoothing"
        self.traj.unwrap_pbc()
        pos = self.traj.get_positions(coords = 'direct')
        self.traj.wrap_pbc()
        print "Min/max: %.2f / %.2f" % (np.min(pos), np.max(pos))

        print "[DistanceFromLatticeSites] Generating symmetric running mean..."
        atpos = pos[:,atom]
        atpos = symmetric_running_mean(atpos, 250/ts)
        atpos = symmetric_running_mean(atpos, 500/ts)

        # Wrap back into cell
        atpos = atpos - np.floor(atpos)
        print "Min/max: %.2f / %.2f" % (np.min(atpos), np.max(atpos))

        np.save('temp.npz', atpos)

        cell = self.traj.basis
        latpos = lattice.get_positions(coords = 'direct')

        natoms = pos.shape[1]
        nsteps = pos.shape[0]
        nsites = latpos.shape[0]
        #print "[DistanceFromLatticeSites] Reference lattice contains %d lattice sites" % (nsites)

        dists = np.zeros((nsteps, nn), dtype=np.float)
        sites = np.zeros((nsteps, nn), dtype=np.int)

        pbar = ProgressBar(widgets=['[DistanceFromLatticeSites] Analysing step ',SimpleProgress(),'...'], maxval = nsteps).start()
        for i in np.arange(0, nsteps):
            pbar.update(i)

            # Find displacement vectors between atom and all sites:
            r = atpos[i] - latpos

            # Use minimum image convention to threat bonds over PBCs
            # Note: This will not work with *very* tilted unit cells
            r = r - (2*r).astype('int')
            #r = r - np.floor(r)

            r = direct_to_cartesian(r, cell[i])
            if remove_lattice_drift:
                r -= drift[i] # cartesian? yes

            r2 = (r**2).sum(axis=1)
            r = np.sqrt(r2)

            idx = np.argsort(r)
            dists[i] = r[idx[0:nn]]
            sites[i] = idx[0:nn]

            #print "Shortest bond is: %.3f Angstrom (between atoms %d and %d)" % (minr,minpair[0],minpair[1])
            #break
        pbar.finish()

        #dists = symmetric_running_median(dists,6)
        #dists = symmetric_running_mean(dists,2)

        self.x = self.traj.time/1000.
        self.y = dists
        self.sites = sites

        pkl_file = open(cache_file, 'wb')
        pickle.dump({'x': self.x, 'y': self.y, 'sites': self.sites, 'trajectory': self.traj.path, 'lattice': lattice }, pkl_file)
        pkl_file.close()
        print "[DistanceFromLatticeSites] Wrote cache file: %s" % cache_file