コード例 #1
0
ファイル: p_cif.py プロジェクト: diffpy/diffpy.Structure
    def _expandAsymmetricUnit(self):
        """Perform symmetry expansion of self.stru using self.spacegroup.
        This method updates data in stru and eau.

        No return value.
        """
        from diffpy.structure.symmetryutilities import ExpandAsymmetricUnit
        # get reverse-ordered unique indices
        corepos = [a.xyz for a in self.stru]
        coreUijs = [a.U for a in self.stru]
        self.eau = ExpandAsymmetricUnit(self.spacegroup, corepos, coreUijs,
                                        eps=self.eps)
        # build a nested list of new atoms:
        newatoms = []
        for i, ca in enumerate(self.stru):
            eca = []    # expanded core atom
            for j in range(self.eau.multiplicity[i]):
                a = Atom(ca)
                a.xyz = self.eau.expandedpos[i][j]
                if j > 0:
                    a.label += '_' + str(j + 1)
                if a.anisotropy:
                    a.U = self.eau.expandedUijs[i][j]
                eca.append(a)
            newatoms.append(eca)
        # insert new atoms where they belong
        self.stru[:] = sum(newatoms, [])
        return
コード例 #2
0
def supercell(S, mno):
    """Perform supercell expansion for a structure.

    New lattice parameters are multiplied and fractional coordinates
    divided by corresponding multiplier.  New atoms are grouped with
    their source in the original cell.

    S   -- an instance of Structure from diffpy.structure.
    mno -- sequence of 3 integers for cell multipliers along
           the a, b and c axes.

    Return a new expanded structure instance.
    Raise TypeError when S is not Structure instance.
    Raise ValueError for invalid mno argument.
    """
    # check arguments
    if len(mno) != 3:
        emsg = "Argument mno must contain 3 numbers."
        raise ValueError(emsg)
    elif min(mno) < 1:
        emsg = "Multipliers must be greater or equal 1"
        raise ValueError(emsg)
    if not isinstance(S, Structure):
        emsg = "The first argument must be a Structure instance."
        raise TypeError(emsg)

    # convert mno to a tuple of integers so it can be used as range limit.
    mno = (int(mno[0]), int(mno[1]), int(mno[2]))

    # create return instance
    newS = Structure(S)
    if mno == (1, 1, 1):
        return newS

    # back to business
    ijklist = [(i,j,k)
                for i in range(mno[0])
                    for j in range(mno[1])
                        for k in range(mno[2])]
    # numpy.floor returns float array
    mnofloats = numpy.array(mno, dtype=float)

    # build a list of new atoms
    newAtoms = []
    for a in S:
        for ijk in ijklist:
            adup = Atom(a)
            adup.xyz = (a.xyz + ijk)/mnofloats
            newAtoms.append(adup)
    # newS can own references in newAtoms, no need to make copies
    newS.__setitem__(slice(None), newAtoms, copy=False)

    # take care of lattice parameters
    newS.lattice.setLatPar(
            a=mno[0]*S.lattice.a,
            b=mno[1]*S.lattice.b,
            c=mno[2]*S.lattice.c )
    return newS
コード例 #3
0
def _dummyAtomWithBiso(crystal, biso):
    from numpy import degrees
    from diffpy.structure import Lattice, Atom
    lattice = Lattice(crystal.a, crystal.b, crystal.c,
                      degrees(crystal.alpha),
                      degrees(crystal.beta),
                      degrees(crystal.gamma))
    a = Atom('X', anisotropy=False, lattice=lattice)
    a.Bisoequiv = biso
    return a
コード例 #4
0
def supercell(S, mno):
    """Perform supercell expansion for a structure.

    New lattice parameters are multiplied and fractional coordinates
    divided by corresponding multiplier.  New atoms are grouped with
    their source in the original cell.

    S   -- an instance of Structure from diffpy.structure.
    mno -- sequence of 3 integers for cell multipliers along
           the a, b and c axes.

    Return a new expanded structure instance.
    Raise TypeError when S is not Structure instance.
    Raise ValueError for invalid mno argument.
    """
    # check arguments
    if len(mno) != 3:
        emsg = "Argument mno must contain 3 numbers."
        raise ValueError(emsg)
    elif min(mno) < 1:
        emsg = "Multipliers must be greater or equal 1"
        raise ValueError(emsg)
    if not isinstance(S, Structure):
        emsg = "The first argument must be a Structure instance."
        raise TypeError(emsg)

    # convert mno to a tuple of integers so it can be used as range limit.
    mno = (int(mno[0]), int(mno[1]), int(mno[2]))

    # create return instance
    newS = Structure(S)
    if mno == (1, 1, 1):
        return newS

    # back to business
    ijklist = [(i, j, k) for i in range(mno[0]) for j in range(mno[1])
               for k in range(mno[2])]
    # numpy.floor returns float array
    mnofloats = numpy.array(mno, dtype=float)

    # build a list of new atoms
    newAtoms = []
    for a in S:
        for ijk in ijklist:
            adup = Atom(a)
            adup.xyz = (a.xyz + ijk) / mnofloats
            newAtoms.append(adup)
    # newS can own references in newAtoms, no need to make copies
    newS.__setitem__(slice(None), newAtoms, copy=False)

    # take care of lattice parameters
    newS.lattice.setLatPar(a=mno[0] * S.lattice.a,
                           b=mno[1] * S.lattice.b,
                           c=mno[2] * S.lattice.c)
    return newS
コード例 #5
0
 def test_writeStr_xyz(self):
     """check string representation of normal xyz file"""
     stru = self.stru
     stru.title = "test of writeStr"
     stru.lattice = Lattice(1.0, 2.0, 3.0, 90.0, 90.0, 90.0)
     stru[:] = [Atom('H', [1., 1., 1.]), Atom('Cl', [3., 2., 1.])]
     s1 = stru.writeStr(self.format)
     s1 = re.sub('[ \t]+', ' ', s1)
     s0 = "2\n%s\nH 1 2 3\nCl 3 4 3\n" % stru.title
     self.assertEqual(s1, s0)
     return
コード例 #6
0
ファイル: conftest.py プロジェクト: pyxem/diffsims
def ferrite_phase():
    return Phase(
        name="ferrite",
        space_group=229,
        structure=Structure(
            lattice=Lattice(2.8665, 2.8665, 2.8665, 90, 90, 90),
            atoms=[
                Atom(xyz=[0, 0, 0], atype="Fe", Uisoequiv=0.006332),
                Atom(xyz=[0.5, 0.5, 0.5], atype="Fe", Uisoequiv=0.006332),
            ],
        ),
    )
コード例 #7
0
 def setUp(self):
     self.stru = Structure(
         [Atom('C', [0, 0, 0]), Atom('C', [1, 1, 1])],
         lattice=Lattice(1, 1, 1, 90, 90, 120))
     if not self._loaded_structures:
         self._loaded_structures.update([
             ('cdse', Structure(filename=cdsefile)),
             ('tei', Structure(filename=teifile)),
             ('pbte', Structure(filename=pbtefile)),
         ])
     self.__dict__.update(self._loaded_structures)
     self.places = 12
     return
コード例 #8
0
 def test_write_xyz(self):
     """check writing of normal xyz file"""
     stru = self.stru
     stru.title = "test of writeStr"
     stru.lattice = Lattice(1.0, 2.0, 3.0, 90.0, 90.0, 90.0)
     stru[:] = [Atom('H', [1., 1., 1.]), Atom('Cl', [3., 2., 1.])]
     filename = self.mktmpfile()
     stru.write(filename, self.format)
     with open(filename) as fp:
         f_s = fp.read()
     f_s = re.sub('[ \t]+', ' ', f_s)
     s_s = "2\n%s\nH 1 2 3\nCl 3 4 3\n" % stru.title
     self.assertEqual(f_s, s_s)
     return
コード例 #9
0
ファイル: conftest.py プロジェクト: pyxem/diffsims
def silicon_carbide_phase():
    """Silicon Carbide 4H polytype (hexagonal, space group 186)."""
    return Phase(
        space_group=186,
        structure=Structure(
            lattice=Lattice(3.073, 3.073, 10.053, 90, 90, 120),
            atoms=[
                Atom(atype="Si", xyz=[0, 0, 0]),
                Atom(atype="Si", xyz=[0.33, 0.667, 0.25]),
                Atom(atype="C", xyz=[0, 0, 0.188]),
                Atom(atype="C", xyz=[0.333, 0.667, 0.438]),
            ],
        ),
    )
コード例 #10
0
 def test_insertAtoms(self):
     """check FitStructure.insertAtoms()
     """
     from diffpy.structure import Atom
     stru = self.stru
     stru.read(datafile('Ni.stru'), format='pdffit')
     cns = Constraint('@1')
     stru.constraints['x(2)'] = cns
     stru.insertAtoms(0, [Atom('Na', (0, 0, 0))])
     self.assertEqual(5, len(stru))
     self.assertEqual(1, len(stru.constraints))
     self.assertTrue(cns is stru.constraints['x(3)'])
     stru.insertAtoms(5, [Atom('Cl', (0, 0, 0))])
     self.assertTrue(['x(3)'] == stru.constraints.keys())
     return
コード例 #11
0
    def expandAsymmetricUnit(self, spacegroup, indices, sgoffset=[0,0,0]):
        """Perform symmetry expansion for atoms at given indices.
        Temperature factors may be corrected to reflect the symmetry.
        All constraints for expanded atoms are erased with the exception
        of the occupancy("occ".  Constraints of unaffected atoms are adjusted
        for new positions self.initial.

        spacegroup  -- instance of SpaceGroup from diffpy.structure
        indices     -- list of integer indices of atoms to be expanded
        sgoffset    -- optional offset of space group origin [0,0,0]
        """
        from diffpy.structure.symmetryutilities import ExpandAsymmetricUnit
        acd = self._popAtomConstraints()
        # get unique, reverse sorted indices
        ruindices = dict.fromkeys(indices).keys()
        ruindices.sort()
        ruindices.reverse()
        coreatoms = [self.initial[i] for i in ruindices]
        corepos = [a.xyz for a in coreatoms]
        coreUijs = [a.U for a in coreatoms]
        eau = ExpandAsymmetricUnit(spacegroup, corepos, coreUijs,
                sgoffset=sgoffset, eps=self.symposeps)
        # build a nested list of new atoms:
        newatoms = []
        for i in range(len(coreatoms)):
            ca = coreatoms[i]
            caocc_con = None
            if ca in acd and "occ" in acd[ca]:
                caocc_con = acd[ca]["occ"]
            eca = []    # expanded core atom
            for j in range(eau.multiplicity[i]):
                a = Atom(ca)
                a.xyz = eau.expandedpos[i][j]
                a.U = eau.expandedUijs[i][j]
                eca.append(a)
                if caocc_con is None:   continue
                # make a copy of occupancy constraint
                acd[a] = {"occ" : copy.copy(caocc_con)}
            newatoms.append(eca)
        # insert new atoms where they belong
        for i, atomlist in zip(ruindices, newatoms):
            self.initial[i:i+1] = atomlist
        # remember this spacegroup as the last one used
        self.initial.pdffit["spcgr"] = spacegroup.short_name
        self.initial.pdffit["sgoffset"] = list(sgoffset)
        # tidy constraints
        self._restoreAtomConstraints(acd)
        return
コード例 #12
0
 def test_getvar(self):
     """check PDFStructure.getvar()
     """
     from diffpy.structure import Atom
     stru = self.stru
     abcABG = (3.0, 4.0, 5.0, 81, 82, 83)
     stru.lattice.setLatPar(*abcABG)
     for i in range(6):
         self.assertEqual(abcABG[i], stru.getvar('lat(%i)' % (i + 1)))
     stru.append(Atom('Ni', [0.1, 0.2, 0.3]))
     self.assertEqual(0.1, stru.getvar('x(1)'))
     self.assertEqual(0.2, stru.getvar('y(1)'))
     self.assertEqual(0.3, stru.getvar('z(1)'))
     self.assertEqual(1.0, stru.getvar('occ(1)'))
     # pscale
     self.assertEqual(1.0, stru.getvar('pscale'))
     # spdiameter
     self.assertEqual(0.0, stru.getvar('spdiameter'))
     stru.pdffit['spdiameter'] = 37.7
     self.assertEqual(37.7, stru.getvar('spdiameter'))
     # stepcut
     self.assertEqual(0.0, stru.getvar('stepcut'))
     stru.pdffit['stepcut'] = 17.7
     self.assertEqual(17.7, stru.getvar('stepcut'))
     self.assertRaises(ControlKeyError, stru.getvar, 'invalid(1)')
     self.assertRaises(ControlKeyError, stru.getvar, 'invalid')
     return
コード例 #13
0
def _defaultNewAtom():
    """Create new atom instance with non-zero initial U.
    """
    uii = 0.003
    rv = Atom("C", [0.0, 0.0, 0.0],
              U=[[uii, 0, 0], [0, uii, 0], [0, 0, uii]])
    return rv
コード例 #14
0
def _create_fcc(atom1=None, atom2=None, lattice_parameter=2.54, size=10):
    """Sets the initial positions for an FCC-like cluster.
      Uses the golden ratio to create a set of evenly
      spaced atom around some central point.

    Parameters
    _______________
    atom1: str
        The corner atom of the cluster
    atom2: str
        The edge atoms of the cluster
    lattice_parameter: float
        The lattice parameter of the unit cell
    size: float
        The size of the cluster in angstroms

    Returns
    ------------
    atom_list: list
        A list of atoms in the cluster
    """
    atom_list = []
    x_pos, y_pos, z_pos = np.mgrid[-size:size + 1, -size:size + 1,
                                   -size:size + 1]
    x_pos = x_pos * lattice_parameter
    y_pos = y_pos * lattice_parameter
    z_pos = z_pos * lattice_parameter
    dis = [[0, 0, 0], [.5, .5, 0], [0, .5, .5], [.5, 0, .5]]
    for x, y, z in zip(x_pos.flatten(), y_pos.flatten(), z_pos.flatten()):
        for d in dis:
            if d == [0, 0, 0] and np.linalg.norm([x, y, z]) < size:
                atom_list.append(Atom(xyz=[x, y, z], atype=atom1))
            elif np.linalg.norm([
                    x + d[0] * lattice_parameter, y + d[1] * lattice_parameter,
                    z + d[2] * lattice_parameter
            ]) < size:
                atom_list.append(
                    Atom(xyz=[
                        x + d[0] * lattice_parameter,
                        y + d[1] * lattice_parameter,
                        z + d[2] * lattice_parameter
                    ],
                         atype=atom2))
            else:
                pass
    return atom_list
コード例 #15
0
def _create_bcc(atom1=None, atom2=None, lattice_parameter=2.54, size=10):
    """Sets the initial positions for an FCC-like cluster.
      Uses the golden ratio to create a set of evenly
      spaced atom around some central point.

    Parameters
    _______________
    atom1: str
        The corner atom of the cluster
    atom2: str
        The edge atoms of the cluster
    lattice_parameter: float
        The lattice parameter of the unit cell
    size: float
        The size of the cluster in angstroms

    Returns
    ------------
    atom_list: list
        A list of atoms in the cluster
    """
    atom_list = []
    int_size = np.ceil(size / lattice_parameter)
    print(int_size)
    x_pos, y_pos, z_pos = np.mgrid[-int_size:(int_size + 1),
                                   -int_size:(int_size + 1),
                                   -int_size:(int_size + 1)]
    x_pos = x_pos * lattice_parameter
    y_pos = y_pos * lattice_parameter
    z_pos = z_pos * lattice_parameter
    for x, y, z in zip(x_pos.flatten(), y_pos.flatten(), z_pos.flatten()):
        if np.linalg.norm([x, y, z]) < size:
            a1 = Atom(xyz=[x, y, z], atype=atom1)
            atom_list.append(a1)
        if np.linalg.norm([
                x + .5 * lattice_parameter, y + .5 * lattice_parameter,
                z + .5 * lattice_parameter
        ]) < size:
            a2 = Atom(xyz=[
                x + 0.5 * lattice_parameter, y + 0.5 * lattice_parameter,
                z + 0.5 * lattice_parameter
            ],
                      atype=atom2)
            atom_list.append(a2)
    return atom_list
コード例 #16
0
ファイル: conftest.py プロジェクト: pyxem/diffsims
def nickel_phase():
    return Phase(
        name="nickel",
        space_group=225,
        structure=Structure(
            lattice=Lattice(3.5236, 3.5236, 3.5236, 90, 90, 90),
            atoms=[Atom(xyz=[0, 0, 0], atype="Ni", Uisoequiv=0.006332)],
        ),
    )
コード例 #17
0
 def test_pickling(self):
     """Test pickling of DiffpyStructureParSet.
     """
     stru = Structure([Atom("C", [0, 0.2, 0.5])])
     dsps = DiffpyStructureParSet("dsps", stru)
     data = pickle.dumps(dsps)
     dsps2 = pickle.loads(data)
     self.assertEqual(1, len(dsps2.atoms))
     self.assertEqual(0.2, dsps2.atoms[0].y.value)
     return
コード例 #18
0
 def test___repr__(self):
     """Test representation of DiffpyStructureParSet objects.
     """
     lat = Lattice(3, 3, 2, 90, 90, 90)
     atom = Atom("C", [0, 0.2, 0.5])
     stru = Structure([atom], lattice=lat)
     dsps = DiffpyStructureParSet("dsps", stru)
     self.assertEqual(repr(stru), repr(dsps))
     self.assertEqual(repr(lat), repr(dsps.lattice))
     self.assertEqual(repr(atom), repr(dsps.atoms[0]))
     return
コード例 #19
0
 def test___init__(self):
     """check Structure.__init__()
     """
     atoms = [Atom('C', [0, 0, 0]), Atom('C', [0.5, 0.5, 0.5])]
     self.assertRaises(ValueError, Structure, atoms, filename=teifile)
     self.assertRaises(ValueError,
                       Structure,
                       lattice=Lattice(),
                       filename=teifile)
     self.assertRaises(ValueError,
                       Structure,
                       title='test',
                       filename=teifile)
     stru1 = Structure(title='my title')
     self.assertEqual('my title', stru1.title)
     stru2a = Structure(atoms)
     stru2b = Structure(iter(atoms))
     stru2c = Structure(a for a in atoms)
     s2a = str(stru2a)
     self.assertEqual(s2a, str(stru2b))
     self.assertEqual(s2a, str(stru2c))
     return
コード例 #20
0
ファイル: p_cif.py プロジェクト: samrmayers/diffpy.structure
    def _expandAsymmetricUnit(self, block):
        """Perform symmetry expansion of self.stru using self.spacegroup.

        This method updates data in stru and eau.

        Parameters
        ----------
        block : CifBlock
            The top-level block containing crystal structure data.
        """
        from diffpy.structure.symmetryutilities import ExpandAsymmetricUnit
        corepos = [a.xyz for a in self.stru]
        coreUijs = [a.U for a in self.stru]
        self.eau = ExpandAsymmetricUnit(self.spacegroup,
                                        corepos,
                                        coreUijs,
                                        eps=self.eps)
        # setup anisotropy according to symmetry requirements
        # unless it was already explicitly set
        for ca, uisotropy in zip(self.stru, self.eau.Uisotropy):
            if not ca.label in self.anisotropy:
                ca.anisotropy = not uisotropy
                self.anisotropy[ca.label] = ca.anisotropy
        # build a nested list of new atoms:
        newatoms = []
        for i, ca in enumerate(self.stru):
            eca = []  # expanded core atom
            for j in range(self.eau.multiplicity[i]):
                a = Atom(ca)
                a.xyz = self.eau.expandedpos[i][j]
                if j > 0:
                    a.label += '_' + str(j + 1)
                if a.anisotropy:
                    a.U = self.eau.expandedUijs[i][j]
                eca.append(a)
            newatoms.append(eca)
        # insert new atoms where they belong
        self.stru[:] = sum(newatoms, [])
        return
コード例 #21
0
 def test___setitem__slice(self):
     """check Structure.__setitem__() with a slice argument
     """
     a = Atom("Si", (0.1, 0.2, 0.3))
     lat = self.stru.lattice
     self.stru[:] = [a]
     a0 = self.stru[0]
     self.assertEqual(1, len(self.stru))
     self.assertEqual('Si', a0.element)
     self.assertTrue(lat is a0.lattice)
     self.assertTrue(numpy.array_equal(a.xyz, a0.xyz))
     self.assertFalse(a is a0)
     self.assertFalse(lat is a.lattice)
     return
コード例 #22
0
 def test___setitem__(self):
     """check Structure.__setitem__()
     """
     a = Atom("Si", (0.1, 0.2, 0.3))
     lat = self.stru.lattice
     self.stru[1] = a
     a1 = self.stru[1]
     self.assertEqual(2, len(self.stru))
     self.assertEqual('Si', a1.element)
     self.assertTrue(lat is a1.lattice)
     self.assertTrue(numpy.array_equal(a.xyz, a1.xyz))
     self.assertFalse(a is a1)
     self.assertFalse(lat is a.lattice)
     return
コード例 #23
0
 def test_append(self):
     """check Structure.append()
     """
     a = Atom("Si", (0.1, 0.2, 0.3))
     lat = self.stru.lattice
     self.stru.append(a)
     alast = self.stru[-1]
     self.assertEqual(3, len(self.stru))
     self.assertEqual('Si', alast.element)
     self.assertTrue(lat is alast.lattice)
     self.assertTrue(numpy.array_equal(a.xyz, alast.xyz))
     self.assertFalse(a is alast)
     self.assertFalse(lat is a.lattice)
     return
コード例 #24
0
def test_get_kinematical_atomic_scattering_factor(element, occupancy,
                                                  displacement_factor,
                                                  scattering_parameter,
                                                  desired_factor):
    atom = Atom(atype=element,
                occupancy=occupancy,
                Uisoequiv=displacement_factor)
    assert np.allclose(
        get_kinematical_atomic_scattering_factor(
            atom=atom,
            scattering_parameter=scattering_parameter,
        ),
        desired_factor,
    )
コード例 #25
0
ファイル: orix_hdf5.py プロジェクト: haal9751/orix
def dict2atom(dictionary):
    """Get a :class:`diffpy.structure.Atom.atom` object from a dictionary.

    Parameters
    ----------
    dictionary : dict
        Dictionary with atom information.

    Returns
    -------
    Atom
    """
    dictionary = copy.deepcopy(dictionary)
    atom_dict = {"atype": dictionary.pop("element")}
    atom_dict.update(dictionary)
    return Atom(**atom_dict)
コード例 #26
0
 def test_writeStr_rawxyz(self):
     """check writing of normal xyz file"""
     stru = self.stru
     stru.title = "test of writeStr"
     stru.lattice = Lattice(1.0, 2.0, 3.0, 90.0, 90.0, 90.0)
     # plain version
     stru[:] = [Atom('H', [1., 1., 1.])]
     s1 = stru.writeStr(self.format)
     s1 = re.sub('[ \t]+', ' ', s1)
     s0 = "H 1 2 3\n"
     # brutal raw version
     stru[0].element = ""
     s1 = stru.writeStr(self.format)
     s0 = "1 2 3\n"
     self.assertEqual(s1, s0)
     return
コード例 #27
0
ファイル: emsoft_ebsd.py プロジェクト: hakonanes/kikuchipy
def _crystaldata2phase(dictionary: dict) -> Phase:
    """Return a :class:`~orix.crystal_map.Phase` object from a
    dictionary with EMsoft CrystalData group content.

    Parameters
    ----------
    dictionary
        Dictionary with phase information.

    Returns
    -------
    Phase
    """
    # TODO: Move this to orix.io.plugins.emsoft_h5ebsd as part of v0.6
    # Get list of atoms
    n_atoms = dictionary["Natomtypes"]
    atom_data = dictionary["AtomData"]
    atom_types = dictionary["Atomtypes"]
    if n_atoms == 1:
        atom_types = (atom_types, )  # Make iterable
    atoms = []
    for i in range(n_atoms):
        # TODO: Convert atom type integer to element name, like Ni for 26
        atoms.append(
            Atom(
                atype=atom_types[i],
                xyz=atom_data[:3, i],
                occupancy=atom_data[3, i],
                Uisoequiv=atom_data[4, i] / (8 * np.pi**2) * 1e2,  # Å^-2
            ))

    # TODO: Use space group setting
    return Phase(
        space_group=int(dictionary["SpaceGroupNumber"]),
        structure=Structure(
            lattice=Lattice(*dictionary["LatticeParameters"].T), atoms=atoms),
    )
コード例 #28
0
    def testDiffpyStructureParSet(self):
        """Test the structure conversion."""

        a1 = Atom("Cu", xyz = numpy.array([.0, .1, .2]), Uisoequiv = 0.003)
        a2 = Atom("Ag", xyz = numpy.array([.3, .4, .5]), Uisoequiv = 0.002)
        l = Lattice(2.5, 2.5, 2.5, 90, 90, 90)

        dsstru = Structure([a1,a2], l)
        # Structure makes copies
        a1 = dsstru[0]
        a2 = dsstru[1]

        s = DiffpyStructureParSet("CuAg", dsstru)

        self.assertEqual(s.name, "CuAg")

        def _testAtoms():
            # Check the atoms thoroughly
            self.assertEqual(a1.element, s.Cu0.element)
            self.assertEqual(a2.element, s.Ag0.element)
            self.assertEqual(a1.Uisoequiv, s.Cu0.Uiso.getValue())
            self.assertEqual(a2.Uisoequiv, s.Ag0.Uiso.getValue())
            self.assertEqual(a1.Bisoequiv, s.Cu0.Biso.getValue())
            self.assertEqual(a2.Bisoequiv, s.Ag0.Biso.getValue())
            for i in range(1, 4):
                for j in range(i, 4):
                    uijstru = getattr(a1, "U%i%i"%(i,j))
                    uij = getattr(s.Cu0, "U%i%i"%(i,j)).getValue()
                    uji = getattr(s.Cu0, "U%i%i"%(j,i)).getValue()
                    self.assertEqual(uijstru, uij)
                    self.assertEqual(uijstru, uji)
                    bijstru = getattr(a1, "B%i%i"%(i,j))
                    bij = getattr(s.Cu0, "B%i%i"%(i,j)).getValue()
                    bji = getattr(s.Cu0, "B%i%i"%(j,i)).getValue()
                    self.assertEqual(bijstru, bij)
                    self.assertEqual(bijstru, bji)

            self.assertEqual(a1.xyz[0], s.Cu0.x.getValue())
            self.assertEqual(a1.xyz[1], s.Cu0.y.getValue())
            self.assertEqual(a1.xyz[2], s.Cu0.z.getValue())
            return


        def _testLattice():

            # Test the lattice
            self.assertEqual(dsstru.lattice.a, s.lattice.a.getValue())
            self.assertEqual(dsstru.lattice.b, s.lattice.b.getValue())
            self.assertEqual(dsstru.lattice.c, s.lattice.c.getValue())
            self.assertEqual(dsstru.lattice.alpha, s.lattice.alpha.getValue())
            self.assertEqual(dsstru.lattice.beta, s.lattice.beta.getValue())
            self.assertEqual(dsstru.lattice.gamma, s.lattice.gamma.getValue())

        _testAtoms()
        _testLattice()

        # Now change some values from the diffpy Structure
        a1.xyz[1] = 0.123
        a1.U11 = 0.321
        a1.B32 = 0.111
        dsstru.lattice.setLatPar(a=3.0, gamma=121)
        _testAtoms()
        _testLattice()

        # Now change values from the srfit DiffpyStructureParSet
        s.Cu0.x.setValue(0.456)
        s.Cu0.U22.setValue(0.441)
        s.Cu0.B13.setValue(0.550)
        d = dsstru.lattice.dist(a1.xyz, a2.xyz)
        s.lattice.b.setValue(4.6)
        s.lattice.alpha.setValue(91.3)
        _testAtoms()
        _testLattice()
        # Make sure the distance changed
        self.assertNotEqual(d, dsstru.lattice.dist(a1.xyz, a2.xyz))
        return
コード例 #29
0
ファイル: conftest.py プロジェクト: antonyvam/kikuchipy
def nickel_structure():
    """A diffpy.structure with a Nickel crystal structure."""
    return Structure(
        atoms=[Atom("Ni", [0, 0, 0])],
        lattice=Lattice(3.5236, 3.5236, 3.5236, 90, 90, 90),
    )
コード例 #30
0
    def expandSuperCell(self, mno):
        """Perform supercell expansion for this structure and adjust
        constraints for positions and lattice parameters.  New lattice
        parameters are multiplied and fractional coordinates divided by
        corresponding multiplier.  New atoms are grouped with their source
        in the original cell.

        mno -- tuple or list of three positive integer cell multipliers along
        the a, b, c axis
        """
        # check argument
        if tuple(mno) == (1, 1, 1):     return
        if min(mno) < 1:
            raise ControlValueError("mno must contain 3 positive integers")
        # back to business
        acd = self._popAtomConstraints()
        mnofloats = numpy.array(mno[:3], dtype=float)
        ijklist = [(i,j,k) for i in range(mno[0])
                    for j in range(mno[1]) for k in range(mno[2])]
        # build a list of new atoms
        newatoms = []
        for a in self.initial:
            for ijk in ijklist:
                adup = Atom(a)
                adup.xyz = (a.xyz + ijk)/mnofloats
                newatoms.append(adup)
                # does atom a have any constraint?
                if a not in acd:    continue
                # add empty constraint dictionary for duplicate atom
                acd[adup] = {}
                for barevar, con in acd[a].iteritems():
                    formula = con.formula
                    if barevar in ("x", "y", "z"):
                        symidx = "xyz".index(barevar)
                        if ijk[symidx] != 0:
                            formula += " + %i" % ijk[symidx]
                        if mno[symidx] > 1:
                            formula = "(%s)/%.1f" % (formula, mno[symidx])
                            formula = re.sub(r'\((@\d+)\)', r'\1', formula)
                    # keep other formulas intact and add constraint
                    # for barevar of the duplicate atom
                    acd[adup][barevar] = Constraint(formula)
        # replace original atoms with newatoms
        self.initial[:] = newatoms
        for ai, an in zip(self.initial, newatoms):
            if an in acd:
                acd[ai] = acd[an]
        # and rebuild their constraints
        self._restoreAtomConstraints(acd)
        # take care of lattice parameters
        self.initial.lattice.setLatPar(
                a=mno[0]*self.initial.lattice.a,
                b=mno[1]*self.initial.lattice.b,
                c=mno[2]*self.initial.lattice.c )
        # adjust lattice constraints if present
        latvars = ( "lat(1)", "lat(2)", "lat(3)" )
        for var, multiplier in zip(latvars, mno):
            if var in self.constraints and multiplier > 1:
                con = self.constraints[var]
                formula = "%.0f*(%s)" % (multiplier, con.formula)
                formula = re.sub(r'\((@\d+)\)', r'\1', formula)
                con.formula = formula
        return
コード例 #31
0
ファイル: conftest.py プロジェクト: onatlandsmyr/orix
        ("Lattice Constant gamma", "90.000"),
    ]:
        phase_group.create_dataset(name,
                                   data=np.array([data], dtype=np.dtype("S")))

    yield f
    gc.collect()


@pytest.fixture(params=[(
    ["a", "b", "c"],
    [229, 207, 143],
    ["m-3m", "432", "3"],
    ["r", "g", "b"],
    [Lattice()] * 3,
    [[Atom()]] * 3,
)])
def phase_list(request):
    names, space_groups, point_group_names, colors, lattices, atoms = request.param
    # Apparently diffpy.structure don't allow iteration over a list of lattices
    structures = [
        Structure(lattice=lattices[i], atoms=a) for i, a in enumerate(atoms)
    ]
    return PhaseList(
        names=names,
        space_groups=space_groups,
        point_groups=point_group_names,
        colors=colors,
        structures=structures,
    )
コード例 #32
0
ファイル: conftest.py プロジェクト: pyxem/diffsims
def default_structure():
    """An atomic structure represented using diffpy """
    latt = Lattice(3, 3, 5, 90, 90, 120)
    atom = Atom(atype="Ni", xyz=[0, 0, 0], lattice=latt)
    hexagonal_structure = Structure(atoms=[atom], lattice=latt)
    return hexagonal_structure
コード例 #33
0
    def testDiffpyStructureParSet(self):
        """Test the structure conversion."""

        a1 = Atom("Cu", xyz=numpy.array([.0, .1, .2]), Uisoequiv=0.003)
        a2 = Atom("Ag", xyz=numpy.array([.3, .4, .5]), Uisoequiv=0.002)
        l = Lattice(2.5, 2.5, 2.5, 90, 90, 90)

        dsstru = Structure([a1, a2], l)
        # Structure makes copies
        a1 = dsstru[0]
        a2 = dsstru[1]

        s = DiffpyStructureParSet("CuAg", dsstru)

        self.assertEqual(s.name, "CuAg")

        def _testAtoms():
            # Check the atoms thoroughly
            self.assertEqual(a1.element, s.Cu0.element)
            self.assertEqual(a2.element, s.Ag0.element)
            self.assertEqual(a1.Uisoequiv, s.Cu0.Uiso.getValue())
            self.assertEqual(a2.Uisoequiv, s.Ag0.Uiso.getValue())
            self.assertEqual(a1.Bisoequiv, s.Cu0.Biso.getValue())
            self.assertEqual(a2.Bisoequiv, s.Ag0.Biso.getValue())
            for i in range(1, 4):
                for j in range(i, 4):
                    uijstru = getattr(a1, "U%i%i" % (i, j))
                    uij = getattr(s.Cu0, "U%i%i" % (i, j)).getValue()
                    uji = getattr(s.Cu0, "U%i%i" % (j, i)).getValue()
                    self.assertEqual(uijstru, uij)
                    self.assertEqual(uijstru, uji)
                    bijstru = getattr(a1, "B%i%i" % (i, j))
                    bij = getattr(s.Cu0, "B%i%i" % (i, j)).getValue()
                    bji = getattr(s.Cu0, "B%i%i" % (j, i)).getValue()
                    self.assertEqual(bijstru, bij)
                    self.assertEqual(bijstru, bji)

            self.assertEqual(a1.xyz[0], s.Cu0.x.getValue())
            self.assertEqual(a1.xyz[1], s.Cu0.y.getValue())
            self.assertEqual(a1.xyz[2], s.Cu0.z.getValue())
            return

        def _testLattice():

            # Test the lattice
            self.assertEqual(dsstru.lattice.a, s.lattice.a.getValue())
            self.assertEqual(dsstru.lattice.b, s.lattice.b.getValue())
            self.assertEqual(dsstru.lattice.c, s.lattice.c.getValue())
            self.assertEqual(dsstru.lattice.alpha, s.lattice.alpha.getValue())
            self.assertEqual(dsstru.lattice.beta, s.lattice.beta.getValue())
            self.assertEqual(dsstru.lattice.gamma, s.lattice.gamma.getValue())

        _testAtoms()
        _testLattice()

        # Now change some values from the diffpy Structure
        a1.xyz[1] = 0.123
        a1.U11 = 0.321
        a1.B32 = 0.111
        dsstru.lattice.setLatPar(a=3.0, gamma=121)
        _testAtoms()
        _testLattice()

        # Now change values from the srfit DiffpyStructureParSet
        s.Cu0.x.setValue(0.456)
        s.Cu0.U22.setValue(0.441)
        s.Cu0.B13.setValue(0.550)
        d = dsstru.lattice.dist(a1.xyz, a2.xyz)
        s.lattice.b.setValue(4.6)
        s.lattice.alpha.setValue(91.3)
        _testAtoms()
        _testLattice()
        # Make sure the distance changed
        self.assertNotEqual(d, dsstru.lattice.dist(a1.xyz, a2.xyz))
        return