Esempio n. 1
0
    def set_from_pymatgen(self,
                          structure,
                          k0,
                          k0p,
                          file=None,
                          name='',
                          version=4,
                          comments='',
                          thermal_expansion=0.,
                          two_theta_range=(0., 40.)):
        """
        set parameters from pymatgen outputs

        Parameters
        ----------
        structure = pymatgen structure object
        k0 = bulk modulus
        k0p = pressure derivative of bulk modulus
        file = file name (optional)
        name = name (optional)
        version = version (optional)
        comments = comments (optional)
        thermal_expansion = 0 (optional)

        Returns
        -------

        """
        lattice = structure.lattice
        self.k0 = k0
        self.k0p = k0p
        self.a0 = lattice.a
        self.b0 = lattice.b
        self.c0 = lattice.c
        self.alpha0 = lattice.alpha
        self.beta0 = lattice.beta
        self.gamma0 = lattice.gamma
        self.symmetry = SpacegroupAnalyzer(structure).get_crystal_system()
        self.file = file
        self.name = name
        self.version = version
        self.comments = comments
        self.thermal_expansion = thermal_expansion
        self.v0 = cal_UnitCellVolume(self.symmetry, self.a0, self.b0, self.c0,
                                     self.alpha0, self.beta0, self.gamma0)
        c = XRDCalculator(wavelength=0.3344)
        pattern = c.get_xrd_data(structure, two_theta_range=two_theta_range)
        DiffLines = []
        for line in pattern:
            hkl_key = line[2].keys()
            hkl_txt = str(hkl_key)[12:-3].split(",")
            d_line = DiffractionLine()
            d_line.dsp0 = line[3]
            d_line.dsp = line[3]
            d_line.intensity = line[1]
            d_line.h = int(hkl_txt[0])
            d_line.k = int(hkl_txt[1])
            d_line.l = int(hkl_txt[-1])
            DiffLines.append(d_line)
        self.DiffLines = DiffLines
Esempio n. 2
0
        def pattern_from_mpid_or_struct(rad_source, mp_time, struct_time, mpid, struct):

            if (struct_time is None) or (mp_time is None):
                raise PreventUpdate

            if struct_time > mp_time:
                if struct is None:
                    raise PreventUpdate
                sga = SpacegroupAnalyzer(self.from_data(struct))
                struct = (
                    sga.get_conventional_standard_structure()
                )  # always get conventional structure
            elif mp_time >= struct_time:
                if mpid is None:
                    raise PreventUpdate
                mpid = mpid["mpid"]

                with MPRester() as mpr:
                    struct = mpr.get_structure_by_material_id(
                        mpid, conventional_unit_cell=True
                    )
            xrdc = XRDCalculator(wavelength=rad_source)
            data = xrdc.get_pattern(struct, two_theta_range=None)

            return data.as_dict()
Esempio n. 3
0
    def test_get_xrd_data(self):
        a = 4.209
        latt = Lattice.cubic(a)
        structure = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]])
        c = XRDCalculator()
        data = c.get_xrd_data(structure, two_theta_range=(0, 90))
        #Check the first two peaks
        self.assertAlmostEqual(data[0][0], 21.107738329639844)
        self.assertAlmostEqual(data[0][1], 36.483184003748946)
        self.assertEqual(data[0][2], {(1, 0, 0): 6})
        self.assertAlmostEqual(data[0][3], 4.2089999999999996)
        self.assertAlmostEqual(data[1][0], 30.024695921112777)
        self.assertAlmostEqual(data[1][1], 100)
        self.assertEqual(data[1][2], {(1, 1, 0): 12})
        self.assertAlmostEqual(data[1][3], 2.976212442014178)

        s = read_structure(os.path.join(test_dir, "LiFePO4.cif"))
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[1][0], 17.03504233621785)
        self.assertAlmostEqual(data[1][1], 50.400928948337075)

        s = read_structure(os.path.join(test_dir, "Li10GeP2S12.cif"))
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[1][0], 14.058274883353876)
        self.assertAlmostEqual(data[1][1], 4.4111123641667671)

        # Test a hexagonal structure.
        s = read_structure(os.path.join(test_dir, "Graphite.cif"),
                           primitive=False)
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[0][0], 7.929279053132362)
        self.assertAlmostEqual(data[0][1], 100)
        self.assertAlmostEqual(len(list(data[0][2].keys())[0]), 4)

        #Add test case with different lengths of coefficients.
        #Also test d_hkl.
        coords = [[0.25, 0.25, 0.173], [0.75, 0.75, 0.827], [0.75, 0.25, 0],
                  [0.25, 0.75, 0], [0.25, 0.25, 0.676], [0.75, 0.75, 0.324]]
        sp = ["Si", "Si", "Ru", "Ru", "Pr", "Pr"]
        s = Structure(Lattice.tetragonal(4.192, 6.88), sp, coords)
        data = c.get_xrd_data(s)
        self.assertAlmostEqual(data[0][0], 12.86727341476735)
        self.assertAlmostEqual(data[0][1], 31.448239816769796)
        self.assertAlmostEqual(data[0][3], 6.88)
        self.assertEqual(len(data), 42)
        data = c.get_xrd_data(s, two_theta_range=[0, 60])
        self.assertEqual(len(data), 18)

        #Test with and without Debye-Waller factor
        tungsten = Structure(Lattice.cubic(3.1653), ["W"] * 2,
                             [[0, 0, 0], [0.5, 0.5, 0.5]])
        data = c.get_xrd_data(tungsten, scaled=False)
        self.assertAlmostEqual(data[0][0], 40.294828554672264)
        self.assertAlmostEqual(data[0][1], 2414237.5633093244)
        self.assertAlmostEqual(data[0][3], 2.2382050944897789)
        c = XRDCalculator(debye_waller_factors={"W": 0.1526})
        data = c.get_xrd_data(tungsten, scaled=False)
        self.assertAlmostEqual(data[0][0], 40.294828554672264)
        self.assertAlmostEqual(data[0][1], 2377745.2296686019)
        self.assertAlmostEqual(data[0][3], 2.2382050944897789)
Esempio n. 4
0
def generate_diffraction_plot(args):
    s = Structure.from_file(args.filenames[0])
    c = XRDCalculator()
    if args.outfile:
        c.get_xrd_plot(s).savefig(args.outfile[0])
    else:
        c.show_xrd_plot(s)
Esempio n. 5
0
 def get_interplanar_spacing(self, structure, surface):
     xc = XRDCalculator()
     xrd_data = xc.get_xrd_data(structure)
     logging.info("xrd_data: {}".format(xrd_data))
     sort_data = pd.DataFrame(
         xrd_data,
         columns=["two_theta", "intensity", "miller_index_dict", "d_hkl"])
     matcher = (1, 1, 1)
     logging.info("sort_data: {}".format(sort_data))
     flag = 0
     for mid in sort_data.miller_index_dict:
         logging.info("mid: {}".format(mid))
         for key, value in mid.items():
             key = reduce_vector(key)
             if (surface == key):
                 matcher = mid
                 flag = 1
                 break
             else:
                 logging.info("*" * 50)
                 logging.info("key: {}".format(key))
                 logging.info("value {}".format(value))
                 logging.info("*" * 50)
         if flag == 1:
             break
     spacing = sort_data[sort_data.miller_index_dict ==
                         matcher].d_hkl.values[0]
     return spacing
Esempio n. 6
0
def abicomp_xrd(options):
    """
    Compare X-ray diffraction plots (requires FILES with structure).
    """
    if len(options.paths) < 2:
        print("You need more than one structure to compare!")
        return 1

    structures = [abilab.Structure.from_file(p) for p in options.paths]

    dfs = abilab.dataframes_from_structures(
        structures, index=[os.path.relpath(p) for p in options.paths])
    abilab.print_dataframe(dfs.lattice, title="Lattice parameters:")
    if options.verbose:
        abilab.print_dataframe(
            dfs.coords,
            title="Atomic positions (columns give the site index):")

    from pymatgen.analysis.diffraction.xrd import XRDCalculator
    two_theta_range = tuple(float(t) for t in options.two_theta_range)
    xrd = XRDCalculator(wavelength=options.wavelength, symprec=options.symprec)
    xrd.plot_structures(structures,
                        two_theta_range=two_theta_range,
                        fontsize=6,
                        annotate_peaks=not options.no_annotate_peaks,
                        tight_layout=True)
    return 0
Esempio n. 7
0
    def from_structure(  # type: ignore[override]
        cls,
        material_id: Union[MPID, int],
        spectrum_id: str,
        structure: Structure,
        wavelength: float,
        min_two_theta=0,
        max_two_theta=180,
        symprec=0.1,
        **kwargs,
    ) -> "XRDDoc":
        calc = XRDCalculator(wavelength=wavelength, symprec=symprec)
        pattern = calc.get_pattern(
            structure, two_theta_range=(min_two_theta, max_two_theta)
        )

        return super().from_structure(
            material_id=material_id,
            spectrum_id=spectrum_id,
            structure=structure,
            spectrum=pattern,
            wavelength=wavelength,
            min_two_theta=min_two_theta,
            max_two_theta=max_two_theta,
            **kwargs,
        )
Esempio n. 8
0
    def test_get_pattern(self):
        s = self.get_structure("CsCl")
        c = XRDCalculator()
        xrd = c.get_pattern(s, two_theta_range=(0, 90))
        self.assertTrue(xrd.to_json())  # Test MSONAble property
        # Check the first two peaks
        self.assertAlmostEqual(xrd.x[0], 21.107738329639844)
        self.assertAlmostEqual(xrd.y[0], 36.483184003748946)
        self.assertEqual(xrd.hkls[0], [{'hkl': (1, 0, 0), 'multiplicity': 6}])
        self.assertAlmostEqual(xrd.d_hkls[0], 4.2089999999999996)
        self.assertAlmostEqual(xrd.x[1], 30.024695921112777)
        self.assertAlmostEqual(xrd.y[1], 100)
        self.assertEqual(xrd.hkls[1], [{"hkl": (1, 1, 0), "multiplicity": 12}])
        self.assertAlmostEqual(xrd.d_hkls[1], 2.976212442014178)

        s = self.get_structure("LiFePO4")
        xrd = c.get_pattern(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(xrd.x[1], 17.03504233621785)
        self.assertAlmostEqual(xrd.y[1], 50.400928948337075)

        s = self.get_structure("Li10GeP2S12")
        xrd = c.get_pattern(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(xrd.x[1], 14.058274883353876)
        self.assertAlmostEqual(xrd.y[1], 4.4111123641667671)

        # Test a hexagonal structure.
        s = self.get_structure("Graphite")

        xrd = c.get_pattern(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(xrd.x[0], 26.21057350859598)
        self.assertAlmostEqual(xrd.y[0], 100)
        self.assertAlmostEqual(len(xrd.hkls[0][0]["hkl"]), 4)

        # Add test case with different lengths of coefficients.
        # Also test d_hkl.
        coords = [[0.25, 0.25, 0.173], [0.75, 0.75, 0.827], [0.75, 0.25, 0],
                  [0.25, 0.75, 0], [0.25, 0.25, 0.676], [0.75, 0.75, 0.324]]
        sp = ["Si", "Si", "Ru", "Ru", "Pr", "Pr"]
        s = Structure(Lattice.tetragonal(4.192, 6.88), sp, coords)
        xrd = c.get_pattern(s)
        self.assertAlmostEqual(xrd.x[0], 12.86727341476735)
        self.assertAlmostEqual(xrd.y[0], 31.448239816769796)
        self.assertAlmostEqual(xrd.d_hkls[0], 6.88)
        self.assertEqual(len(xrd), 42)
        xrd = c.get_pattern(s, two_theta_range=[0, 60])
        self.assertEqual(len(xrd), 18)

        # Test with and without Debye-Waller factor
        tungsten = Structure(Lattice.cubic(3.1653), ["W"] * 2,
                             [[0, 0, 0], [0.5, 0.5, 0.5]])
        xrd = c.get_pattern(tungsten, scaled=False)
        self.assertAlmostEqual(xrd.x[0], 40.294828554672264)
        self.assertAlmostEqual(xrd.y[0], 2414237.5633093244)
        self.assertAlmostEqual(xrd.d_hkls[0], 2.2382050944897789)
        c = XRDCalculator(debye_waller_factors={"W": 0.1526})
        xrd = c.get_pattern(tungsten, scaled=False)
        self.assertAlmostEqual(xrd.x[0], 40.294828554672264)
        self.assertAlmostEqual(xrd.y[0], 2377745.2296686019)
        self.assertAlmostEqual(xrd.d_hkls[0], 2.2382050944897789)
Esempio n. 9
0
def get_xrd_plot(args):
    """
    Plot XRD

    Args:
        args (dict): Args from argparse
    """
    s = Structure.from_file(args.xrd_structure_file)
    c = XRDCalculator()
    return c.get_plot(s)
Esempio n. 10
0
    def calculate(self, structure, show=False):

        c = XRDCalculator(wavelength=self.wavelength)
        xrd_pattern = c.get_xrd_pattern(AseAtomsAdaptor.get_structure(structure))

        if show:
            c.show_xrd_plot(AseAtomsAdaptor.get_structure(structure))

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

        structure.info['descriptor'] = descriptor_data

        return structure
Esempio n. 11
0
 def xrd(self, ):
     import os
     os.chdir(r"D:\Desktop\VASP practical\workdir")
     from pymatgen import Lattice, Structure
     from pymatgen.analysis.diffraction.xrd import XRDCalculator
     from IPython.display import Image, display
     from pymatgen.ext.matproj import MPRester
     mpr = MPRester()
     mp_id = self.mp_id
     structure = mpr.get_structure_by_material_id(mp_id)
     c = XRDCalculator()
     print(c)
     c.show_plot(structure)
     print(os.getcwd())
Esempio n. 12
0
    def get_xrd_from_struct(self, structure):
        doc = {}

        for xs in self.__settings:
            xrdcalc = XRDCalculator(wavelength="".join([xs['target'], xs['edge']]),
                                    symprec=xs.get('symprec', 0))

            pattern = jsanitize(xrdcalc.get_xrd_pattern(
                structure, two_theta_range=xs['two_theta']).as_dict())
            # TODO: Make sure this is what the website actually needs
            d = {'wavelength': {'element': xs['target'],
                                'in_angstroms': WAVELENGTHS["".join([xs['target'], xs['edge']])]},
                 'pattern': pattern}
            doc[xs['target']] = d
        return doc
Esempio n. 13
0
    def get_xrd_from_struct(self, structure):
        doc = {}

        for xs in self.__xrd_settings:
            xrdcalc = XRDCalculator(wavelength="".join([xs['target'], xs['edge']]),
                                    symprec=xs.get('symprec', 0))

            pattern = [[float(p[1]), [int(x) for x in list(p[2])[0]], p[0], float(p[3])] for p in
                       xrdcalc.get_xrd_data(structure, two_theta_range=xs['two_theta'])]
            # TODO: Make sure this is what the website actually needs
            d = {'wavelength': {'element': xs['target'],
                                'in_angstroms': WAVELENGTHS["".join([xs['target'], xs['edge']])]},
                 'meta': ['amplitude', 'hkl', 'two_theta', 'd_spacing'],
                 'pattern': pattern}
            doc[xs['target']] = d
        return doc
Esempio n. 14
0
        def pattern_from_struct(struct, xrdcalculator_kwargs):

            if struct is None:
                raise PreventUpdate

            struct = self.from_data(struct)
            xrdcalculator_kwargs = self.from_data(xrdcalculator_kwargs)

            sga = SpacegroupAnalyzer(struct)
            struct = (
                sga.get_conventional_standard_structure()
            )  # always get conventional structure

            xrdc = XRDCalculator(**xrdcalculator_kwargs)
            data = xrdc.get_pattern(struct, two_theta_range=None)

            return data.as_dict()
Esempio n. 15
0
def get_xrd():
    struct = readstructure()
    xrd = XRDCalculator()

    #    xrd_data=xrd.get_xrd_pattern(struct)
    xrd_data = xrd.get_pattern(struct)
    jxrd_data = jsanitize(xrd_data.as_dict())
    fname = 'XRD.json'
    proc_str = "Saving data to " + fname + " File ..."
    procs(proc_str, 1, sp='-->>')
    json_store(jxrd_data, fname)

    data = np.vstack((xrd_data.x, xrd_data.y)).T

    margin = 10.
    ds = xrd_data.x[0] - margin
    de = xrd_data.x[-1] + margin
    tmp_data = [ds] + xrd_data.x.tolist() + [de]
    tmp_data1 = np.diff(tmp_data).tolist()
    tmp_data2 = np.array([0] + np.cumsum(tmp_data1).tolist())
    tmp_data3 = tmp_data2 / tmp_data2[-1]
    x_data = np.linspace(ds, de, 10000)
    y_data = np.zeros((len(x_data)))
    for i in range(1, len(tmp_data3) - 1):
        index = int(tmp_data3[i] * 10000)
        y_data[index] = xrd_data.y[i - 1]

    data = np.vstack((x_data, y_data))
    data = (smear(data, sigma=0.1)).T

    head_line = "#%(key1)+12s %(key2)+12s" % {
        'key1': '2theta',
        'key2': 'Intensity'
    }
    fname = 'XRD.dat'
    proc_str = "Saving data to " + fname + " File ..."
    procs(proc_str, 2, sp='-->>')
    write_col_data(fname, data, head_line)

    check_matplotlib()
    fname = 'XRD.png'
    proc_str = "Saving plot to " + fname + " File ..."
    procs(proc_str, 3, sp='-->>')
    plt = xrd.get_plot(struct)
    plt.savefig(fname, format='png')
Esempio n. 16
0
        def pattern_from_struct(struct, rad_source):

            if struct is None or not rad_source:
                raise PreventUpdate

            struct = self.from_data(struct)
            rad_source = self.reconstruct_kwarg_from_state(
                callback_context.inputs, "rad_source")

            sga = SpacegroupAnalyzer(struct)
            struct = (sga.get_conventional_standard_structure()
                      )  # always get conventional structure

            xrdc = XRDCalculator(wavelength=WAVELENGTHS[rad_source],
                                 symprec=0,
                                 debye_waller_factors=None)
            data = xrdc.get_pattern(struct, two_theta_range=None)

            return data.as_dict()
Esempio n. 17
0
def calculate_xrd(request):
    results = {}
    xrd = XRDCalculator(symprec=0.01)
    for name, f in request.FILES.items():
        name, s = get_structure(f)
        plt = xrd.get_xrd_plot(s, annotate_peaks=False)
        fig = plt.gcf()
        fig.set_dpi(100)
        fig.set_size_inches(8, 6)
        ax = plt.gca()
        plt.setp(ax.get_xticklabels(), fontsize=16)
        plt.setp(ax.get_yticklabels(), fontsize=16)
        ax.xaxis.label.set_size(16)
        ax.yaxis.label.set_size(16)

        si = StringIO()
        plt.savefig(si, format="svg")
        results[name] = si.getvalue()
    return results
Esempio n. 18
0
def abicomp_xrd(options):
    """
    Compare X-ray diffraction plots (requires FILES with structure).
    """
    if len(options.paths) < 2:
        print("You need more than one structure to compare!")
        return 1

    structures = [abilab.Structure.from_file(p) for p in options.paths]

    dfs = abilab.dataframes_from_structures(structures, index=[os.path.relpath(p) for p in options.paths])
    abilab.print_dataframe(dfs.lattice, title="Lattice parameters:")
    if options.verbose:
        abilab.print_dataframe(dfs.coords, title="Atomic positions (columns give the site index):")

    from pymatgen.analysis.diffraction.xrd import XRDCalculator
    two_theta_range = tuple(float(t) for t in options.two_theta_range)
    xrd = XRDCalculator(wavelength=options.wavelength, symprec=options.symprec)
    xrd.plot_structures(structures, two_theta_range=two_theta_range, fontsize=6,
                        annotate_peaks=not options.no_annotate_peaks, tight_layout=True)
    return 0
Esempio n. 19
0
    def __init__(self, two_theta_range=(0, 127), bw_method=0.05,
                 pattern_length=None, **kwargs):
        """
        Initialize the featurizer.

        Args:
            two_theta_range ([float of length 2]): Tuple for range of
                two_thetas to calculate in degrees. Defaults to (0, 90). Set to
                None if you want all diffracted beams within the limiting
                sphere of radius 2 / wavelength.
            bw_method (float): how much to smear the XRD pattern
            pattern_length (float): length of final array; defaults to one value
             per degree (i.e. two_theta_range + 1)
            **kwargs: any other arguments to pass into pymatgen's XRDCalculator,
                such as the type of radiation.
        """
        self.two_theta_range = two_theta_range
        self.bw_method = bw_method
        self.pattern_length = pattern_length or two_theta_range[1] - \
                              two_theta_range[0] + 1
        self.xrd_calc = XRDCalculator(**kwargs)
Esempio n. 20
0
def generate_diffraction_plot(args):
    s = Structure.from_file(args.filenames[0])
    c = XRDCalculator()
    if args.outfile:
        c.get_xrd_plot(s).savefig(args.outfile[0])
    else:
        c.show_xrd_plot(s)
Esempio n. 21
0
def get_kinematic_reflection(unit_cell, top=3):
    """
    Find top hkl and d_hkl with highest intensity.
    """
    xrd = XRDCalculator().get_pattern(unit_cell)
    hkls = np.array([itm[0]['hkl'] for itm in xrd.hkls])
    intens = xrd.y
    if top > intens.size:
        top = intens.size
    top_ind = np.argsort(intens)[::-1][:top]
    hkl_vecs = hkls[top_ind]
    d_hkls = np.array(xrd.d_hkls)[top_ind]
    return hkl_vecs, d_hkls
Esempio n. 22
0
    def xrd(self, ):
        import os
        from pymatgen import Lattice, Structure
        from pymatgen.analysis.diffraction.xrd import XRDCalculator
        from IPython.display import Image, display
        from pymatgen import Structure, Lattice, MPRester, Molecule
        ass = self.cif_route
        print(ass)
        # os.chdir(r"D:\Desktop\VASP practical\Input")
        # print (os.getcwd())

        # Note that you must provide your own API Key, which can
        # be accessed via the Dashboard at materialsproject.org
        #mpr = MPRester()#密钥
        molecule = Molecule.from_file(ass)
        structure = molecule.get_boxed_structure(self.a, self.b, self.c)
        print(structure)
        os.chdir(r"D:\Desktop\VASP practical\Input")
        print(os.getcwd())
        c = XRDCalculator()
        c.show_plot(structure)

        print(os.getcwd())
Esempio n. 23
0
def xrd(pymat_struct,
        descriptor_size=300,
        two_theta_min=0.0,
        two_theta_max=90.0):
    """construct XRD descriptor"""
    # get values from XRD
    two_theta = np.array(XRDCalculator().get_xrd_pattern(pymat_struct).x)
    intensity = np.array(XRDCalculator().get_xrd_pattern(pymat_struct).y)

    # create & digitize bins, include the right bourndary only (zeroth bin is designated for zero only)
    # bin_size = 90/vector_size
    # bins = np.arange(two_theta_min, two_theta_max + bin_size, bin_size)
    bins = np.linspace(two_theta_min, two_theta_max, descriptor_size)
    index_of_bins_for_points = np.digitize(two_theta, bins, right=True)

    # number of points from XRD = len(two_theta) = len(index_of_bins_for_points)
    num_points = len(two_theta)
    descriptor_vector = np.zeros(len(bins))

    # put XRD points into bins
    for i in range(num_points):
        descriptor_vector[index_of_bins_for_points[i]] += intensity[i]
    return descriptor_vector
Esempio n. 24
0
    def xrd(self, ):
        import os
        from pymatgen import Lattice, Structure
        from pymatgen.analysis.diffraction.xrd import XRDCalculator
        from IPython.display import Image, display
        from pymatgen.io.cif import CifParser
        ass = self.cif_route
        print(ass)
        # os.chdir(r"E:\VASP practical\Input")
        # print (os.getcwd())

        # Note that you must provide your own API Key, which can
        # be accessed via the Dashboard at materialsproject.org
        #mpr = MPRester()#密钥
        struct = CifParser(ass)
        structure = struct.get_structures()[0]
        print(structure)
        os.chdir(r"E:\VASP practical\Input")
        print(os.getcwd())
        c = XRDCalculator()
        c.show_plot(structure)

        print(os.getcwd())
Esempio n. 25
0
def peaks_with_gauss(structure, degree_min=0.0, degree_max=90.0, step=0.05):
    spectrum = XRDCalculator().get_pattern(structure)
    positions, intensities = spectrum.x, spectrum.y
    num_points = int((degree_max - degree_min) / step + 1)
    num_positions = [int(position / step + 1) for position in positions]

    def peak(num_points, position, intensity, M=31, std=3):
        k = np.zeros(num_points)
        mn = int(position - (M - 1) / 2)
        mx = int(position + (M - 1) / 2 + 1)
        diff = mx if mx <= num_points else num_points - mn if mn >= 0 else 0
        k[mn if mn >= 0 else 0:mx if mx <= num_points else
          num_points] = intensity * gaussian(M, std=std)[:diff]
        return k

    final_intensity = sum(
        [peak(num_points, p, i) for p, i in zip(num_positions, intensities)])

    return np.linspace(degree_min, degree_max, num_points), final_intensity
Esempio n. 26
0
def get_xrd_plot(args):
    s = Structure.from_file(args.xrd_structure_file)
    c = XRDCalculator()
    return c.get_plot(s)
Esempio n. 27
0
dest_dir = str(sys.argv[2])
#wave = str(sys.argv[2])
# wave = One of [Cuka, AgKa, MoKa, FeKa]
p = Poscar.from_file(os.path.join(poscar_dir, "POSCAR"),
                     check_for_POTCAR=False)

lattice = p.structure.lattice
species = p.structure.species
frac_coords = p.structure.frac_coords

structure = Structure(lattice, species, frac_coords)

plt = pretty_plot(16, 14)
ax = plt.gca()

c_cuka = XRDCalculator("CuKa")
d1 = c_cuka.get_xrd_plot(structure,
                         two_theta_range=(0, 100),
                         annotate_peaks=False,
                         ax=ax)
d1.savefig(os.path.join(dest_dir, "xrd_CuKa.png"))

c_agka = XRDCalculator("AgKa")
d2 = c_agka.get_xrd_plot(structure,
                         two_theta_range=(0, 100),
                         annotate_peaks=False,
                         ax=ax)
d2.savefig(os.path.join(dest_dir, "xrd_AgKa.png"))

c_moka = XRDCalculator("MoKa")
d3 = c_moka.get_xrd_plot(structure,
Esempio n. 28
0
def xrd(structure: Structure,
        two_theta_range: Tuple[int, int] = (0, 120),
        sigma: float = 0.05,
        nsample: int = 5000,
        fig_name: str = "XRD.png",
        peak_raw_fname: str = "",
        plot_dat_fname: str = ""):
    '''
    Calculate XRD pattern of given structure, raw pattern data is returned

    @in
      - structure, Structure
      - two_theta_range, (int, int), range of 2Theta in XRD pattern
      - sigma, float, gaussian smearing width
      - nsample, int, how many points in final plot
      - fig_name, str, name of the figure file to be written,
        default is XRD.png
      - peak_raw_fname, str, name of the raw data file containing 2Theta and
        intensity.
      - plot_dat_fname, str, name of the plot data file. That plot data was
        used to plot the XRD pattern.
    @out
      - x, np.1darray, theta
      - y, np.1darray, intensity
      - plot_x, np.1darray, theta of final data in plotting
      - plot_y, np.1darray, intensity of final data in plotting
    '''
    def _smearing(x,
                  y,
                  sigma=sigma,
                  nsample=nsample) -> Tuple[NDArray, NDArray]:
        '''
        Apply smearing to discret delta functions to get a continuous array
        @in
          - x: x coordinates of peak
          - y: peak heights
        @out
          - res_x
          - res_y
        '''
        def _smearing_helper(x, x0, sigma=sigma):
            return np.exp(-(x - x0)**2 / (2 * sigma**2))

        assert x.shape == y.shape
        npeaks = x.shape[0]
        res_x = np.linspace(two_theta_range[0],
                            two_theta_range[1],
                            num=nsample)
        smear_res = np.empty((npeaks, nsample))
        for ipeak in range(npeaks):
            smear_res[ipeak] = _smearing_helper(res_x, x[ipeak]) * y[ipeak]
            pass
        res_y = np.sum(smear_res, axis=(0))
        return (res_x, res_y)

    c = XRDCalculator()
    p = c.get_pattern(structure, two_theta_range=two_theta_range)
    (x, y) = _smearing(p.x, p.y, sigma=sigma)
    plt.figure()
    plt.plot(x, y)
    plt.vlines(p.x, ymin=-5, ymax=-1)
    plt.ylim(-5, 110)
    plt.xlabel(r"$2\theta$ ($^\circ$)")
    plt.ylabel(r"Intensities (scaled)")
    if "" != fig_name:
        plt.savefig(fig_name, dpi=800, linewidth=0.01)

    if "" != peak_raw_fname:
        with open(peak_raw_fname, 'w') as f:
            to_be_written = "# {:^10} {:^12} {:^9}\n".format(
                "2Theta", "Intensity", "Miller")
            for (_x, _y, hkls) in zip(p.x, p.y, p.hkls):
                label = ",".join([str(hkl['hkl']) for hkl in hkls])
                to_be_written += " {:11.7f} {:11.7f} {}\n".format(
                    _x, _y, label)
            print(to_be_written, file=f)

    if "" != plot_dat_fname:
        with open(plot_dat_fname, 'w') as f:
            to_be_written = "# {:^10} {:^12}\n".format("2Theta", "Intensity")
            for (_x, _y) in np.vstack([x, y]).T:
                to_be_written += " {:11.7f} {:11.7f}\n".format(_x, _y)
            print(to_be_written, file=f)
    return (p.x, p.y, x, y)
Esempio n. 29
0
    def set_from_pymatgen(self, structure, k0, k0p, file=None,
                          name='', version=4, int_min=0.1,
                          comments='', thermal_expansion=0.,
                          two_theta_range=(0., 30.)):
        """
        set parameters from pymatgen outputs

        Parameters
        ----------
        structure = pymatgen structure object
        k0 = bulk modulus
        k0p = pressure derivative of bulk modulus
        file = file name (optional)
        name = name (optional)
        version = version (optional)
        comments = comments (optional)
        thermal_expansion = 0 (optional)

        Returns
        -------

        """
        lattice = structure.lattice
        self.k0 = k0
        self.k0p = k0p
        self.a0 = float(lattice.a)
        self.b0 = float(lattice.b)
        self.c0 = float(lattice.c)
        self.alpha0 = float(lattice.alpha)
        self.beta0 = float(lattice.beta)
        self.gamma0 = float(lattice.gamma)
        self.symmetry = str(SpacegroupAnalyzer(structure).get_crystal_system())
        self.file = file
        self.name = name
        self.version = version
        self.comments = comments
        self.thermal_expansion = thermal_expansion
        self.v0 = cal_UnitCellVolume(self.symmetry,
                                     self.a0, self.b0, self.c0,
                                     self.alpha0, self.beta0,
                                     self.gamma0)
        c = XRDCalculator(wavelength=0.3344)
        pattern = c.get_pattern(structure, two_theta_range=two_theta_range)
        h = []
        k = []
        l = []
        for i in range(pattern.hkls.__len__()):
            h.append(pattern.hkls[i][0]['hkl'][0])
            k.append(pattern.hkls[i][0]['hkl'][1])
            l.append(pattern.hkls[i][0]['hkl'][-1])
        d_lines = np.transpose([pattern.x, pattern.d_hkls, pattern.y, h, k, l])
        DiffLines = []
        for line in d_lines:
            if float(line[2]) >= int_min:
                d_line = DiffractionLine()
                d_line.dsp0 = float(line[1])
                #d_line.dsp = float(line[1])
                d_line.intensity = float(line[2])
                d_line.h = float(line[3])
                d_line.k = float(line[4])
                d_line.l = float(line[5])
                DiffLines.append(d_line)
        self.DiffLines = DiffLines
Esempio n. 30
0
    def learninglib_build(self, output_dir=None, pdfcal_cfg=None,
                          rdf=True, xrd=False, Bisoequiv=0.1,
                          rstep=None, DebyeCal=False, nosymmetry=False,
                          tth_range=None, wavelength=0.5):
        """ method to build learning lib with diffpy based on path
        of cif library. Paramters of G(r) calculation are set
        via glbl.<attribute>. "PDFCal_config.txt" file with PDFCalculator
        configuration will also be output

        Parameters
        ----------
        pdfcal_cfg : dict, optional
            configuration of PDF calculator, default is the one defined
            inside glbl class.
        rdf : bool, optional
            option to compute RDF or not. default to True, if not,
            compute pdf
        xrd : bool, optional
            option to compute XRD (which is slow). default to False.
        Bisoequiv : float, optional
            value of isotropic thermal parameter. default is 0.1.
            scientific equation: Biso = 8 (pi**2) Uiso
        rstep : float, optioanl
            space of PDF. default is pi/qmax.
        DebyeCal : bool, optional
            option to use Debye calculator. default is False.
        nosymmetry : bool, optional
            DEPRECATED for now. option to apply no symmetry.
            default is False.
        tth_range : ndarray, optional
            range of 2theta. default is [0:0.1:90]
        wavelength : float, optional
            wavelength in angstroms, default to 0.5 A which corresponds
            to Qmax ~= 17
        """
        # setup output dir
        timestr = _timestampstr(time.time())
        if output_dir is None:
            tail = "LearningLib_{}".format(timestr)
            output_dir = os.path.join(os.getcwd(), tail)
        print('=== output dir would be {} ==='.format(output_dir))
        self.output_dir = output_dir
        if tth_range is None:
            self.tth_range = np.arange(0, 90, 0.1)
        self.wavelength = wavelength
        self.std_q = theta2q(self.tth_range, self.wavelength)

        ####### configure pymatgen XRD calculator #####
        # instantiate calculators
        xrd_cal = XRDCalculator()
        xrd_cal.wavelength = self.wavelength
        xrd_cal.TWO_THETA_TOL = 10**-2
        self.calculate_params.update({'xrd_wavelength':
                                       xrd_cal.wavelength})

        xrd_list = []
        sg_list = []
        # (a,b,c, alpha, beta, gamma, volume)
        structure_list_1 = []  # primative cell
        structure_list_2 = []  # ordinary cell
        # chemical element
        composition_list_1 = []  # primative cell
        composition_list_2 = []  # ordinary cell
        fail_list = []

        ####### configure diffpy PDF calculator ######
        if DebyeCal:
            cal = DebyePDFCalculator()
            self.calculator_type = 'Debye'
        cal = PDFCalculator()
        self.calculator = cal
        self.calculator_type = 'PDF'
        self.calculate_params.update({'calculator_type':
                                      self.calculator_type})
        # setup calculator parameters
        if rstep is None:
            rstep = glbl.rstep
        self.rstep = rstep
        self.calculator.rstep = rstep  # annoying fact
        self.calculate_params.update({'rstep':rstep})

        if pdfcal_cfg is None:
            self.pdfcal_cfg = glbl.cfg
        self.calculate_params.update(self.pdfcal_cfg)

        # configure calculator
        for k,v in self.pdfcal_cfg.items():
            setattr(self.calculator, k, v)
        # empty list to store results
        gr_list = []
        rdf_list = []
        print("====== INFO: calculation parameters:====\n{}"
              .format(self.calculate_params))
        struc_df = pd.DataFrame()
        ############# loop through cifs #################
        for cif in sorted(self.cif_list):
            _cif = os.path.join(self.input_dir, cif)
            try:
                # diffpy structure
                struc = loadStructure(_cif)
                struc.Bisoequiv = Bisoequiv

                ## calculate PDF/RDF with diffpy ##
                if nosymmetry:
                    struc = nosymmetry(struc)
                cal.setStructure(struc)
                cal.eval()

                # pymatge structure
                struc_meta = CifParser(_cif)
                ## calculate XRD with pymatgen ##
                if xrd:
                    xrd = xrd_cal.get_xrd_data(struc_meta\
                            .get_structures(False).pop())
                    _xrd = np.asarray(xrd)[:,:2]
                    q, iq = _xrd.T
                    interp_q = assign_nearest(self.std_q, q, iq)
                    xrd_list.append(interp_q)
                else:
                    pass
                ## test space group info ##
                _sg = struc_meta.get_structures(False).pop()\
                        .get_space_group_info()
            except:
                print("{} fail".format(_cif))
                fail_list.append(cif)
            else:
                # no error for both pymatgen and diffpy
                gr_list.append(cal.pdf)
                rdf_list.append(cal.rdf)
                self.density_list.append(cal.slope)
                print('=== Finished evaluating PDF from structure {} ==='
                       .format(cif))
                ## update features ##
                flag = ['primitive', 'ordinary']
                option = [True, False]
                compo_list = [composition_list_1, composition_list_2]
                struc_fields = ['a','b','c','alpha','beta','gamma', 'volume']
                for f, op, compo in zip(flag, option, compo_list):
                    rv_dict = {}
                    struc = struc_meta.get_structures(op).pop()
                    a, b, c = struc.lattice.abc
                    aa, bb, cc = struc.lattice.angles
                    volume = struc.volume
                    for k, v in zip(struc_fields,
                                    [a, b, c, aa, bb, cc, volume]):
                        rv_dict.update({"{}_{}".format(f, k) : v})
                    compo.append(struc.composition.as_dict())
                    struc_df = struc_df.append(rv_dict,
                                               ignore_index=True)
                # sg info, use the ordinary setup
                sg_list.append(struc.get_space_group_info())
                print('=== Finished evaluating XRD from structure {} ==='
                      .format(cif))

        # finally, store crucial calculation results as attributes
        self.r_grid = cal.rgrid
        #4*pi * r^2 * rho(r) = R(r)  -> RDF to density 
        self.gr_array = np.asarray(gr_list)/4/np.pi/self.r_grid**2
        self.rdf_array = np.asarray(gr_list)
        self.density_list = np.asarray(self.density_list)
        self.xrd_info = np.asarray(xrd_list)
        self.sg_list = sg_list
        # 1 -> primitive , 2 -> ordinary
        self.composition_list_1 = composition_list_1
        self.composition_list_2 = composition_list_2
        self.struc_df = struc_df
        self.fail_list = fail_list
Esempio n. 31
0
def get_xrd_plot(args):
    s = Structure.from_file(args.xrd_structure_file)
    c = XRDCalculator()
    return c.get_xrd_plot(s)
Esempio n. 32
0
# # 4. Get lattice parameters

# In[9]:

lattice = material.lattice
print('Lattice parameters = ', lattice.a, lattice.b, lattice.c, lattice.alpha,
      lattice.beta, lattice.gamma)
crystal_system = SpacegroupAnalyzer(material).get_crystal_system()
print(crystal_system)

# # 5. Get diffraction pattern

# In[10]:

c = XRDCalculator(wavelength=wl_xray)
pattern = c.get_xrd_data(material, two_theta_range=xrange)

# ## 5.1. Extract twotheta, d-sp, int, hkl

# In[11]:

d_lines = []
for values in pattern:
    hkl_key = values[2].keys()
    hkl_txt = str(hkl_key)[12:-3].split(",")
    # print(hkl_txt[0], hkl_txt[1], hkl_txt[-1])
    d_lines.append([
        values[0], values[3], values[1],
        int(hkl_txt[0]),
        int(hkl_txt[1]),
Esempio n. 33
0
# This initializes the REST adaptor. Put your own API key in.
from pymatgen import MPRester, Element
from pymatgen.analysis.diffraction.xrd import XRDCalculator

a = MPRester("")

# Entries are the basic unit for thermodynamic and other analyses in pymatgen.
# This gets all entries belonging to the MnO2 material.
entry = a.get_entry_by_material_id(
    "mp-18759",
    inc_structure=True,
    property_data=["material_id", "energy", "energy_per_atom", "volume"])

#print(entry)

xrdc = XRDCalculator()
xrdc.get_plot(entry.structure).show()
Esempio n. 34
0
def list_get_pattern_xrd(list_struc):
    ls = []
    for structure in list_struc:
        i = XRDCalculator()
        ls.append(i.get_pattern(structure))
    return ls
Esempio n. 35
0
    def test_get_pattern(self):
        s = self.get_structure("CsCl")
        c = XRDCalculator()
        xrd = c.get_pattern(s, two_theta_range=(0, 90))
        self.assertTrue(xrd.to_json())  # Test MSONAble property
        # Check the first two peaks
        self.assertAlmostEqual(xrd.x[0], 21.107738329639844)
        self.assertAlmostEqual(xrd.y[0], 36.483184003748946)
        self.assertEqual(xrd.hkls[0], [{"hkl": (1, 0, 0), "multiplicity": 6}])
        self.assertAlmostEqual(xrd.d_hkls[0], 4.2089999999999996)
        self.assertAlmostEqual(xrd.x[1], 30.024695921112777)
        self.assertAlmostEqual(xrd.y[1], 100)
        self.assertEqual(xrd.hkls[1], [{"hkl": (1, 1, 0), "multiplicity": 12}])
        self.assertAlmostEqual(xrd.d_hkls[1], 2.976212442014178)

        s = self.get_structure("LiFePO4")
        xrd = c.get_pattern(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(xrd.x[1], 17.03504233621785)
        self.assertAlmostEqual(xrd.y[1], 50.400928948337075)

        s = self.get_structure("Li10GeP2S12")
        xrd = c.get_pattern(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(xrd.x[1], 14.058274883353876)
        self.assertAlmostEqual(xrd.y[1], 4.4111123641667671)

        # Test a hexagonal structure.
        s = self.get_structure("Graphite")

        xrd = c.get_pattern(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(xrd.x[0], 26.21057350859598)
        self.assertAlmostEqual(xrd.y[0], 100)
        self.assertAlmostEqual(len(xrd.hkls[0][0]["hkl"]), 4)

        # Add test case with different lengths of coefficients.
        # Also test d_hkl.
        coords = [
            [0.25, 0.25, 0.173],
            [0.75, 0.75, 0.827],
            [0.75, 0.25, 0],
            [0.25, 0.75, 0],
            [0.25, 0.25, 0.676],
            [0.75, 0.75, 0.324],
        ]
        sp = ["Si", "Si", "Ru", "Ru", "Pr", "Pr"]
        s = Structure(Lattice.tetragonal(4.192, 6.88), sp, coords)
        xrd = c.get_pattern(s)
        self.assertAlmostEqual(xrd.x[0], 12.86727341476735)
        self.assertAlmostEqual(xrd.y[0], 31.448239816769796)
        self.assertAlmostEqual(xrd.d_hkls[0], 6.88)
        self.assertEqual(len(xrd), 42)
        xrd = c.get_pattern(s, two_theta_range=[0, 60])
        self.assertEqual(len(xrd), 18)

        # Test with and without Debye-Waller factor
        tungsten = Structure(Lattice.cubic(3.1653), ["W"] * 2,
                             [[0, 0, 0], [0.5, 0.5, 0.5]])
        xrd = c.get_pattern(tungsten, scaled=False)
        self.assertAlmostEqual(xrd.x[0], 40.294828554672264)
        self.assertAlmostEqual(xrd.y[0], 2414237.5633093244)
        self.assertAlmostEqual(xrd.d_hkls[0], 2.2382050944897789)
        c = XRDCalculator(debye_waller_factors={"W": 0.1526})
        xrd = c.get_pattern(tungsten, scaled=False)
        self.assertAlmostEqual(xrd.x[0], 40.294828554672264)
        self.assertAlmostEqual(xrd.y[0], 2377745.2296686019)
        self.assertAlmostEqual(xrd.d_hkls[0], 2.2382050944897789)
Esempio n. 36
0
from pymatgen.io.vaspio import Vasprun

vr=Vasprun("vasprun.xml")

structure0=vr.structures[0]
structure1=vr.structures[391]

from pymatgen.analysis.diffraction.xrd import XRDCalculator

c = XRDCalculator()

c.show_xrd_plot(structure0)
c.show_xrd_plot(structure1)
Esempio n. 37
0
	return(structure_files)

####################################################################
def find_line(file,searchExp):
	f=open(file,'r')
	index=0
	for line in f:
		if searchExp in line:
			break
		index += 1
        f.close()

	return(index)

####################################################################
# filename = 'TMDMOF.vasp'
read_structures()
for each in structure_files:
	print(each)
	filename = str(each + ".vasp")

	structure_pos = Poscar.from_file(filename)

	c = XRDCalculator()
	structure = structure_pos.structure
	XRD = c.get_xrd_data(structure, scaled = True, two_theta_range = (5,20))

	fil = filename.split(".", 1)
	f = open(str(fil[0] + ".xye"), 'w')
	print(*XRD, sep='\n', file=f)
from pymatgen import Lattice, Structure
from pymatgen.analysis.diffraction.xrd import XRDCalculator
from IPython.display import Image, display
from matplotlib import pyplot


# Create CsCl structure
a = 4.209 #Angstrom(埃:一个长度单位,用来表示原子尺寸、键长和电磁波波长。)
latt = Lattice.cubic(a)

#latt:点阵一个长度为a的立方体
#species:物质,这里是["Cs", "Cl"]
#坐标:三位数组的列表,表示物质的坐标
structure = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]])

c = XRDCalculator()

#get_plot返回的结果就是一个pyplot类型的图片
image = c.get_plot(structure, two_theta_range=(0, 90), annotate_peaks=True, ax=None, with_labels=True, fontsize=16)

#image.show()
image.savefig("alpha CsCl.jpg")
#display(Image(filename=('./PDF - alpha CsCl.png')))
a = 6.923 #Angstrom
latt = Lattice.cubic(a)
structure = Structure(latt, ["Cs", "Cs", "Cs", "Cs", "Cl", "Cl", "Cl", "Cl"],
                      [[0, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0.5], [0.5, 0, 0.5],
                       [0.5, 0.5, 0.5], [0, 0, 0.5], [0, 0.5, 0], [0.5, 0, 0]])

image = c.get_plot(structure, two_theta_range=(0, 90), annotate_peaks=True, ax=None, with_labels=True, fontsize=16)
#display(Image(filename=('./PDF - beta CsCl.png')))这段代码display我还没有弄明白,帮我看看哪里出问题了
Esempio n. 39
0
def strip_fn(fp):
    """helper function to strip extention of filename"""
    base = os.path.basename(fp)
    fn, ext = os.path.splitext(base)
    return fn

####### configure pymatgen XRD calculator #####
calculate_params = {}

wavelength = 0.5
tth_range = np.arange(0, 90, 0.1)
std_q = theta2q(tth_range, wavelength)

# instantiate calculators
xrd_cal = XRDCalculator()
xrd_cal.wavelength = wavelength
xrd_cal.TWO_THETA_TOL = 10**-2
calculate_params.update({'xrd_wavelength':
                         xrd_cal.wavelength})

#######  PDF calculator instance ######
cal = PDFCalculator()

#######  Bond distance calculator instance ######
bc = BondCalculator(rmax=bond_range)

def map_learninglib(cif_fp, mode='bond_dst'):
    """function designed to build atomic distance list with
    parallel computation