Example #1
0
class VoronoiAnalyzerTest(PymatgenTest):
    _multiprocess_shared_ = True

    def setUp(self):
        self.ss = Xdatcar(
            os.path.join(PymatgenTest.TEST_FILES_DIR, "XDATCAR.MD")).structures
        self.s = self.ss[1]
        self.va = VoronoiAnalyzer(cutoff=4.0)

    def test_analyze(self):
        # Check for the Voronoi index of site i in Structure
        single_structure = self.va.analyze(self.s, n=5)
        self.assertIn(
            single_structure.view(),
            np.array([4, 3, 3, 4, 2, 2, 1, 0]).view(),
            "Cannot find the right polyhedron.",
        )
        # Check for the presence of a Voronoi index and its frequency in
        # a ensemble (list) of Structures
        ensemble = self.va.analyze_structures(self.ss,
                                              step_freq=2,
                                              most_frequent_polyhedra=10)
        self.assertIn(
            ("[1 3 4 7 1 0 0 0]", 3),
            ensemble,
            "Cannot find the right polyhedron in ensemble.",
        )
Example #2
0
 def __init__(self, cutoff=6.0):
     """
     Args:
         cutoff (float): cutoff distance in determining the potential
             neighbors for Voronoi tessellation analysis
     """
     self.cutoff = cutoff
     self.voronoi_analyzer = VoronoiAnalyzer(cutoff=self.cutoff)
Example #3
0
class VoronoiIndex(BaseFeaturizer):
    """
    The Voronoi indices n_i and the fractional Voronoi indices n_i/sum(n_i) that
    reflects the i-fold symmetry in the local sites.
    n_i denotes the number of the i-edged faces, and i is in the range of 3-10 here.
    e.g. for bcc lattice, the Voronoi indices are [0,6,0,8,0,0...]
         for fcc/hcp lattice, the Voronoi indices are [0,12,0,0,...]
         for icosahedra, the Voronoi indices are [0,0,12,0,...]
    """
    def __init__(self, cutoff=6.0):
        """
        Args:
            cutoff (float): cutoff distance in determining the potential
                neighbors for Voronoi tessellation analysis
        """
        self.cutoff = cutoff
        self.voronoi_analyzer = VoronoiAnalyzer(cutoff=self.cutoff)

    def featurize(self, struct, idx):
        """
        Args:
            struct (Structure): Pymatgen Structure object.
            idx (int): index of target site in structure.
        Returns:
            list including Voronoi indices, sum of Voronoi indices, and
            fractional Voronoi indices
        """

        voro_index_result = []
        voro_index_list = self.voronoi_analyzer.analyze(struct, n=idx)
        for voro_index in voro_index_list:
            voro_index_result.append(voro_index)
        voro_index_sum = sum(voro_index_list)
        voro_index_result.append(voro_index_sum)

        voro_index_frac_list = voro_index_list / voro_index_sum
        for voro_index_frac in voro_index_frac_list:
            voro_index_result.append(voro_index_frac)

        return voro_index_result

    def feature_labels(self):
        labels = []
        for i in range(3, 11):
            labels.append('voro_index_%d' % i)
        labels.append('voro_index_sum')
        for i in range(3, 11):
            labels.append('voro_index_frac_%d' % i)
        return labels

    def citations(self):
        citation = ('@book{okabe1992spatial,  '
                    'title={Spatial tessellations}, '
                    'author={Okabe, Atsuyuki}, '
                    'year={1992}, '
                    'publisher={Wiley Online Library}}')
        return citation

    def implementors(self):
        return ['Qi Wang']
class VoronoiAnalyzerTest(PymatgenTest):

    def setUp(self):
        self.ss = Xdatcar(os.path.join(test_dir, 'XDATCAR.MD')).structures
        self.s = self.ss[1]
        self.va = VoronoiAnalyzer(cutoff=4.0)

    def test_analyze(self):
        # Check for the Voronoi index of site i in Structure
        single_structure = self.va.analyze(self.s, n=5)
        self.assertIn(single_structure.view(),
                      np.array([4, 3, 3, 4, 2, 2, 1, 0]).view(),
                      "Cannot find the right polyhedron.")
        # Check for the presence of a Voronoi index and its frequency in
        # a ensemble (list) of Structures
        ensemble = self.va.analyze_structures(self.ss, step_freq=2,
                                              most_frequent_polyhedra=10)
        self.assertIn(('[1 3 4 7 1 0 0 0]', 3),
                      ensemble, "Cannot find the right polyhedron in ensemble.")
class VoronoiAnalyzerTest(PymatgenTest):

    def setUp(self):
        self.ss = Xdatcar(os.path.join(test_dir, 'XDATCAR.MD')).structures
        self.s = self.ss[19]
        self.va = VoronoiAnalyzer(cutoff=4.0)

    def test_analyze(self):
        # Check for the Voronoi index of site i in Structure
        single_structure = self.va.analyze(self.s, n=5)
        self.assertIn(single_structure.view(),
                      np.array([5, 4, 2, 5, 3, 1, 0, 2]).view(),
                      "Cannot find the right polyhedron.")
        # Check for the presence of a Voronoi index and its frequency in
        # a ensemble (list) of Structures
        ensemble = self.va.analyze_structures(self.ss, step_freq=2,
                                              most_frequent_polyhedra=10)
        self.assertIn(('[2 3 3 3 1 1 0 0]', 6),
                      ensemble, "Cannot find the right polyhedron in ensemble.")
Example #6
0
    def featurize(self, struct, site):
        """
        :param struct: Pymatgen Structure object
        :param site: index of target site in structure
        :return: voro_index: Voronoi indices
                 voro_index_sum: sum of Voronoi indices
                 voro_index_frac: fractional Voronoi indices
        """

        voro_index_result = []
        self.voronoi_analyzer = VoronoiAnalyzer(cutoff=self.cutoff)
        voro_index_list = self.voronoi_analyzer.analyze(struct, n=site)
        for voro_index in voro_index_list:
            voro_index_result.append(voro_index)
        voro_index_sum = sum(voro_index_list)
        voro_index_result.append(voro_index_sum)

        voro_index_frac_list = voro_index_list / voro_index_sum
        for voro_index_frac in voro_index_frac_list:
            voro_index_result.append(voro_index_frac)

        return voro_index_result
Example #7
0
 def setUp(self):
     self.ss = Xdatcar(os.path.join(test_dir, 'XDATCAR.MD')).structures
     self.s = self.ss[1]
     self.va = VoronoiAnalyzer(cutoff=4.0)
 def setUp(self):
     self.ss = Xdatcar(os.path.join(test_dir, 'XDATCAR.MD')).structures
     self.s = self.ss[1]
     self.va = VoronoiAnalyzer(cutoff=4.0)
      spacegroup1.get_space_group_symbol())
print('space group number of structure1:',
      spacegroup1.get_space_group_number())
print('space group symbol of structure2:',
      spacegroup2.get_space_group_symbol())
print('space group number of structure2:',
      spacegroup2.get_space_group_number())
Voronoi = VoronoiCoordFinder(s2, target=None)
site = s2.num_sites
#print("s2[0]:",s2.sites)
print("s2_cart_coords[0]", s2.cart_coords[0])
#print("s2_distance_(0,1)",s2.get_distance(0,1))
polyhedra = Voronoi.get_voronoi_polyhedra(1)
coordinate = Voronoi.get_coordination_number(1)
coordinate_sites = Voronoi.get_coordinated_sites(1)
Voronoi_Analyzer = VoronoiAnalyzer()
anay = Voronoi_Analyzer.analyze(s1, n=0)
strucs = [s1, s2]
anays = Voronoi_Analyzer.analyze_structures(strucs)
print("Voronoi_Analyzer.analyze(s1,n=0):", anay)
#plt = Voronoi_Analyzer.plot_vor_analysis(anays)
relax = RelaxationAnalyzer(s1, s2)
volume_change = relax.get_percentage_volume_change()
lattice_parameter_changes = relax.get_percentage_lattice_parameter_changes()
print('initial volume:', s1.volume)
print('final volume:', s2.volume)
print("percent_volume_change:", volume_change)
print("percent_lattice_change:", lattice_parameter_changes)
bond_dist = relax.get_percentage_bond_dist_changes(max_radius=6)
print("percent_bond_distance_change:", bond_dist)
connec = VoronoiConnectivity(s2)
Example #10
0
def list_number_of_facets_with_i_vertices(list_struc):
    return [
        VoronoiAnalyzer().analyze(structure, n=0) for structure in list_struc
    ]
Example #11
0
    def run_task(self, fw_spec):

        # Get
        data_dir = self.get('data_dir')
        calc_rdf = self.get('calc_rdf', True)
        calc_bad = self.get('calc_bad', True)
        calc_voronoi = self.get('calc_voronoi', False)
        calc_cage = self.get('calc_cage', True)
        calc_pmf = self.get('calc_pmf', False)
        calc_connectivity = self.get('calc_connectivity', False)

        ionic_steps = []
        for root, dirs, files in os.walk(data_dir):
            for f in files:
                if 'ionic_steps' in f:
                    name, ext = os.path.splitext(f)
                    if ext in ('.gz', '.GZ', '.Z'):
                        with gzip.open(f, "rb") as gzipped:
                            d = json.loads(gzipped.read().decode("ascii"))
                    else:
                        d = loadfn(f)
                    ionic_steps.extend(d)

        structures = [step['structure'] for step in ionic_steps]

        data_dict = {}

        if calc_rdf:
            logger.info("LOGGER: Calculating radial distribution functions...")
            rdf = RadialDistributionFunction(structures=structures)
            rdf.get_radial_distribution_functions(nproc=4)
            cns = rdf.get_coordination_numbers()
            fs = rdf.first_coordination_shell_radius
            data_dict.update({'radial_distribution_functions': rdf.as_dict()})
            data_dict.update({'coordination_numbers': cns})

            if calc_cage:
                logger.info("LOGGER: Calculating cage correlation function...")
                ccf = CageCorrelationFunction(structures, fs)
                ccf.get_cage_correlation_function()
                # TODO: Make sure the CCFs work

            if calc_pmf:
                logger.info(
                    "LOGGER: Calculating the potential of mean force...")
                # TODO: Need to include the implementation of PMF here

        if calc_bad:
            logger.info(
                "LOGGER: Calculating bond angle distribution functions...")
            bad = BondAngleDistribution(structures=structures)
            bad.get_bond_angle_distribution(nproc=4)
            data_dict.update(
                {'bond_angle_distribution_functions': bad.as_dict()})

        if calc_voronoi:
            logger.info("LOGGER: Performing voronoi analysis...")
            va = VoronoiAnalyzer(structures)
            try:
                poly = va.analyze_structures()
                data_dict.update({'voronoi_polyhedra': poly})
            except MemoryError:
                logger.info(
                    "ERROR: Voronoi analysis failed due to insufficient memory..."
                )

        if calc_connectivity:
            logger.info(
                "LOGGER: Getting the connectivity motif distribution functions..."
            )
            # TODO: Implement after writing connectivity function

        # write structural analysis results to json file and then zip it
        write_dir = os.path.join(os.getcwd(), 'structural_analysis')
        os.mkdir(write_dir)
        for k, v in data_dict.items():
            dumpfn(v, os.path.join(write_dir, '{}.json').format(k))
        gzip_dir(write_dir)

        return FWAction()
Example #12
0
 def setUp(self):
     self.ss = Xdatcar(
         os.path.join(PymatgenTest.TEST_FILES_DIR, "XDATCAR.MD")).structures
     self.s = self.ss[1]
     self.va = VoronoiAnalyzer(cutoff=4.0)