Esempio n. 1
0
    def iterate(self, method="hessian", supercell=None, q=None, nrattle=0):
        """Returns a list of possible configurations, one for each eigenmode in the
        system, that has `supercell` is compatible with the specified `q`
        vector.

        Args:
            method (str): desired method for computing the eigenvalues and
              eigenvectors. Possible choices are :meth:`hessian` or
              :meth:`dynmat`.
            supercell (numpy.ndarray): supercell matrix to use in generating the
              configs.
            q (numpy.ndarray): q-vector that the resulting supercell should be
              compatible with.
            nrattle (int): number of additional, empty configs to include via
              :meth:`quippy.Atoms.rattle`.
        """
        if method == "hessian":
            dmd = self.hessian()
        elif method == "vasp_hessian":
            dmd = self.vasp_hessian()
        else:
            dmd = self.dynmat(supercell, q)

        hname = "hessian1"
        seed = quippy.Atoms()
        seed.copy_from(dmd["template"])
        result = quippy.AtomsList()
        result.append(dmd["template"])

        #Delete the force, energy and virial information from the copy, so that
        #we don't duplicate it all over.
        del seed.params["dft_energy"]
        del seed.params["dft_virial"]
        del seed.properties["dft_force"]

        for l, v in zip(dmd["eigvals"], dmd["eigvecs"]):
            atc = seed.copy()

            #Add this eigenvector to its own configuration.
            atc.add_property(hname, 0.0, n_cols=3)
            H = np.reshape(v.real, (atc.n, 3)).T
            setattr(atc, hname, H)

            #Same thing for the eigenvalue. Then save it to the group folder
            #structure.
            atc.params.set_value(hname, l)
            atc.params.set_value("n_hessian", 1)
            #atc.add_property("force", 0.0, n_cols=3)
            result.append(atc)

        for i in range(nrattle):
            atRand = seed.copy()
            quippy.randomise(atRand.pos, 0.2)
            result.append(atRand)

        # atz = seed.copy()
        # atz.add_property("dft_force", 0.0, n_cols=3)
        #atz.params.set_value("dft_energy",

        return result
Esempio n. 2
0
def get_raw_soap_wrapper(kwargs):
    fpointer = kwargs.pop('fpointer')
    # need to copy the frame to avoid seg fault in quip if rerun the procedure on the same name space
    frame = qp.Atoms(fpointer=fpointer).copy()
    kwargs.update({'atoms': frame, 'spkit': get_spkit(frame)})
    idx = kwargs.pop('idx')
    return (idx, get_soap(**kwargs))
Esempio n. 3
0
    def __init__(self,
                 sn,
                 tracer_atomic_number=None,
                 soap_params={},
                 verbose=True):

        # Make a copy of the structure
        self._structure = qp.Atoms(sn.static_structure)
        # Add a tracer
        if tracer_atomic_number is None:
            tracer_atomic_number = sn.structure.get_atomic_numbers()[
                sn.mobile_mask][0]

        self.tracer_atomic_number = tracer_atomic_number

        self._structure.add_atoms((0.0, 0.0, 0.0), tracer_atomic_number)
        self._tracer_index = len(self._structure) - 1

        # Create the descriptor
        soap_opts = dict(DEFAULT_SOAP_PARAMS)
        soap_opts.update(soap_params)
        soap_cmd_line = ["soap"]
        # User options
        for opt in soap_opts:
            soap_cmd_line.append("{}={}".format(opt, soap_opts[opt]))
        # Stuff that's the same no matter what
        soap_cmd_line.append("n_Z=1")  #always one tracer
        soap_cmd_line.append("Z={{{}}}".format(self.tracer_atomic_number))

        self._soaper = descriptors.Descriptor(" ".join(soap_cmd_line))

        self.verbose = verbose
Esempio n. 4
0
 def setUp(self):
     self.dia_quippy = diamond(5.44, 14)
     self.dia_quippy.add_property(
         'magmoms',
         np.random.uniform(-1, 1, size=3 * 8).reshape(3, 8))
     self.dia_quippy.add_property('charge', [1.0] * 8)
     self.dia_ase = ase.Atoms(self.dia_quippy)
     self.dia_quippy_2 = quippy.Atoms(self.dia_ase)
Esempio n. 5
0
def framesprod_wrapper(kargs):
    keys = kargs.keys()
    get_envKernel = kargs.pop('frameprodFunc')
    queue = kargs.pop('queue')
    # to disable the progressbar
    dispbar = kargs.pop('dispbar')
    if 'fpointers1' in keys:
        fpointers1 = kargs.pop('fpointers1')
        fpointers2 = kargs.pop('fpointers2')
        atoms1 = [qp.Atoms(fpointer=fpointer1) for fpointer1 in fpointers1]

        chemicalKernelmat = kargs.pop('chemicalKernelmat')

        frames1 = get_Soaps(atoms1, dispbar=dispbar, **kargs)
        if fpointers2 is not None:
            atoms2 = [qp.Atoms(fpointer=fpointer2) for fpointer2 in fpointers2]
            frames2 = get_Soaps(atoms2, dispbar=dispbar, **kargs)
        else:
            frames2 = None

        kargs = {
            'frames1': frames1,
            'frames2': frames2,
            'chemicalKernelmat': chemicalKernelmat
        }

    elif 'atoms1' in keys:
        atoms1 = kargs.pop('atoms1')
        atoms2 = kargs.pop('atoms2')
        chemicalKernelmat = kargs.pop('chemicalKernelmat')

        frames1 = get_Soaps(atoms1, dispbar=dispbar, **kargs)
        if atoms2 is not None:
            frames2 = get_Soaps(atoms2, dispbar=dispbar, **kargs)
        else:
            frames2 = None

        kargs = {
            'frames1': frames1,
            'frames2': frames2,
            'chemicalKernelmat': chemicalKernelmat
        }

    return framesprod(queue=queue, frameprodFunc=get_envKernel, **kargs)
Esempio n. 6
0
    def __init__(self, filepath):
        self.filepath = filepath
        self.atoms = quippy.Atoms(filepath)
        self.xyz = self.atoms.positions
        self.extras = list(self.atoms.properties.keys())
        for k in self.extras:
            setattr(self, k, self.atoms.properties[k])

        self.types = None
        self.box = self.atoms.lattice
Esempio n. 7
0
def enthalpy(sqnc, p=None):
    """Returns Helmholtz enthalpy, h=E+PV per atom of the polytype stack sequence

    Args:
        sqnc (string): polytype stacking sequence
          For example, 'abc' or 'abcabcacbacb'.
        p (float): hydrostatic pressure in epsilon per sigma cubed units; default None.

    Returns:
       float
    """

    apos = aparray(sqnc)
    N = len(apos)
    lat = [[1., 0., 0.], [0.5, sqrt(3) / 2., 0.], [0., 0., N * sqrt(2. / 3)]]

    numbers = []
    for i in range(0, N):
        numbers.append(14)

    plyt = quippy.Atoms(n=N, lattice=lat, positions=apos, numbers=numbers)

    plyt.set_cutoff(LJ.cutoff())
    plyt.calc_connect()
    LJ.calc(plyt, energy=True)
    e1 = plyt.energy
    v = plyt.get_volume()
    print("Initial energy: ", e1)
    print("Initial volume: ", v)
    plyt.calc_connect()

    pressure = [[p, 0., 0.], [0., p, 0.], [0., 0., p]]

    LJ.minim(plyt,
             'cg',
             1e-12,
             100,
             do_pos=True,
             do_lat=True,
             external_pressure=pressure)
    LJ.calc(plyt, energy=True)
    e2 = plyt.energy
    v = plyt.get_volume()
    print("Energy for {} after relaxing: ".format(sqnc), e2)
    print("Volume after relaxing: ", v, " per ", N, " atoms.")
    #plyt.write("{}.xyz".format(sqnc))

    if p == None:
        p = 0
    h = (e2 + p * v) / N
    #hd=(hf-h)/N
    return h
Esempio n. 8
0
File: soap.py Progetto: rzk1/glosim2
def get_alchemy_frame( spkit, spkitMax,atoms=None,fpointer=None, nocenters=None, centerweight=1., gaussian_width=0.5,cutoff=3.5,
                      chemicalProjection=None,
                      cutoff_transition_width=0.5, nmax=8, lmax=6,chem_channels=True,is_fast_average=False,queue=None):
    if nocenters is None:
        nocenters = []

    if atoms is None and fpointer is not None:
        atoms = qp.Atoms(fpointer=fpointer)
    elif atoms is not None and fpointer is None:
        atoms = atoms
    elif atoms is not None and fpointer is not None:
        atoms = atoms
    else:
        raise NotImplementedError('At least atoms or fpointer needs to be given')
    spkit = get_spkit(atoms)
    soapParams = {'spkit': spkit, 'spkitMax': spkitMax, 'nocenters': nocenters,
                  'centerweight': centerweight, 'gaussian_width': gaussian_width,
                  'cutoff': cutoff, 'cutoff_transition_width': cutoff_transition_width,
                  'nmax': nmax, 'lmax': lmax,'is_fast_average':is_fast_average}


    rawsoaps = get_soap(atoms, **soapParams)

    zList = atoms.get_atomic_numbers()

    mm = envIdx2centerIdxMap(atoms, spkit, nocenters)
    # chemical channel separation for each central atom species
    # and each atomic environment
    alchemyFrame = AlchemyFrame(atom=atoms, nocenters=nocenters, soapParams=soapParams,is_fast_average=is_fast_average)
    Nenv, Npowerspectrum = rawsoaps.shape
    if chem_channels:
        for it in range(Nenv):
            # soap[it] is (1,Npowerspectrum) so need to transpose it
            #  convert the soap vector of an environment from quippy descriptor to soap vectors
            # with chemical channels.
            alchemySoapdict = Soap2AlchemySoap(rawsoaps[it, :], spkitMax, nmax, lmax)

            alchemySoap = AlchemySoap(qpatoms=atoms, soapParams=soapParams, centerIdx=mm[it],
                                      is_fast_average=is_fast_average)

            alchemySoap.from_dict(alchemySoapdict)
            if chemicalProjection is not None:
                alchemySoap = ProjectedAlchemySoap(alchemySoap,chemicalProjection)

            centerZ = zList[mm[it]] if not is_fast_average else 'AVG'
            alchemyFrame[centerZ] = alchemySoap
    else:
        for it in xrange(Nenv):
            centerZ = zList[mm[it]] if not is_fast_average else 'AVG'
            alchemyFrame[centerZ] = rawsoaps[it, :]

    return alchemyFrame
Esempio n. 9
0
def create_hcp_custom(c_vs_a, V_per_at, z):
    import quippy
    import numpy as np

    V = 2.0 * V_per_at
    a = (2 * V / (3.0**(0.5) * c_vs_a))**(1.0 / 3.0)
    c = c_vs_a * a

    lattice = []
    lattice.append([3.0**(0.5) / 2.0 * a, -a / 2.0, 0])
    lattice.append([3.0**(0.5) / 2.0 * a, a / 2.0, 0])
    lattice.append([0, 0, c])
    lattice = np.transpose(lattice)
    unitcell = quippy.Atoms(n=0, lattice=lattice)

    pos = []
    pos.append([3.0**(0.5) / 6.0 * a, 0, 0.0])
    pos.append([3.0**(0.5) / 2.0 * a, 0, c / 2.0])

    for i in range(0, len(pos)):
        unitcell.add_atoms(pos[i], z)

    return unitcell
Esempio n. 10
0
    def __init__(self,
                 init_file,
                 args_str,
                 param_file,
                 latency=1.0e-3,
                 name="",
                 pars=None,
                 dopbc=True,
                 threaded=False):
        """Initialises QUIP.

        Args:
        pars: Mandatory dictionary, giving the parameters needed by QUIP.
        """
        if quippy is None:
            info("QUIPPY import failed", verbosity.low)
            raise quippy_exc

        # a socket to the communication library is created or linked
        super(FFQUIP, self).__init__(latency,
                                     name,
                                     pars,
                                     dopbc,
                                     threaded=threaded)
        self.init_file = init_file
        self.args_str = args_str
        self.param_file = param_file

        # Initializes an atoms object and the interaction potential
        self.atoms = quippy.Atoms(self.init_file)
        self.pot = quippy.Potential(self.args_str,
                                    param_filename=self.param_file)

        # Initializes the conversion factors from i-pi to QUIP
        self.len_conv = unit_to_user("length", "angstrom", 1)
        self.energy_conv = unit_to_user("energy", "electronvolt", 1)
        self.force_conv = unit_to_user("force", "ev/ang", 1)
Esempio n. 11
0
    def __init__(self, primitive, supercell, folder, vasp=False):
        self.atoms = PhonopyAtoms(symbols=primitive.get_chemical_symbols(),
                                  positions=primitive.positions,
                                  masses=primitive.get_masses(),
                                  cell=primitive.cell,
                                  pbc=primitive.pbc)

        self.supercell = supercell
        self.folder = folder
        if not vasp:
            self.phonopy = Phonopy(self.atoms, supercell)
            self._get_dynmatrix()
            self.primitive = self.phonopy._dynamical_matrix.get_primitive()
        else:
            from matdb.io import vasp_to_xyz
            self.phonopy = Phonopy(self.atoms, supercell)
            if path.isfile("FORCE_CONSTANTS"):
                fc = file_IO.parse_FORCE_CONSTANTS(filename="FORCE_CONSTANTS")
                self.phonopy.set_force_constants(fc)
                self.phonopy._set_dynamical_matrix()

            self.primitive = primitive
            vasp_to_xyz(folder)
            self.parent = quippy.Atoms(path.join(folder, "output.xyz"))
Esempio n. 12
0
                str(lat_vec_mean_histo[i]) + "\n")

    V_aver_per_at = V / len(at)

    at_name_average_list = []  # list of atom objects and their names

    for struc in ref_struc_name_list:

        at_name_average_list.append([
            misc_calc_lib.create_at_accord_struc(V_aver_per_at, z_ref, struc),
            struc
        ])

    for path in ref_struc_config_path_list:

        at_old = quippy.Atoms(path)  # load in the reference structure

        V_old_per_at = at_old.get_volume() / len(at_old)
        f = V_aver_per_at / V_old_per_at  # stretch/shrink factor for volume (need third root of this for each dimension)

        # Creating a new atoms object with the appropriate volume
        at_new = quippy.Atoms(n=len(at_old))
        at_new.set_cell(at_old.get_cell() * f**(1.0 / 3.0))
        at_new.set_positions(at_old.get_positions() * f**(1.0 / 3.0))
        at_new.set_atomic_numbers(at_old.get_atomic_numbers())

        at_name_average_list.append(
            [at_new, misc_calc_lib.raw_filename_xyz_extxyz(path)])

    for el in at_name_average_list:
Esempio n. 13
0
# the script that actually computes SOAP. Called by `quippy_interface.py`.
import os

print(
    "This is the output of the run_quippy.py script. Printing the environment variables for easier debugging."
)
print(os.environ)

import quippy
import ase
import numpy as np

with open("quippy_config.txt", "r") as f:
    config = f.read()

all_ase = ase.io.iread("data.traj")

descs = []
cutoffs = []
for at_ase in all_ase:
    at = quippy.Atoms(at_ase)
    desc = quippy.descriptors.Descriptor(config)
    at.set_cutoff(desc.cutoff())
    at.calc_connect()

    desc_out = desc.calc(at)
    descs.append(np.round(desc_out["descriptor"], 20))
    cutoffs.append(desc_out["cutoff"])

np.save("out", descs)  # automatically saves as dtype=object
Esempio n. 14
0
 def setUp(self):
     self.dia_quippy = diamond(5.44, 14)
     self.dia_quippy.add_property('new', -1.0)
     self.dia_ase = ase.Atoms(self.dia_quippy)
     self.dia_quippy_2 = quippy.Atoms(self.dia_ase)
Esempio n. 15
0
 def setUp(self):
     self.dia_quippy = diamond(5.44, 14)
     self.dia_ase = ase.Atoms(self.dia_quippy)
     self.dia_quippy_2 = quippy.Atoms(self.dia_ase)
Esempio n. 16
0
import os.path, ase.io
from utilities import relax_config, run_root
import random
import quippy

test_dir = os.path.abspath(os.path.dirname(__file__))

bulk = ase.io.read(os.path.join(test_dir,"bulk.xyz"), format="extxyz")
tol=1.0e-3 # hack to work around bad convergence
relaxed_bulk = relax_config(bulk, relax_pos=True, relax_cell=True, tol=tol, 
    traj_file=None, config_label='bulk', from_base_model=True, save_config=True)
relaxed_bulk_pe = relaxed_bulk.get_potential_energy()/len(bulk)

orig_cell = relaxed_bulk.get_cell()
energies = []
ns=20
for i in range(0,ns+1):
    l_factor = 1.0-0.5*float(i)/float(ns)
    relaxed_bulk.set_cell(orig_cell*l_factor, True)
    qrb = quippy.Atoms(relaxed_bulk)
    qrb.set_cutoff(3.0)
    qrb.calc_connect()
    try:
        energies.append([ min([nn.distance for nn in qrb.neighbours[1]]), relaxed_bulk.get_potential_energy()/len(relaxed_bulk) ])
    except:
        break

properties={ 'unrelaxed_energies' :  energies }
Esempio n. 17
0
    if vacuum is not None:
        shrink_cell(atoms)
        atoms.cell += np.eye(3) * vacuum

    axis_mask = [True if ax in axis else False for ax in range(3)]
    atoms.positions -= atoms.positions.mean(axis=0) * axis_mask
    return


calc = quippy.Potential('IP TS', param_filename="ts_params.xml")

# Load atomic configuration
fld = sys.argv[1].strip()
params.os.chdir(fld)

crack_slab = quippy.Atoms('slab.xyz')
print('Unit slab with %d atoms per unit cell:' % len(crack_slab))
print(crack_slab.cell)
print('')

in_put = raw_input('Perform dry system generation (guess configuration)?')
GUESS_RUN = (in_put in ['y', 'Y', 'yes'])
if GUESS_RUN:
    print("Performing dry run...")
else:
    print("Performing full system construction...")

# open up the cell along x and y by introducing some vacuum
center_atoms(crack_slab, vacuum=params.vacuum)

# centre the slab on the origin
Esempio n. 18
0
    jjj += 1
traj_name = 'md-%s-%03d.xyz' % (basename, jjj)
db_name = 'db-%s-%03d.csv' % (basename, jjj)
log_name = 'md-%s-%03d.log' % (basename, jjj)

# ***** Initialise Atoms object *****
if not at.has_property('momenta'):
    print("Resetting momenta to desired temperature")
    MaxwellBoltzmannDistribution(at, 2.0 * params.sim_T * units.kB)

try:
    clamp_mask = at.get_array('clamp_mask')
    fix_line_mask = at.get_array('fix_line_mask')
    initial_positions = at.get_array('pos_orig')
except:
    at_help = quippy.Atoms('crack.xyz')
    clamp_mask = at_help.get_array('clamp_mask')
    # fix_line_mask = at_help.get_array('fix_line_mask')
    initial_positions = at_help.get_array('pos_orig')
    at_help = None

at.set_calculator(calc)

# set atoms order
_, dists = find_mic(initial_positions - initial_positions[tipatoms[0]],
                    at.get_cell())
at_order = np.argsort(dists)[:120]

# ***** Setup constraints *****
# springs = [Hookean(a1=i, a2=[0,-1,0,initial_positions[i,1]], k=k_spring, rt=0) for i in np.where(clamp_mask)[0]]
springs = [
Esempio n. 19
0
import quippy
import re
import os

import __builtin__

# the current model
import model

a0 = 5.43  # initial guess at lattice constant, cell will be relaxed below
N = 2  # number of unit cells in each direction

# set up the a
bulk = Diamond(symbol='Si', latticeconstant=a0)
bulk *= (N, N, N)
bulk = quippy.Atoms(bulk)


def save_hook(traj, a=bulk):
    traj.append(a.copy())


quippy.system_set_random_seeds(10)

debug = True
save_traj = True
n_steps_heat = 20000
n_steps_equil = 10000
n_steps_liquid = 5000
T_melt = 5000.0
T_equil = 2000.0