def xyz(project, id): fd = io.StringIO() from ase.io.xyz import write_xyz db = databases[project] write_xyz(fd, db.get_atoms(id)) data = fd.getvalue() return data, '{}.xyz'.format(id)
def xyz(id): fd = io.StringIO() from ase.io.xyz import write_xyz db = database() write_xyz(fd, db.get_atoms(id)) data = fd.getvalue() return data, '{0}.xyz'.format(id)
def append(ats, rr, initial_crack, output_file='joined.xyz'): num_images = len(ats) for i, at in enumerate(ats): print i + 1, '/', num_images, initial_crack fixed_mask = (np.sqrt( map(sum, map(np.square, at.positions[:, 0:3] - initial_crack[0:3]))) <= rr) cl = at.select(fixed_mask) write_xyz(output_file, cl, append=True)
def CalculateOnTeran(molecule_prefix, molecule_start, molecule_end): MOL = atoms[molecule_start:molecule_end] n_mol = len(MOL) write_xyz(fileobj='gaussian_in.com', images=MOL) bash('./gaussian.sh') print('Calculating ' + molecule_prefix + ' on Isabella...') bash('./teran.sh ' + molecule_prefix + ' ' + str(n_mol)) print('Isabella calculation done.') return ()
def save_molecule(self, name, file_format='xyz', append=False): """ Save the current molecular geometry. Args: name (str): Name of save-file. file_format (str): Format to store geometry (default xyz). append (bool): If set to true, geometry is added to end of file (default False). """ molecule_path = os.path.join(self.working_dir, "%s.%s" % (name, file_format)) if file_format == "xyz": # For extended xyz format, plain is needed since ase can not parse the extxyz it writes write_xyz(molecule_path, self.molecule, plain=True) else: write(molecule_path, self.molecule, format=file_format, append=append)
def pull_file(args, dir_name=None): if dir_name == None: ats = read(args.input, index=":") else: ats = read(os.path.join(dir_name, args.input), index=":") if not args.full_qm: init_ats = Atoms("crack_sim.xyz") crack_pos = init_ats.info["CrackPos"] qm_radius = 3.0 buff = 8.0 mm_pos = init_ats.get_positions() x, y, z = init_ats.positions.T #radius1 = np.sqrt((x - crack_pos[0])**2 + (y-crack_pos[1])**2 + (z-crack_pos[2])**2) radius1 = np.sqrt((x - crack_pos[0])**2 + (y - crack_pos[1])**2) qm_region_mask = (radius1 < qm_radius) qm_pos = init_ats.get_positions()[qm_region_mask] qm_com = qm_pos.mean(axis=0) # just to avoid pbc errors.. cell_center = np.diag(ats[0].get_cell()) / 2.0 print cell_center print 'Full Cell CrackPos: ', crack_pos crack_pos = crack_pos - qm_com + cell_center print 'Shift CrackPos', crack_pos print 'QM Radius', qm_radius print len(ats) for at in ats[args.start:args.end]: #mark quantum atoms x, y, z = at.positions.T radius1 = np.sqrt((x - crack_pos[0])**2 + (y - crack_pos[1])**2 + (z - crack_pos[2])**2) qm_region_mask = np.array(map(int, (radius1 <= qm_radius))) print sum(qm_region_mask) at.new_array("qm_atoms", qm_region_mask, dtype=float) at.set_array("qm_atoms", qm_region_mask) write_xyz(args.output, at, append=True) else: for at in ats[args.start:args.end]: write_xyz(args.output, at, append=True)
def convert_PDB_2_XYZ(file, comment=None): """ Convert PDB to standard (NOT exteneded) XYZ file, save and return structure """ xyz_file = file.replace('.pdb', '.xyz') print('converting:', file, 'to', xyz_file) if exists(xyz_file) is False: structure = read(file) if comment is None: cmt = 'This is an XYZ structure.' else: cmt = comment write_xyz(xyz_file, images=structure, comment=cmt, columns=['symbols', 'positions']) print('conversion done.') structure = read(xyz_file) return xyz_file, structure
def cmd_xyz(ctx, label_file): """ Commandline tool for creating a concatenated xyz files from res also, the labels for each strucure is saved """ titl_list, atoms_list = ctx.obj['titl_list'], ctx.obj['atoms_list'] output = ctx.obj['output'] # Setup info for atoms for atoms, titl in zip(atoms_list, titl_list): atoms.info['label'] = titl.label atoms.info['enthalpy'] = titl.enthalpy atoms.info['pressure'] = titl.pressure atoms.info['symmetry'] = titl.symm # Write the xyz files write_xyz(output, atoms_list) # Write the label file from tabulate import tabulate if label_file: data = [[ 'label', 'natoms', 'enthalpy', 'volume', 'pressure', 'symmetry' ]] for titl in titl_list: data.append([ titl.label, titl.natoms, titl.enthalpy / titl.natoms, titl.volume / titl.natoms, titl.pressure, titl.symm ]) if label_file.endswith('.csv'): dataframe = pd.DataFrame(data[1:], columns=data[0]) dataframe.to_csv(label_file, index=False) else: content = tabulate(data, headers='firstrow', tablefmt='plain') with open(label_file, 'w') as fhandle: fhandle.write('#') fhandle.write(content)
def write(filename, images, format=None, **kwargs): """Write Atoms object(s) to file. filename: str Name of the file to write to. images: Atoms object or list of Atoms objects A single Atoms object or a list of Atoms objects. format: str Used to specify the file-format. If not given, the file-format will be taken from suffix of the filename. The accepted output formats: ========================= =========== format short name ========================= =========== ASE pickle trajectory traj ASE bundle trajectory bundle CUBE file cube XYZ-file xyz VASP POSCAR/CONTCAR file vasp ABINIT input file abinit Protein Data Bank pdb CIF-file cif XCrySDen Structure File xsf FHI-aims geometry file aims gOpenMol .plt file plt Python script py Encapsulated Postscript eps Portable Network Graphics png Persistance of Vision pov VTK XML Image Data vti VTK XML Structured Grid vts VTK XML Unstructured Grid vtu TURBOMOLE coord file tmol exciting exi AtomEye configuration cfg WIEN2k structure file struct CASTEP cell file cell DftbPlus input file dftb ETSF etsf.nc DFTBPlus GEN format gen CMR db/cmr-file db CMR db/cmr-file cmr ========================= =========== The use of additional keywords is format specific. The ``cube`` and ``plt`` formats accept (plt requires it) a ``data`` keyword, which can be used to write a 3D array to the file along with the nuclei coordinates. The ``vti``, ``vts`` and ``vtu`` formats are all specifically directed for use with MayaVi, and the latter is designated for visualization of the atoms whereas the two others are intended for volume data. Further, it should be noted that the ``vti`` format is intended for orthogonal unit cells as only the grid-spacing is stored, whereas the ``vts`` format additionally stores the coordinates of each grid point, thus making it useful for volume date in more general unit cells. The ``eps``, ``png``, and ``pov`` formats are all graphics formats, and accept the additional keywords: rotation: str (default '') The rotation angles, e.g. '45x,70y,90z'. show_unit_cell: int (default 0) Can be 0, 1, 2 to either not show, show, or show all of the unit cell. radii: array or float (default 1.0) An array of same length as the list of atoms indicating the sphere radii. A single float specifies a uniform scaling of the default covalent radii. bbox: 4 floats (default None) Set the bounding box to (xll, yll, xur, yur) (lower left, upper right). colors: array (default None) An array of same length as the list of atoms, indicating the rgb color code for each atom. Default is the jmol_colors of ase/data/colors. scale: int (default 20) Number of pixels per Angstrom. For the ``pov`` graphics format, ``scale`` should not be specified. The elements of the color array can additionally be strings, or 4 and 5 vectors for named colors, rgb + filter, and rgb + filter + transmit specification. This format accepts the additional keywords: ``run_povray``, ``display``, ``pause``, ``transparent``, ``canvas_width``, ``canvas_height``, ``camera_dist``, ``image_plane``, ``camera_type``, ``point_lights``, ``area_light``, ``background``, ``textures``, ``celllinewidth``, ``bondlinewidth``, ``bondatoms`` """ if format is None: if filename == '-': format = 'xyz' filename = sys.stdout elif 'POSCAR' in filename or 'CONTCAR' in filename: format = 'vasp' elif 'OUTCAR' in filename: format = 'vasp_out' elif filename.endswith('etsf.nc'): format = 'etsf' elif os.path.basename(filename) == 'coord': format = 'tmol' else: suffix = filename.split('.')[-1] format = { 'cell': 'castep_cell', }.get(suffix, suffix) # XXX this does not make sense # Maybe like this: ## format = {'traj': 'trajectory', ## 'nc': 'netcdf', ## 'exi': 'exciting', ## 'in': 'aims', ## 'tmol': 'turbomole', ## }.get(suffix, suffix) if format == 'castep_cell': from ase.io.castep import write_cell write_cell(filename, images, **kwargs) return if format == 'exi': from ase.io.exciting import write_exciting write_exciting(filename, images) return if format == 'cif': from ase.io.cif import write_cif write_cif(filename, images) if format == 'xyz': from ase.io.xyz import write_xyz write_xyz(filename, images) return if format == 'gen': from ase.io.gen import write_gen write_gen(filename, images) return elif format == 'in': format = 'aims' elif format == 'tmol': from ase.io.turbomole import write_turbomole write_turbomole(filename, images) return elif format == 'dftb': from ase.io.dftb import write_dftb write_dftb(filename, images) return elif format == 'struct': from ase.io.wien2k import write_struct write_struct(filename, images, **kwargs) return elif format == 'findsym': from ase.io.findsym import write_findsym write_findsym(filename, images) return elif format == 'etsf': from ase.io.etsf import ETSFWriter writer = ETSFWriter(filename) if not isinstance(images, (list, tuple)): images = [images] writer.write_atoms(images[0]) writer.close() return elif format == 'db' or format == 'cmr': from ase.io.cmr_io import write_db return write_db(filename, images, **kwargs) format = { 'traj': 'trajectory', 'nc': 'netcdf', 'bundle': 'bundletrajectory' }.get(format, format) name = 'write_' + format if format in ['vti', 'vts', 'vtu']: format = 'vtkxml' if format is None: format = filetype(filename) try: write = getattr(__import__('ase.io.%s' % format, {}, {}, [name]), name) except ImportError: raise TypeError('Unknown format: "%s".' % format) write(filename, images, **kwargs)
def write(filename, images, format=None, **kwargs): """Write Atoms object(s) to file. filename: str Name of the file to write to. images: Atoms object or list of Atoms objects A single Atoms object or a list of Atoms objects. format: str Used to specify the file-format. If not given, the file-format will be taken from suffix of the filename. The accepted output formats: ========================= =========== format short name ========================= =========== ASE pickle trajectory traj ASE bundle trajectory bundle CUBE file cube XYZ-file xyz VASP POSCAR/CONTCAR file vasp ABINIT input file abinit Protein Data Bank pdb CIF-file cif XCrySDen Structure File xsf FHI-aims geometry file aims gOpenMol .plt file plt Python script py Encapsulated Postscript eps Portable Network Graphics png Persistance of Vision pov VTK XML Image Data vti VTK XML Structured Grid vts VTK XML Unstructured Grid vtu TURBOMOLE coord file tmol exciting exi AtomEye configuration cfg WIEN2k structure file struct CASTEP cell file cell DftbPlus input file dftb ETSF etsf.nc DFTBPlus GEN format gen CMR db/cmr-file db CMR db/cmr-file cmr ========================= =========== The use of additional keywords is format specific. The ``cube`` and ``plt`` formats accept (plt requires it) a ``data`` keyword, which can be used to write a 3D array to the file along with the nuclei coordinates. The ``vti``, ``vts`` and ``vtu`` formats are all specifically directed for use with MayaVi, and the latter is designated for visualization of the atoms whereas the two others are intended for volume data. Further, it should be noted that the ``vti`` format is intended for orthogonal unit cells as only the grid-spacing is stored, whereas the ``vts`` format additionally stores the coordinates of each grid point, thus making it useful for volume date in more general unit cells. The ``eps``, ``png``, and ``pov`` formats are all graphics formats, and accept the additional keywords: rotation: str (default '') The rotation angles, e.g. '45x,70y,90z'. show_unit_cell: int (default 0) Can be 0, 1, 2 to either not show, show, or show all of the unit cell. radii: array or float (default 1.0) An array of same length as the list of atoms indicating the sphere radii. A single float specifies a uniform scaling of the default covalent radii. bbox: 4 floats (default None) Set the bounding box to (xll, yll, xur, yur) (lower left, upper right). colors: array (default None) An array of same length as the list of atoms, indicating the rgb color code for each atom. Default is the jmol_colors of ase/data/colors. scale: int (default 20) Number of pixels per Angstrom. For the ``pov`` graphics format, ``scale`` should not be specified. The elements of the color array can additionally be strings, or 4 and 5 vectors for named colors, rgb + filter, and rgb + filter + transmit specification. This format accepts the additional keywords: ``run_povray``, ``display``, ``pause``, ``transparent``, ``canvas_width``, ``canvas_height``, ``camera_dist``, ``image_plane``, ``camera_type``, ``point_lights``, ``area_light``, ``background``, ``textures``, ``celllinewidth``, ``bondlinewidth``, ``bondatoms`` """ if format is None: if filename == '-': format = 'xyz' filename = sys.stdout elif 'POSCAR' in filename or 'CONTCAR' in filename: format = 'vasp' elif 'OUTCAR' in filename: format = 'vasp_out' elif filename.endswith('etsf.nc'): format = 'etsf' elif os.path.basename(filename) == 'coord': format = 'tmol' else: suffix = filename.split('.')[-1] format = {'cell':'castep_cell', }.get(suffix, suffix) # XXX this does not make sense # Maybe like this: ## format = {'traj': 'trajectory', ## 'nc': 'netcdf', ## 'exi': 'exciting', ## 'in': 'aims', ## 'tmol': 'turbomole', ## }.get(suffix, suffix) if format == 'castep_cell': from ase.io.castep import write_cell write_cell(filename, images, **kwargs) return if format == 'exi': from ase.io.exciting import write_exciting write_exciting(filename, images) return if format == 'cif': from ase.io.cif import write_cif write_cif(filename, images) if format == 'xyz': from ase.io.xyz import write_xyz write_xyz(filename, images) return if format == 'gen': from ase.io.gen import write_gen write_gen(filename, images) return elif format == 'in': format = 'aims' elif format == 'tmol': from ase.io.turbomole import write_turbomole write_turbomole(filename, images) return elif format == 'dftb': from ase.io.dftb import write_dftb write_dftb(filename, images) return elif format == 'struct': from ase.io.wien2k import write_struct write_struct(filename, images, **kwargs) return elif format == 'findsym': from ase.io.findsym import write_findsym write_findsym(filename, images) return elif format == 'etsf': from ase.io.etsf import ETSFWriter writer = ETSFWriter(filename) if not isinstance(images, (list, tuple)): images = [images] writer.write_atoms(images[0]) writer.close() return elif format == 'db' or format == 'cmr': from ase.io.cmr_io import write_db return write_db(filename, images, **kwargs) format = {'traj': 'trajectory', 'nc': 'netcdf', 'bundle': 'bundletrajectory' }.get(format, format) name = 'write_' + format if format in ['vti', 'vts', 'vtu']: format = 'vtkxml' if format is None: format = filetype(filename) try: write = getattr(__import__('ase.io.%s' % format, {}, {}, [name]), name) except ImportError: raise TypeError('Unknown format: "%s".' % format) write(filename, images, **kwargs)
def xyz(id): fd = io.BytesIO() from ase.io.xyz import write_xyz write_xyz(fd, db.get_atoms(id)) data = fd.getvalue() return data, '{0}.xyz'.format(id)
scratch = "/gss_gpfs_scratch/harms.n/conformers/" ff = file_of_interest.split("/")[-1] label = ff.split(".")[0] os.chdir(scratch) calc = Gaussian(mem="5GB", nprocshared=20, label=label, scratch=".", method="m062x", basis="6-311+g(2df,2p)", multiplicity=1) atoms.set_calculator(calc) opt = BFGS(atoms=atoms) opt.run() results_path = os.path.join( "/gss_gpfs_scratch/harms.n/conformers/new_ga_results", mol, file_of_interest) f = open(results_path, "w") write_xyz(f, atoms) print print "The potential energy of {} is:".format(file_of_interest[20:-4].replace( "/", "_")) print atoms.get_potential_energy()
def write(filename, images, format=None, **kwargs): """Write Atoms object(s) to file. filename: str Name of the file to write to. images: Atoms object or list of Atoms objects A single Atoms object or a list of Atoms objects. format: str Used to specify the file-format. If not given, the file-format will be taken from suffix of the filename. If given as 'babel', will try to use the OpenBabel library. The accepted output formats: ========================= =========== format short name ========================= =========== ASE pickle trajectory traj CUBE file cube XYZ-file xyz VASP POSCAR/CONTCAR file vasp Protein Data Bank pdb XCrySDen Structure File xsf gOpenMol .plt file plt Python script py Encapsulated Postscript eps Portable Network Graphics png Persistance of Vision pov VTK XML Image Data vti VTK XML Structured Grid vts VTK XML Unstructured Grid vtu ========================= =========== The use of additional keywords is format specific. The ``cube`` and ``plt`` formats accept (plt requires it) a ``data`` keyword, which can be used to write a 3D array to the file along with the nuclei coordinates. The ``eps``, ``png``, and ``pov`` formats are all graphics formats, and accept the additional keywords:: rotation='', show_unit_cell=0, radii=None, bbox=None, colors=None, scale=20 The ``vti``, ``vts`` and ``vtu`` formats are all specifically directed for use with MayaVi, and the latter is designated for visualization of the atoms whereas the two others are intended for volume data. Further, it should be noted that the ``vti`` format is intended for orthogonal unit cells as only the grid-spacing is stored, whereas the ``vts`` format additionally stores the coordinates of each grid point, thus making it useful for volume date in more general unit cells. rotation: str The rotation angles, e.g. '45x,70y,90z'. show_unit_cell: int Can be 0, 1, 2 to either not show, show, or show all of the unit cell. radii: array / float An array of same length as the list of atoms indicating the sphere radii. A single float specifies a uniform scaling of the default covalent radii. bbox: array XXX colors: array An array of same length as the list of atoms, indicating the rgb color code for each atom. scale: int Number of pixels per Angstrom. The ``pov`` format accepts the additional keywords: ``run_povray``, ``display``, ``pause``, ``transparent``, ``canvas_width``, ``canvas_height``, ``camera_dist``, ``image_plane``, ``camera_type``, ``point_lights``, ``area_light``, ``background``, ``textures``, ``celllinewidth`` For ``pov`` the elements of the color array can also be strings, or 4, and 5 vectors for named colors, rgb + filter, and rgb + filter + transmit specification. """ if format is None: if filename == '-': format = 'xyz' filename = sys.stdout else: suffix = filename.split('.')[-1] format = {}.get(suffix, suffix) if format == 'xyz': from ase.io.xyz import write_xyz write_xyz(filename, images) return format = {'traj': 'trajectory', 'nc': 'netcdf'}.get(format, format) name = 'write_' + format if format in ['vti', 'vts', 'vtu']: format = 'vtkxml' try: write = getattr(__import__('ase.io.%s' % format, {}, {}, [name]), name) except ImportError: raise TypeError('Unknown format: "%s".' % format) try: write(filename, images, **kwargs) except TypeError: write(filename, images)
def write_slab(a=atoms): write_xyz('surf_traj.xyz', a, append=True)
def write_slab(dynamics=dynamics): if dynamics.state == LOTFDynamics.Interpolation: dynamics.atoms.set_array('avg_sigma', avg_sigma.reshape( (len(atoms), 9))) write_xyz('crack_traj_lotf.xyz', dynamics.atoms, append=True)
def gen_movie(title, list_atoms): from ase.io import xyz with open(title+'.xyz', 'w') as movie_f: xyz.write_xyz(movie_f, list_atoms)
print len(field), len(field[0]), len(field[0][0]) if (oformat == "geometry.in"): tmpname = "geometry.in.tmp" write_aims(tmpname, atoms) f = open(tmpname, 'r') print f.read() f.close() os.remove(tmpname) # write_aims("geometry.in", atoms) # elif(oformat == "cube"): # write_cube(`,xsf[1],xsf[0]) # elif(oformat == "xsf"): # write_xsf(sys.stdout,xsf[1],xsf[0]) elif (oformat == "POSCAR"): write_vasp(ostream, atoms, label=options.comment, direct=False, sort=options.vaspsort, vasp5=options.vaspold) if (oformat == "xyz"): write_xyz(ostream, atoms) if (oformat == "xsf"): write_xsf(sys.stdout, atoms, field) ##write_cube("tmp.cube",xsf[1],xsf[0])
# elif(oformat == "xsf"): # write_xsf(sys.stdout,xsf[1],xsf[0]) elif(oformat == "POSCAR"): write_vasp(ostream, atoms, label=options.comment, direct=options.vaspdirect,sort=options.vaspsort,vasp5=options.vaspold) if(oformat == "xyz"): c = atoms.get_cell() pbc = atoms.get_pbc() fname = "answer.lvs" if(os.path.isfile(fname)): fname += ".new" if( c != None and pbc.all()): f = open(fname, "w") for i in range(3): f.write(str(c[i][0]) + ' '+ str(c[i][1]) + ' ' + str(c[i][2]) + '\n') #write_xyz(ostream, atoms, comment=options.comment) write_xyz(ostream, [atoms], comment=options.comment) if(oformat == "shtm"): d = {} f = open('species.dat', "r") ls = f.read().splitlines() n = int(ls[0]) for ii in ls[1:n+1]: i = ii.split() d[i[3]] = int(i[0]) n = atoms.get_number_of_atoms() pos = atoms.get_positions() sym = atoms.get_chemical_symbols() print atoms.get_number_of_atoms() for s, p in zip(sym, pos):
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties=properties, system_changes=system_changes) # dftd3 can either do fully 3D periodic or non-periodic calculations. # It cannot do calculations that are only periodic in 1 or 2 # dimensions. If the atoms object is periodic in only 1 or 2 # dimensions, then treat it as a fully 3D periodic system, but warn # the user. pbc = False if any(atoms.pbc): if not all(atoms.pbc): warn('WARNING! dftd3 can only calculate the dispersion energy ' 'of non-periodic or 3D-periodic systems. We will treat ' 'this system as 3D-periodic!') pbc = True if pbc: fname = os.path.join(self.directory, '{}.POSCAR'.format(self.label)) write_vasp(fname, atoms) else: fname = os.path.join(self.directory, '{}.xyz'.format(self.label)) write_xyz(fname, atoms, plain=True) # Generate custom damping parameters file. This is kind of ugly, but # I don't know of a better way of doing this. if self.custom_damp: damppars = [] # s6 is always first damppars.append(str(float(self.parameters['s6']))) # sr6 is the second value for zero{,m} damping, a1 for bj{,m} if self.parameters['damping'] in ['zero', 'zerom']: damppars.append(str(float(self.parameters['sr6']))) elif self.parameters['damping'] in ['bj', 'bjm']: damppars.append(str(float(self.parameters['a1']))) # s8 is always third damppars.append(str(float(self.parameters['s8']))) # sr8 is fourth for zero, a2 for bj{,m}, beta for zerom if self.parameters['damping'] == 'zero': damppars.append(str(float(self.parameters['sr8']))) elif self.parameters['damping'] in ['bj', 'bjm']: damppars.append(str(float(self.parameters['a2']))) elif self.parameters['damping'] == 'zerom': damppars.append(str(float(self.parameters['beta']))) # alpha6 is always fifth damppars.append(str(int(self.parameters['alpha6']))) # last is the version number if self.parameters['old']: damppars.append('2') elif self.parameters['damping'] == 'zero': damppars.append('3') elif self.parameters['damping'] == 'bj': damppars.append('4') elif self.parameters['damping'] == 'zerom': damppars.append('5') elif self.parameters['damping'] == 'bjm': damppars.append('6') damp_fname = os.path.join(self.directory, '.dftd3par.local') with open(damp_fname, 'w') as f: f.write(' '.join(damppars))
from ase.io import read from ase.io.xyz import write_xyz import glob for i in glob.glob('*.pdb'): print(i) a = read(i) cmt = 'This is an XYZ structure.' write_xyz(i.replace('.pdb', '.xyz'), images=a, comment=cmt, columns=['symbols', 'positions'])
if not name in os.listdir("/gss_gpfs_scratch/harms.n/conformers/es"): os.mkdir(name) os.chdir("/gss_gpfs_scratch/harms.n/conformers/es/{}".format(name)) mol = AutoTST_Molecule(smiles) mol.ase_molecule.set_calculator(Hotbit()) final, confs = perform_simple_es(mol, min_rms=60) _, non_terminal_torsions = find_terminal_torsions(mol) logging.info("The dictonary corresponding to the conformer analysis is:") print("\t{}".format(confs)) from time import time t_0 = time() for ind, combo in enumerate(confs.iterkeys()): for index, tor in enumerate(non_terminal_torsions): dihedral = combo[index] mol.ase_molecule.set_dihedral(tor.indices, angle=dihedral, mask=tor.right_mask) mol.update_from_ase_mol() label = "{0}_{1}_{2}_{3}.xyz".format(name, "es", ith, ind) f = open(label, "w") write_xyz(f, mol.ase_molecule) logging.info("This process took: {} s".format(time() - t_0))
def write_slab(a=atoms): write_xyz('crack_traj.xyz', a, append=True)
ra = options.rotate_around if (ra > 0 and ra <= natoms): positions = step.arrays['positions'] origin = positions[ra - 1] # rotate selected atoms asekk.rotate_atoms(step, alpha, fromto=[a_from, a_to], axis=options.axis, origin=origin) # --- Repetytion ---- if (do_we_repeat): # multiply by periods step = step * p # ----- Write ----- if (options.format == 'xyz'): write_xyz(sys.stdout, step, comment=comm) elif (options.format == 'aims'): write_aims("geometry.in", step) elif (options.format == 'poscar'): # print step.get_cell() step.center() write_vasp(sys.stdout, step, label="POSCAR generated by asm.xyz.py", direct=False, sort=False, vasp5=True)
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties=properties, system_changes=system_changes) # dftd3 can either do fully 3D periodic or non-periodic calculations. # It cannot do calculations that are only periodic in 1 or 2 # dimensions. If the atoms object is periodic in only 1 or 2 # dimensions, then treat it as a fully 3D periodic system, but warn # the user. pbc = False if any(atoms.pbc): if not all(atoms.pbc): warn('WARNING! dftd3 can only calculate the dispersion energy ' 'of non-periodic or 3D-periodic systems. We will treat ' 'this system as 3D-periodic!') pbc = True if self.comm.rank == 0: if pbc: fname = os.path.join(self.directory, '{}.POSCAR'.format(self.label)) write_vasp(fname, atoms) else: fname = os.path.join(self.directory, '{}.xyz'.format(self.label)) write_xyz(fname, atoms, plain=True) # Generate custom damping parameters file. This is kind of ugly, but # I don't know of a better way of doing this. if self.custom_damp: damppars = [] # s6 is always first damppars.append(str(float(self.parameters['s6']))) # sr6 is the second value for zero{,m} damping, a1 for bj{,m} if self.parameters['damping'] in ['zero', 'zerom']: damppars.append(str(float(self.parameters['sr6']))) elif self.parameters['damping'] in ['bj', 'bjm']: damppars.append(str(float(self.parameters['a1']))) # s8 is always third damppars.append(str(float(self.parameters['s8']))) # sr8 is fourth for zero, a2 for bj{,m}, beta for zerom if self.parameters['damping'] == 'zero': damppars.append(str(float(self.parameters['sr8']))) elif self.parameters['damping'] in ['bj', 'bjm']: damppars.append(str(float(self.parameters['a2']))) elif self.parameters['damping'] == 'zerom': damppars.append(str(float(self.parameters['beta']))) # alpha6 is always fifth damppars.append(str(int(self.parameters['alpha6']))) # last is the version number if self.parameters['old']: damppars.append('2') elif self.parameters['damping'] == 'zero': damppars.append('3') elif self.parameters['damping'] == 'bj': damppars.append('4') elif self.parameters['damping'] == 'zerom': damppars.append('5') elif self.parameters['damping'] == 'bjm': damppars.append('6') damp_fname = os.path.join(self.directory, '.dftd3par.local') if self.comm.rank == 0: with open(damp_fname, 'w') as f: f.write(' '.join(damppars))
def write_cluster(ats=atoms, qmmm_pot=qmmm_pot): qm_list = list((qmmm_pot.atoms.hybrid > 0).nonzero()[0]) qm_ats = ats[qm_list] write_xyz('cluster.xyz', qm_ats, append=True)
def write_slab(dynamics=dynamics): if dynamics.state == LOTFDynamics.Interpolation: dynamics.atoms.set_array('avg_sigma', avg_sigma.reshape((len(atoms), 9))) write_xyz('crack_slab.xyz', dynamics.atoms, append=True)
print "Job number {0} is the {1}th optimization of {2}.".format(job_number, ith, name) os.chdir("/gss_gpfs_scratch/harms.n/conformers/new_ga/") if not name in os.listdir("/gss_gpfs_scratch/harms.n/conformers/new_ga"): os.mkdir(name) os.chdir(name) mol = AutoTST_Molecule(smiles) mol.ase_molecule.set_calculator(Hotbit()) final, confs = perform_ga(autotst_object = mol, min_rms=30) _, non_terminal_torsions = find_terminal_torsions(mol) logging.info("The dictonary corresponding to the conformer analysis is:") print("\t{}".format(confs)) from time import time t_0 = time() for ind, combo in enumerate(confs.iterkeys()): for index, tor in enumerate(non_terminal_torsions): dihedral = combo[index] mol.ase_molecule.set_dihedral(tor.indices, angle=dihedral, mask=tor.right_mask) mol.update_from_ase_mol() label = "{0}_{1}_{2}_{3}.xyz".format(name, "ga", ith, ind) f = open(label, "w") write_xyz(f, mol.ase_molecule) logging.info("This process took: {} s".format(time() - t_0))
def fix_cyclopropenyl(xyz: str, mol_string: str) -> str: """Detect cyclopropenyl groups and assure they are planar. Args: xyz: Current structure in XYZ format mol_string: SMILES or InChI string of the molecule Returns: Version of atoms with the rings flattened """ # Find cyclopropenyl groups mol = parse_from_molecule_string(mol_string) rings = mol.GetSubstructMatches(Chem.MolFromSmarts("c1c[c+]1")) if len(rings) == 0: return xyz # no changes # For each ring, flatten it atoms = next(simple_read_xyz(StringIO(xyz), slice(None))) g = convert_string_to_nx(mol_string) for ring in rings: # Get the normal of the ring normal = np.cross(*np.subtract(atoms.positions[ring[:2], :], atoms.positions[ring[2], :])) normal /= np.linalg.norm(normal) # Adjust the groups attached to each member of the ring for ring_atom in ring: # Get the ID of the group bonded to it bonded_atom = next(r for r in g[ring_atom] if r not in ring) # Determine the atoms that are part of that functional group h = g.copy() h.remove_edge(ring_atom, bonded_atom) a, b = nx.connected_components(h) mask = np.zeros((len(atoms), ), dtype=bool) if bonded_atom in a: mask[list(a)] = True else: mask[list(b)] = True # Get the rotation angle bond_vector = atoms.positions[bonded_atom, :] - atoms.positions[ ring_atom, :] angle = np.dot(bond_vector, normal) / np.linalg.norm(bond_vector) rot_angle = np.arccos(angle) - np.pi / 2 logger.debug(f'Rotating by {rot_angle} radians') # Perform the rotation rotation_axis = np.cross(bond_vector, normal) atoms._masked_rotate(atoms.positions[ring_atom], rotation_axis, rot_angle, mask) # make the atom at a 150 angle with the the ring too another_ring = next(r for r in ring if r != ring_atom) atoms.set_angle(another_ring, ring_atom, bonded_atom, 150, mask=mask) assert np.isclose( atoms.get_angle(another_ring, ring_atom, bonded_atom), 150).all() # Make sure it worked bond_vector = atoms.positions[bonded_atom, :] - atoms.positions[ ring_atom, :] angle = np.dot(bond_vector, normal) / np.linalg.norm(bond_vector) final_angle = np.arccos(angle) assert np.isclose(final_angle, np.pi / 2).all() logger.info( f'Detected {len(rings)} cyclopropenyl rings. Ensured they are planar.' ) # Write to a string out = StringIO() write_xyz(out, [atoms]) return out.getvalue()
def write_slab(a=crack_slab): write_xyz('crack_slab.xyz', a, append=True)
poscar.set_cell(c) # --------------- unit cell2 extending ----------------- u = options.cell2_extend if (u != [0.0, 0.0, 0.0]): c = poscar.get_cell() c[1] += np.array(u) poscar.set_cell(c) # --------------- unit cell3 extending ----------------- u = options.cell3_extend if (u != [0.0, 0.0, 0.0]): c = poscar.get_cell() c[2] += np.array(u) poscar.set_cell(c) # --------------- Periodic repetitions ----------------- p = options.periods if (p != [1, 1, 1]): poscar = poscar * (p[0], p[1], p[2]) # print p # --------------- Wirting out in proper format ----------------- if (options.format == "POSCAR"): write_vasp(sys.stdout, poscar, label=options.comment, direct=False, sort=False, vasp5=True) elif (options.format == "xyz"): write_xyz(sys.stdout, poscar, options.comment)
scratch = "/gss_gpfs_scratch/harms.n/conformers/" ff = file_of_interest.split("/")[-1] label = ff.split(".")[0] os.chdir(scratch) calc = Gaussian(mem="5GB", nprocshared=20, label=label, scratch=".", method="m062x", basis="6-311+g(2df,2p)", multiplicity=1 ) atoms.set_calculator(calc) opt = BFGS(atoms=atoms) opt.run() results_path = os.path.join("/gss_gpfs_scratch/harms.n/conformers/es_results", mol, file_of_interest) f = open(results_path, "w") write_xyz(f, atoms) print print "The potential energy of {} is:".format(file_of_interest[20:-4].replace("/","_")) print atoms.get_potential_energy()
from ase.io.aims import read_aims_output from ase.io.xyz import write_xyz from optparse import OptionParser parser = OptionParser() parser.add_option("-g", "--get", action="store", type="string", default="positions", help="Type of data we want to get") parser.add_option("-p", "--period", action="store", type="int", help="period", nargs=3) (options, args) = parser.parse_args() # count number of command line arguments num = len(sys.argv) if(num < 2): parser.print_help() else: output = read_aims_output(sys.argv[num-1], slice(0,None,1)) n = len(output) if(n > 0): i=0 for step in output: i += 1 if(options.get == "positions"): comm = "step no. " + str(i) + " TOTEN = " + str(step.get_total_energy()) p=options.period if(p != None): step = step*(p[0], p[1], p[2]) write_xyz(sys.stdout,[step],comment=comm) # print step.
def gen_movie(title, list_atoms): from ase.io import xyz with open(title + '.xyz', 'w') as movie_f: xyz.write_xyz(movie_f, list_atoms)