コード例 #1
0
def Minimisation_Function(cluster, collection, cluster_name):
    #######################################################################################
    cluster.pbc = True  # make sure that the periodic boundry conditions are set off
    #######################################################################################
    # Perform the local optimisation method on the cluster.
    original_path = os.getcwd()
    offspring_name = str(cluster_name)
    clusters_to_make_name = 'clusters_for_VASP'
    if not os.path.exists(clusters_to_make_name):
        os.makedir(clusters_to_make_name)
    copyfile('VASP_Files/INCAR',
             clusters_to_make_name + '/' + offspring_name + '/INCAR')
    copyfile('VASP_Files/POTCAR',
             clusters_to_make_name + '/' + offspring_name + '/POTCAR')
    copyfile('VASP_Files/KPOINTS',
             clusters_to_make_name + '/' + offspring_name + '/KPOINTS')
    os.chdir(clusters_to_make_name + '/' + offspring_name)
    ase_write(cluster, 'POSCAR', 'vasp')
    startTime = time.time()
    try:
        Popen(['srun', 'vasp'])
    except Exception:
        pass
    endTime = time.time()
    cluster = ase_read('OUTCAR')
    os.chdir(original_path)
    ####################################################################################################################
    # Write information about the algorithm
    Info = {}
    Info["INFO.txt"] = ''
    #Info["INFO.txt"] += ("No of Force Calls: " + str(dyn.get_number_of_steps()) + '\n')
    Info["INFO.txt"] += ("Time (s): " + str(endTime - startTime) + '\n')
    #Info["INFO.txt"] += ("Cluster converged?: " + str(dyn.converged()) + '\n')
    ####################################################################################################################
    return cluster, converged, Info
コード例 #2
0
def draw_3d(xyz=None, species=None, project_directory=None, save_only=False):
    """
    Draws the molecule in a "3D-balls" style
    If xyz ig given, it will be used, otherwise the function looks for species.final_xyz
    Input coordinates are in string format
    Saves an image if a species and `project_directory` are provided
    If `save_only` is ``True``, then don't plot, only save the image
    """
    xyz = check_xyz_species_for_drawing(xyz, species)
    _, atoms, x, y, z = get_xyz_matrix(xyz)
    atoms = [str(a) for a in atoms]
    ase_atoms = list()
    for i, atom in enumerate(atoms):
        ase_atoms.append(Atom(symbol=atom, position=(x[i], y[i], z[i])))
    ase_mol = Atoms(ase_atoms)
    if not save_only:
        display(view(ase_mol, viewer='x3d'))
    if project_directory is not None and species is not None:
        folder_name = 'rxns' if species.is_ts else 'Species'
        geo_path = os.path.join(project_directory, 'output', folder_name,
                                species.label, 'geometry')
        if not os.path.exists(geo_path):
            os.makedirs(geo_path)
        ase_write(filename=os.path.join(geo_path, 'geometry.png'),
                  images=ase_mol,
                  scale=100)
コード例 #3
0
    def write_traj(self,
                   filename,
                   format=None,
                   parallel=True,
                   append=False,
                   stride=1,
                   center_of_mass=False,
                   **kwargs):
        """
        Writes the trajectory in a given file format based on the `ase.io.write`_ function.

        Args:
            filename (str): Filename of the output
            format (str): The specific format of the output
            parallel (bool):
            append (bool):
            stride (int): Writes trajectory every `stride` steps
            center_of_mass (bool): True if the positions are centered on the COM
            **kwargs: Additional ase arguments

        .. _ase.io.write: https://wiki.fysik.dtu.dk/ase/_modules/ase/io/formats.html#write
        """
        traj = self.trajectory(stride=stride, center_of_mass=center_of_mass)
        # Using thr ASE output writer
        ase_write(filename=filename,
                  images=traj,
                  format=format,
                  parallel=parallel,
                  append=append,
                  **kwargs)
コード例 #4
0
    def write(self, filename: str) -> None:
        """
        Saves cluster space to a file.

        Parameters
        ---------
        filename
            name of file to which to write
        """

        with tarfile.open(name=filename, mode='w') as tar_file:

            # write items
            items = dict(cutoffs=self._cutoffs,
                         chemical_symbols=self._input_chemical_symbols,
                         pruning_history=self._pruning_history,
                         symprec=self.symprec,
                         position_tolerance=self.position_tolerance)
            temp_file = tempfile.TemporaryFile()
            pickle.dump(items, temp_file)
            temp_file.seek(0)
            tar_info = tar_file.gettarinfo(arcname='items', fileobj=temp_file)
            tar_file.addfile(tar_info, temp_file)
            temp_file.close()

            # write structure
            temp_file = tempfile.NamedTemporaryFile()
            ase_write(temp_file.name, self._input_structure, format='json')
            temp_file.seek(0)
            tar_info = tar_file.gettarinfo(arcname='atoms', fileobj=temp_file)
            tar_file.addfile(tar_info, temp_file)
            temp_file.close()
コード例 #5
0
ファイル: io.py プロジェクト: AlexBuccheri/python
def write(f_name, spg_molecule, pbc = None):
    ase_primitive_cell = spglib_to_ase(spg_molecule)

    if pbc:
        assert(isinstance(pbc, tuple))
        ase_primitive_cell.set_pbc(pbc)

    ase_write(f_name, ase_primitive_cell)
    return
コード例 #6
0
    def write_traj(
        self,
        filename,
        file_format=None,
        parallel=True,
        append=False,
        stride=1,
        center_of_mass=False,
        atom_indices=None,
        snapshot_indices=None,
        overwrite_positions=None,
        overwrite_cells=None,
        **kwargs
    ):
        """
        Writes the trajectory in a given file file_format based on the `ase.io.write`_ function.

        Args:
            filename (str): Filename of the output
            file_format (str): The specific file_format of the output
            parallel (bool): ase parameter
            append (bool): ase parameter
            stride (int): Writes trajectory every `stride` steps
            center_of_mass (bool): True if the positions are centered on the COM
            atom_indices (list/numpy.ndarray): The atom indices for which the trajectory should be generated
            snapshot_indices (list/numpy.ndarray): The snapshots for which the trajectory should be generated
            overwrite_positions (list/numpy.ndarray): List of positions that are meant to overwrite the existing
                                                      trajectory. Useful to wrap coordinates for example
            overwrite_cells(list/numpy.ndarray): List of cells that are meant to overwrite the existing
                                                 trajectory. Only used when `overwrite_positions` is defined. This must
                                                 have the same length of `overwrite_positions`
            **kwargs: Additional ase arguments

        .. _ase.io.write: https://wiki.fysik.dtu.dk/ase/_modules/ase/io/formats.html#write
        """
        traj = self.trajectory(
            stride=stride,
            center_of_mass=center_of_mass,
            atom_indices=atom_indices,
            snapshot_indices=snapshot_indices,
            overwrite_positions=overwrite_positions,
            overwrite_cells=overwrite_cells
        )
        # Using thr ASE output writer
        ase_write(
            filename=filename,
            images=traj,
            format=file_format,
            parallel=parallel,
            append=append,
            **kwargs
        )
コード例 #7
0
    def calculate(self, structure, **kwargs):

        atoms = scale_structure(
            structure,
            scaling_type=self.atoms_scaling,
            atoms_scaling_cutoffs=self.atoms_scaling_cutoffs)

        #Define descritpor
        desc = descriptors.Descriptor(self.descriptor_options)

        #Define structure as quippy Atoms object
        filename = str(atoms.info['label']) + '.xyz'
        ase_write(filename, atoms, format='xyz')
        struct = quippy_Atoms(filename)
        struct.set_pbc(self.p_b_c)

        #Remove redundant files that have been created
        if os.path.exists(filename):
            os.remove(filename)
        if os.path.exists(filename + '.idx'):
            os.remove(filename + '.idx')

        #Compute SOAP descriptor
        struct.set_cutoff(desc.cutoff())
        struct.calc_connect()
        SOAP_descriptor = desc.calc(struct)['descriptor']

        if self.average_over_permuations:
            #average over different orders
            SOAP_proto_averaged = np.zeros(SOAP_descriptor.size)
            SOAP_proto_copy = SOAP_descriptor
            for i in range(self.number_averages):
                np.random.shuffle(SOAP_proto_copy)
                SOAP_proto_averaged = np.add(SOAP_proto_averaged,
                                             SOAP_proto_copy.flatten())
            SOAP_proto_averaged = np.array(
                [x / float(self.number_averages) for x in SOAP_proto_averaged])
            SOAP_descriptor = SOAP_proto_averaged

        if self.average:
            SOAP_descriptor = SOAP_descriptor.flatten(
            )  # if get averaged LAE, then default output shape is (1,316), hence flatten()

        descriptor_data = dict(descriptor_name=self.name,
                               descriptor_info=str(self),
                               SOAP_descriptor=SOAP_descriptor)

        structure.info['descriptor'] = descriptor_data

        return structure
コード例 #8
0
    def write(self, outfile: Union[bytes, str]):
        """
        Writes BaseDataContainer object to file.

        Parameters
        ----------
        outfile
            file to which to write
        """
        self._metadata['date_last_backup'] = datetime.now().strftime(
            '%Y-%m-%dT%H:%M:%S')

        # Save reference atomic structure
        reference_structure_file = tempfile.NamedTemporaryFile()
        ase_write(reference_structure_file.name, self.structure, format='json')

        # Save reference data
        data_container_type = str(self.__class__).split('.')[-1].replace(
            "'>", '')
        reference_data = {
            'parameters': self._ensemble_parameters,
            'metadata': self._metadata,
            'last_state': self._last_state,
            'data_container_type': data_container_type
        }

        reference_data_file = tempfile.NamedTemporaryFile()
        with open(reference_data_file.name, 'w') as fileobj:
            json.dump(reference_data, fileobj, cls=Int64Encoder)

        # Save runtime data
        runtime_data_file = tempfile.NamedTemporaryFile()
        np.savez_compressed(runtime_data_file, self._data_list)

        # Write temporary tar file
        with tempfile.NamedTemporaryFile('wb', delete=False) as f:
            with tarfile.open(fileobj=f, mode='w') as handle:
                handle.add(reference_data_file.name, arcname='reference_data')
                handle.add(reference_structure_file.name, arcname='atoms')
                handle.add(runtime_data_file.name, arcname='runtime_data')

        # Copy to permanent location
        file_name = f.name
        f.close()  # Required for Windows
        shutil.copy(file_name, outfile)
        os.remove(file_name)
        runtime_data_file.close()
コード例 #9
0
ファイル: utils.py プロジェクト: devonwa/twodee
def write_image(path, data, options=None):
    #file_path = './img/' + path
    file_path = path
    directory = file_path[:file_path.rfind('/')]
    if not os.path.exists(directory):
        os.makedirs(directory)

    if isinstance(data, ModuleType):
        if data.__name__ == "matplotlib.pyplot":
            data.savefig(file_path)
    elif isinstance(data, Atoms):
        #file_path += '.png'
        ase_write(file_path, data)

    else:
        print("No functionality for type = {}".format(type(data)))

    return '[[' + file_path + ']]'
コード例 #10
0
 def write(self):
     if os.path.exists(self.fn) and not self.opts.overwrite:
         self.logger.error('Not overwriting %s' % self.fn)
     else:
         self.logger.info('Writing to: %s' % self.fn)
         with open(self.fn, 'w') as fh:
             self._writehead(fh)
             self._writezmat(fh)
             self._writetail(fh)
         if self.opts.writeelectrodes:
             self.writeelectrodes()
     if self.opts.png:
         self.logger.info('Writing %s.png' % self.jobname)
         try:
             # pass
             ase_write('%s.png' % self.jobname,
                       self.parser.zmat,
                       rotation='90y')
         except ValueError as msg:
             self.logger.warn("Error writing png file: %s" % str(msg))
         except TypeError as msg:
             self.logger.warn("Error writing png file %s" % str(msg))
         except ImportError as msg:
             self.logger.error("Error importing _png module %s", str(msg))
コード例 #11
0
ファイル: ase.py プロジェクト: plin1112/IPMOF
def write(file_path, ase_atoms, file_format=None):
    ase_write(file_path, ase_atoms, format=file_format)
コード例 #12
0
 def write_poscar(self, oposcar, oformat="vasp"):
     ase_write(oposcar, self.internal_geometry,
               format=oformat)
コード例 #13
0
ファイル: surface.py プロジェクト: krim4ik/Organisms
from ase.build import fcc111
from ase.io import write as ase_write
from ase.visualize import view

symbol = 'Au'
size = (10, 10, 3)
surface = fcc111(symbol,
                 size,
                 a=None,
                 vacuum=10.0,
                 orthogonal=True,
                 periodic=False)
surface.center()
view(surface)
ase_write('surface.xyz', surface)