示例#1
0
 def test_mcif(self):
     m = Sample()
     load_mcif(m, os.path.join(self._stdir,'Cd2Os2O7.mcif'))
     m.add_muon([ float(x) for x in '0.125 0.125 0.125'.split() ])
     
     # distance is l(Os1-H) =  2.20122(0) Å
     r1 = locfield(m, 's',[1,1,1],2.3,4,2.3)
     r1[0].ACont = 1.
     
     # total field is 0
     np.testing.assert_array_almost_equal(r1[0].T,np.zeros(3),decimal=7)
     
     
     # distance to nnn is l(Os1-H) =  5.53962(0) Å
     r1 = locfield(m, 's',[3,3,3],5.54,4,2.3)
     r1[0].ACont = 1.
     
     # total field is 0
     np.testing.assert_array_almost_equal(r1[0].T,np.zeros(3),decimal=7)
     
     # now use a funny cell
     r1 = locfield(m, 's',[np.random.randint(3,10),np.random.randint(3,10),np.random.randint(3,10)],5.54,4,2.3)
     r1[0].ACont = 1.
     
     # total field is 0
     np.testing.assert_array_almost_equal(r1[0].T,np.zeros(3),decimal=7)
示例#2
0
    def test_symbolic_fourier_components(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir,'crys.xsf'))
        
        
        
        rand_k = np.random.rand(3)
        rand_real_fc = np.random.rand(3).reshape((1,3))+0.j # make array complex
        
        mm = MM(1)
        mm.k=np.array(rand_k)
        mm.fc_set(rand_real_fc)
        m.mm = mm
        
        
        m.add_muon([0.1,0.1,0.1])

        r = locfield(m, 's',[10,10,10],40)[0]

        if have_sympy:
            smm = SMM(1,"x,y,z")
            smm.k=np.array(rand_k)
            smm.set_symFC("[[x,y,z]]")
            smm.set_params(rand_real_fc[0].real.tolist())
    
            m.mm = smm
    
            r2 = locfield(m, 's',[10,10,10],40)[0]
    
            self.assertAlmostEqual( r.D[0], r2.D[0], places=10, msg=None, delta=None)
            self.assertAlmostEqual( r.D[1], r2.D[1], places=10, msg=None, delta=None)
            self.assertAlmostEqual( r.D[2], r2.D[2], places=7, msg=None, delta=None)           
示例#3
0
    def test_mcif(self):
        m = Sample()
        load_mcif(m, os.path.join(self._stdir, 'Cd2Os2O7.mcif'))
        m.add_muon([float(x) for x in '0.125 0.125 0.125'.split()])

        # distance is l(Os1-H) =  2.20122(0) Å
        r1 = locfield(m, 's', [1, 1, 1], 2.3, 4, 2.3)
        r1[0].ACont = 1.

        # total field is 0
        np.testing.assert_array_almost_equal(r1[0].T, np.zeros(3), decimal=7)

        # distance to nnn is l(Os1-H) =  5.53962(0) Å
        r1 = locfield(m, 's', [3, 3, 3], 5.54, 4, 2.3)
        r1[0].ACont = 1.

        # total field is 0
        np.testing.assert_array_almost_equal(r1[0].T, np.zeros(3), decimal=7)

        # now use a funny cell
        r1 = locfield(m, 's', [
            np.random.randint(3, 10),
            np.random.randint(3, 10),
            np.random.randint(3, 10)
        ], 5.54, 4, 2.3)
        r1[0].ACont = 1.

        # total field is 0
        np.testing.assert_array_almost_equal(r1[0].T, np.zeros(3), decimal=7)
示例#4
0
    def test_compare_ass_and_rass(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir, 'crys2.xsf'))
        mm = MM(9)
        mm.k = np.array(np.random.rand(3))
        mm.fc_set(
            (np.random.rand(27) + 1.j * np.random.rand(27)).reshape(9, 3))
        m.mm = mm
        m.add_muon(np.random.rand(3))
        m.add_muon(np.random.rand(3))
        r1 = locfield(m, 's', [10, 10, 10], 20)
        r2 = locfield(m, 'r', [10, 10, 10], 20, axis=[1, 1, 1], nangles=1)

        r1[0].ACont = 1.0
        r2[0].ACont = 1.0
        r1[1].ACont = 1.0
        r2[1].ACont = 1.0

        min_oom = min(self.oom(r1[0].T), self.oom(r2[0].T[0]))
        np.testing.assert_array_almost_equal(r1[0].T,
                                             r2[0].T[0],
                                             decimal=6 - min_oom)

        min_oom = min(self.oom(r1[1].T), self.oom(r2[1].T[0]))
        np.testing.assert_array_almost_equal(r1[1].T,
                                             r2[1].T[0],
                                             decimal=6 - min_oom)
示例#5
0
 def test_double_moment(self):
     m = Sample()
     load_xsf(m, os.path.join(self._stdir, 'crys.xsf'))
     mm = MM(1)
     mm.k = np.array([0., 0., 0.])
     mm.fc_set(np.array([[0. + 0j, 0., 1. + 0.j]]))
     m.mm = mm
     m.add_muon([0.1, 0.1, 0.1])
     r = locfield(m, 's', [1, 1, 1], 4)[0]
     m.mm.fc_set(np.array([[0. + 0j, 0. + 0.j, 2. + 0.j]]))
     r2 = locfield(m, 's', [1, 1, 1], 4)[0]
     # r should be: [0 tesla, 11.4226 milliteslas, 11.4226 milliteslas]
     #
     #    (magnetic_constant/4pi)⋅((1/(1angstrom⋅sqrt(2.5^2+2.5^2+2.5^2)))^3)⋅(3⋅(1 bohr_magneton)⋅cos(atan(sqrt(2)))⋅([1,1,1]/sqrt(3))−1bohr_magneton⋅[1,0,0])
     #
     #
     self.assertAlmostEqual(r.D[0],
                            0.5 * r2.D[0],
                            places=10,
                            msg=None,
                            delta=None)
     self.assertAlmostEqual(r.D[1],
                            0.5 * r2.D[1],
                            places=10,
                            msg=None,
                            delta=None)
     self.assertAlmostEqual(r.D[2],
                            0.5 * r2.D[2],
                            places=7,
                            msg=None,
                            delta=None)
示例#6
0
    def test_compare_rass_and_incass(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir,'crys.xsf'))
        mm = MM(1)
        # define three orthogonal vectors
        rp1 = np.random.rand(3)   # used for k
        r2 = np.random.rand(3)
        rp2 = np.cross(rp1,r2)
        rp3 = np.cross(rp1,rp2)
        
        # normalize a and b vectors
        rp2 /= np.linalg.norm(rp2)
        rp3 /= np.linalg.norm(rp3)
        
        #chose a random value for stag moment
        stm = np.random.ranf()*10.
        rp2 *= stm
        rp3 *= stm
        
        mm.k=np.array(rp1)
        mm.fc_set((rp2+1.j*rp3).reshape(1,3))
        m.mm = mm
        m.add_muon(np.random.rand(3))
        m.add_muon(np.random.rand(3))
        r1 = locfield(m, 's',[50,50,50],50)
        r2 = locfield(m, 'r',[50,50,50],50,nangles=1200,axis=rp1)
        r3 = locfield(m, 'i',[50,50,50],50,nangles=1200)

        r1[0].ACont = 1.0
        r2[0].ACont = 1.0
        r3[0].ACont = 1.0
        r1[1].ACont = 1.0
        r2[1].ACont = 1.0
        r3[1].ACont = 1.0
        
        min_oom = min(self.oom(r1[0].T), self.oom(r2[0].T[0]))
        np.testing.assert_array_almost_equal(r1[0].T,r2[0].T[0],decimal=7-min_oom)
        min_oom = min(self.oom(r1[1].T), self.oom(r2[1].T[0]))
        np.testing.assert_array_almost_equal(r1[1].T,r2[1].T[0],decimal=7-min_oom)
        
        r2_norms = np.apply_along_axis(np.linalg.norm, 1, r2[0].D)
        r3_norms = np.apply_along_axis(np.linalg.norm, 1, r3[0].D)
        
        min_oom=min(self.oom(np.max(r2_norms)), self.oom(np.max(r3_norms)))
        np.testing.assert_array_almost_equal(np.max(r2_norms),np.max(r3_norms),decimal=4-min_oom)
        
        min_oom=min(self.oom(np.min(r2_norms)), self.oom(np.min(r3_norms)))
        np.testing.assert_array_almost_equal(np.min(r2_norms),np.min(r3_norms),decimal=4-min_oom)

        r2_norms = np.apply_along_axis(np.linalg.norm, 1, r2[1].T)
        r3_norms = np.apply_along_axis(np.linalg.norm, 1, r3[1].T)
        
        min_oom=min(self.oom(np.max(r2_norms)), self.oom(np.max(r3_norms)))
        np.testing.assert_array_almost_equal(np.max(r2_norms),np.max(r2_norms),decimal=5-min_oom)
        
        min_oom=min(self.oom(np.min(r2_norms)), self.oom(np.min(r3_norms)))
        np.testing.assert_array_almost_equal(np.min(r3_norms),np.min(r3_norms),decimal=5-min_oom)
示例#7
0
 def test_mcif2(self):
     m = Sample()
     load_mcif(m, os.path.join(self._stdir,'ScMnO3.mcif'))
     m.add_muon( [float(x) for x in '0.66666666 0.33333333 0.25'.split()])
     
     # No contact
     r1 = locfield(m, 's',[np.random.randint(10,14),np.random.randint(10,14),np.random.randint(10,14)],22,4,0.3)
     r1[0].ACont = 1.
     
     # total field is 0
     np.testing.assert_array_almost_equal(r1[0].T,np.zeros(3),decimal=7)
示例#8
0
 def test_one_dipole_outside(self):
     m = Sample()
     load_xsf(m, os.path.join(self._stdir,'crys.xsf'))
     mm = MM(1)
     mm.k=np.array([0.,0.,0.])
     mm.fc_set(np.array([[1.+0j,0.+1.j,0.+1.j]]))
     m.mm = mm
     m.add_muon([0.5,0.5,0.5])
     # the diagonal is 8.6603
     r = locfield(m, 's',[1,1,1],8.66/2.)[0]
     self.assertEqual( np.sum(np.abs(r.D)), 0.)
示例#9
0
 def test_one_dipole_outside(self):
     m = Sample()
     load_xsf(m, os.path.join(self._stdir, 'crys.xsf'))
     mm = MM(1)
     mm.k = np.array([0., 0., 0.])
     mm.fc_set(np.array([[1. + 0j, 0. + 1.j, 0. + 1.j]]))
     m.mm = mm
     m.add_muon([0.5, 0.5, 0.5])
     # the diagonal is 8.6603
     r = locfield(m, 's', [1, 1, 1], 8.66 / 2.)[0]
     self.assertEqual(np.sum(np.abs(r.D)), 0.)
示例#10
0
    def test_rotation(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir,'crys3.xsf'))
        mm = MM(1)
        mm.k=np.array([0.,0.,0.])
        mm.fc_set(np.array([[0.+0j,1.+0.j,0.+0.j]]))
        m.mm = mm
        m.add_muon([0.0,0.001,0.0])
        r = locfield(m, 'r',[1,1,1],1.2,nnn=0,nangles=300,axis=[1,0,0])[0]

        # r for angle = 0 should be: [0 T, 1.8548 T, 0 T]
        #
        #    (magnetic_constant/4pi)⋅((1/(1angstrom⋅sqrt(1^2)))^3)⋅(3⋅(1 bohr_magneton)⋅cos(0)⋅([0,1,0]/sqrt(1))−1bohr_magneton⋅[0,1,0])
        #
        #
        # r for angle = 90 should be: [0 T, 0 T, −0.927401 T]
        # 
        #    (magnetic_constant/4pi)⋅((1/(1angstrom⋅sqrt(1^2)))^3)⋅(3⋅(1 bohr_magneton)⋅cos(pi/2)⋅([0,1,0]/sqrt(1))−1bohr_magneton⋅[0,0,1])
        #
        # Opposite moments produce opposite fields. 150 is half of 300
        np.testing.assert_array_almost_equal(r.D[0],-r.D[150],decimal=7)
        np.testing.assert_array_almost_equal(r.D[0],np.array([0., 1.8548018,0.]),decimal=7)
        np.testing.assert_array_almost_equal(r.D[75],np.array([0., 0,-0.9274009]),decimal=6)
        
        rnorms = np.apply_along_axis(np.linalg.norm,1,r.T-r.L)
        self.assertAlmostEqual( np.min(rnorms), 0.9274009 ,places=6, msg=None, delta=None)
        self.assertAlmostEqual( np.max(rnorms), 1.8548018 ,places=6, msg=None, delta=None)

        r = locfield(m, 'r',[5,1,1],1.5,nnn=0,nangles=300,axis=[1,0,0])[0]
        np.testing.assert_array_almost_equal(r.D[0],-r.D[150],decimal=7)
        np.testing.assert_array_almost_equal(r.D[0],np.array([0., 2.18268753,0.]),decimal=7)
        np.testing.assert_array_almost_equal(r.D[75],np.array([0., 0,-1.58317237]),decimal=6)
        
        rnorms = np.apply_along_axis(np.linalg.norm,1,r.T-r.L)
        self.assertAlmostEqual( np.min(rnorms), 1.58317237 ,places=6, msg=None, delta=None)
        self.assertAlmostEqual( np.max(rnorms), 2.18268753 ,places=6, msg=None, delta=None)
        
        # Now test incomm
        mm = MM(1)
        mm.k=np.array([0.,0.,0.])
        mm.fc_set(np.array([[0.+0j,1.+0.j,0.+1.j]]))
        m.mm = mm
        i = locfield(m, 'i',[1,1,1],1.2,nnn=0,nangles=300)[0]
        
        inorms = np.apply_along_axis(np.linalg.norm,1,i.T-i.L)
        
        self.assertAlmostEqual( np.min(inorms), 0.9274009 ,places=6, msg=None, delta=None)
        self.assertAlmostEqual( np.max(inorms), 1.8548018 ,places=6, msg=None, delta=None)
        
        i = locfield(m, 'i',[5,1,1],1.5,nnn=0,nangles=300)[0]
        
        rnorms = np.apply_along_axis(np.linalg.norm,1,i.T-i.L)
        self.assertAlmostEqual( np.min(rnorms), 1.58317237 ,places=6, msg=None, delta=None)
        self.assertAlmostEqual( np.max(rnorms), 2.18268753 ,places=6, msg=None, delta=None)        
示例#11
0
    def test_mcif2(self):
        m = Sample()
        load_mcif(m, os.path.join(self._stdir, 'ScMnO3.mcif'))
        m.add_muon([float(x) for x in '0.66666666 0.33333333 0.25'.split()])

        # No contact
        r1 = locfield(m, 's', [
            np.random.randint(10, 14),
            np.random.randint(10, 14),
            np.random.randint(10, 14)
        ], 22, 4, 0.3)
        r1[0].ACont = 1.

        # total field is 0
        np.testing.assert_array_almost_equal(r1[0].T, np.zeros(3), decimal=7)
示例#12
0
    def test_one_dipole_inside(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir, 'crys.xsf'))
        mm = MM(1)
        mm.k = np.array([0., 0., 0.])
        mm.fc_set(np.array([[1. + 0j, 0. + 0.j, 0. + 0.j]]))
        m.mm = mm
        m.add_muon([0.5, 0.5, 0.5])
        r = locfield(m, 's', [1, 1, 1], 8.67 / 2.)[0]

        # BDip should be: [0 tesla, 11.4226 milliteslas, 11.4226 milliteslas]
        #
        #    (magnetic_constant/4pi)⋅((1/(1angstrom⋅sqrt(2.5^2+2.5^2+2.5^2)))^3)⋅(3⋅(1 bohr_magneton)⋅cos(atan(sqrt(2)))⋅([1,1,1]/sqrt(3))−1bohr_magneton⋅[1,0,0])
        #
        # BLor should be: [ 0.01138414 T, 0 , 0 ]
        #
        #    0.3333333333⋅magnetic_constant (1 bohr_magneton)/((4/3)pi(angstrom 8.67/2.)^3)
        #
        # BCont should be (Assuming ACont = 1 AA^-3 )
        #
        #	 (2/3)⋅magnetic_constant (1 bohr_magneton)⋅(1angstrom^−3) = 7.769376 T
        #

        self.assertAlmostEqual(r.D[0], 0., places=7, msg=None, delta=None)
        self.assertAlmostEqual(r.D[1], r.D[2], places=10, msg=None, delta=None)
        self.assertAlmostEqual(r.D[1],
                               11.4226e-3,
                               places=7,
                               msg=None,
                               delta=None)

        self.assertAlmostEqual(r.L[0],
                               0.01138414,
                               places=7,
                               msg=None,
                               delta=None)
        self.assertAlmostEqual(r.L[1], 0.0, places=7, msg=None, delta=None)
        self.assertAlmostEqual(r.L[2], 0.0, places=7, msg=None, delta=None)

        r.ACont = 1.  # Ang^-3

        self.assertAlmostEqual(r.C[0],
                               7.769376,
                               places=7,
                               msg=None,
                               delta=None)
        self.assertAlmostEqual(r.C[1], 0.0, places=7, msg=None, delta=None)
        self.assertAlmostEqual(r.C[2], 0.0, places=7, msg=None, delta=None)
示例#13
0
 def test_cubic_sym1(self):
     m = Sample()
     load_xsf(m, os.path.join(self._stdir,'crys.xsf'))
     mm = MM(1)
     mm.k=np.array([0.,0.,0.])
     mm.fc_set(np.array([[1.+0j,0.+0.j,0.+0.j]]))
     m.mm = mm
     m.add_muon([0.5,0.5,0.5])
     r = locfield(m, 's',[100,100,100],240)[0]
     # Bdip should be: [0 tesla, 11.4226 milliteslas, 11.4226 milliteslas]
     #
     #    (magnetic_constant/4pi)⋅((1/(1angstrom⋅sqrt(2.5^2+2.5^2+2.5^2)))^3)⋅(3⋅(1 bohr_magneton)⋅cos(atan(sqrt(2)))⋅([1,1,1]/sqrt(3))−1bohr_magneton⋅[1,0,0])
     #
     #
     self.assertAlmostEqual( r.D[0], r.D[1],places=10, msg=None, delta=None)
     self.assertAlmostEqual( r.D[0], r.D[2], places=10, msg=None, delta=None)
     self.assertAlmostEqual( r.D[0], 0., places=7, msg=None, delta=None)    
示例#14
0
    def test_mcif3(self):
        m = Sample()
        load_mcif(m, os.path.join(self._stdir,'LiFeSO4F.mcif'))
        muon_set_frac(m, '0.25 0.25 0.25')
        
        # symmetry null
        r1 = locfield(m, 's',[np.random.randint(10,14),np.random.randint(10,14),np.random.randint(10,14)],22,4,10.)
        r1[0].ACont = 1.
        
        # total field is 0
        np.testing.assert_array_almost_equal(r1[0].T,np.zeros(3),decimal=7)      
        
        muon_reset(m)
        m.add_muon([float(x) for x in '0.15990  0.17820  0.14580'.split()])  # position of O3

        # one atom, distance is 2.14251 AA
        #  dipolar field should be:
        #
        #       def bfield(r,m):
        #           return 0.9274009*(3*r*np.dot(r,m)/(np.linalg.norm(r)**5)-m/(np.linalg.norm(r)**3))
        #       bfield(np.array([1.07574,1.59328,0.945826]),np.array([-1.70376,3.14961,-1.22045])) 
        #
        r1 = locfield(m, 's',[np.random.randint(1,4),np.random.randint(1,4),np.random.randint(1,4)],2.2,1,2.14251+20.*np.random.ranf())
        r1[0].ACont = 1.

        np.testing.assert_array_almost_equal(r1[0].D,np.array([0.29531083,  -0.09756855, 0.23347458]),decimal=6) 
        
        # contact field is (2/3)⋅magnetic_constant ([-1.70376 bohr_magneton ,3.14961bohr_magneton,-1.22045bohr_magneton])⋅(1angstrom^−3) =
        #   [-13.2372 T, 24.4705 T, -9.48213 T]
        
        np.testing.assert_array_almost_equal(r1[0].C,np.array([-13.2372 , 24.4705 , -9.48213]),decimal=4) 
        
        
        r2 = locfield(m, 's',[np.random.randint(3,5),np.random.randint(3,5),np.random.randint(3,5)],4.2,3,5.+20.*np.random.ranf())
        r2[0].ACont = 1.14299 # effective interaction increased since more nnn involved in acont
                                # still only 14% more
        
        # three atoms, distances are 2.14251 AA, 4.191093 AA, 4.19413AA
        #
        #      bfield(np.array([1.07574,1.59328,0.945826]),np.array([-1.70376,3.14961,-1.22045])) + \
        #      bfield(np.array([2.14396,2.77751,-2.29775]),np.array([1.70376,-3.14961,1.22045])) + \
        #      bfield(np.array([-2.28034,-2.66189,-2.29775]),np.array([1.70376,-3.14961,1.22045]))        
        
        np.testing.assert_array_almost_equal(r2[0].D,np.array([ 0.20781014, -0.07504131,  0.23329355]),decimal=6)
示例#15
0
    def test_symbolic_fourier_components(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir, 'crys.xsf'))

        rand_k = np.random.rand(3)
        rand_real_fc = np.random.rand(3).reshape(
            (1, 3)) + 0.j  # make array complex

        mm = MM(1)
        mm.k = np.array(rand_k)
        mm.fc_set(rand_real_fc)
        m.mm = mm

        m.add_muon([0.1, 0.1, 0.1])

        r = locfield(m, 's', [10, 10, 10], 40)[0]

        if have_sympy:
            smm = SMM(1, "x,y,z")
            smm.k = np.array(rand_k)
            smm.set_symFC("[[x,y,z]]")
            smm.set_params(rand_real_fc[0].real.tolist())

            m.mm = smm

            r2 = locfield(m, 's', [10, 10, 10], 40)[0]

            self.assertAlmostEqual(r.D[0],
                                   r2.D[0],
                                   places=10,
                                   msg=None,
                                   delta=None)
            self.assertAlmostEqual(r.D[1],
                                   r2.D[1],
                                   places=10,
                                   msg=None,
                                   delta=None)
            self.assertAlmostEqual(r.D[2],
                                   r2.D[2],
                                   places=7,
                                   msg=None,
                                   delta=None)
示例#16
0
    def test_compare_ass_and_rass(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir,'crys2.xsf'))
        mm = MM(9)
        mm.k=np.array(np.random.rand(3))
        mm.fc_set((np.random.rand(27)+1.j*np.random.rand(27)).reshape(9,3))
        m.mm = mm
        m.add_muon(np.random.rand(3))
        m.add_muon(np.random.rand(3))
        r1 = locfield(m, 's',[10,10,10],20)
        r2 = locfield(m, 'r',[10,10,10],20,axis=[1,1,1],nangles=1)

        r1[0].ACont = 1.0
        r2[0].ACont = 1.0
        r1[1].ACont = 1.0
        r2[1].ACont = 1.0
        
        min_oom = min(self.oom(r1[0].T), self.oom(r2[0].T[0]))
        np.testing.assert_array_almost_equal(r1[0].T,r2[0].T[0],decimal=6-min_oom)
        
        min_oom = min(self.oom(r1[1].T), self.oom(r2[1].T[0]))
        np.testing.assert_array_almost_equal(r1[1].T,r2[1].T[0],decimal=6-min_oom)
示例#17
0
 def test_one_dipole_inside(self):
     m = Sample()
     load_xsf(m, os.path.join(self._stdir,'crys.xsf'))
     mm = MM(1)
     mm.k=np.array([0.,0.,0.])
     mm.fc_set(np.array([[1.+0j,0.+0.j,0.+0.j]]))
     m.mm = mm
     m.add_muon([0.5,0.5,0.5])
     r = locfield(m,'s',[1,1,1],8.67/2.)[0]
     
     # BDip should be: [0 tesla, 11.4226 milliteslas, 11.4226 milliteslas]
     #
     #    (magnetic_constant/4pi)⋅((1/(1angstrom⋅sqrt(2.5^2+2.5^2+2.5^2)))^3)⋅(3⋅(1 bohr_magneton)⋅cos(atan(sqrt(2)))⋅([1,1,1]/sqrt(3))−1bohr_magneton⋅[1,0,0])
     #
     # BLor should be: [ 0.01138414 T, 0 , 0 ]
     #
     #    0.3333333333⋅magnetic_constant (1 bohr_magneton)/((4/3)pi(angstrom 8.67/2.)^3)
     #
     # BCont should be (Assuming ACont = 1 AA^-3 )
     #
     #	 (2/3)⋅magnetic_constant (1 bohr_magneton)⋅(1angstrom^−3) = 7.769376 T
     #
     
     self.assertAlmostEqual( r.D[0], 0.,places=7, msg=None, delta=None)
     self.assertAlmostEqual( r.D[1], r.D[2], places=10, msg=None, delta=None)
     self.assertAlmostEqual( r.D[1], 11.4226e-3, places=7, msg=None, delta=None)
     
     self.assertAlmostEqual( r.L[0], 0.01138414  ,places=7, msg=None, delta=None)
     self.assertAlmostEqual( r.L[1], 0.0  ,places=7, msg=None, delta=None)
     self.assertAlmostEqual( r.L[2], 0.0  ,places=7, msg=None, delta=None)
     
     r.ACont = 1. # Ang^-3
     
     self.assertAlmostEqual( r.C[0], 7.769376  ,places=7, msg=None, delta=None)
     self.assertAlmostEqual( r.C[1], 0.0  ,places=7, msg=None, delta=None)
     self.assertAlmostEqual( r.C[2], 0.0  ,places=7, msg=None, delta=None)
示例#18
0
from muesr.engines.clfc import locfield                # Does the sum and returns the local field in its diff. contributions
from muesr.engines.clfc import find_largest_sphere     # Aids in the calculation of the sphere's radius for the lattice sum.
from muesr.utilities.muon import muon_find_equiv       # For finding and including the symmetry equivalent muon positions in the calculation 

head,tail = os.path.split(os.path.realpath(__file__))
print("working from "+head)

#
np.set_printoptions(suppress=True,precision=5)

#    Declare  and load sample 
fe= Sample()                          
load_cif(fe, os.path.join(head,'Cifs','1534895.cif'))

#    To add the muon position
fe.add_muon([0.50,0.25,0.0])    


#   Finds and includes the symmetry equivalent positions of the above defined muon.
#   For this example there are 12 sites "print (fe.muons)" will show their positions.
muon_find_equiv(fe)  


#   Description of the propagation vector k and fourier components fc 
#   with a new magnetic structure declared with fe.new_mm()
fe.new_mm()     
fe.mm.k=np.array([0.0,0.0,0.0])
fe.mm.fc= np.array([[0.0+0.j, 0.0+0.j, 2.2+0.j],
                                      [0.0+0.j, 0.0+0.j, 2.2+0.j],
                                        [0.0+0.j, 0.0+0.j, 2.2+0.j],
                                        [0.0+0.j, 0.0+0.j, 2.2+0.j]])
示例#19
0
class TestSample(unittest.TestCase):
 
    def setUp(self):
        self._sample = Sample()
        
    def _set_a_cell(self):
        self._sample.cell = Atoms(symbols=['Co'],
                                  scaled_positions=[[0,0,0]],
                                  cell=[[3.,0,0],
                                        [0,3.,0],
                                        [0,0,3.]])
    def test_set_attribute(self):
        with self.assertRaises(TypeError):
            self._sample.blabla = 1
        
        
    def test_name_property(self):
        
        self.assertEqual(self._sample.name,"No name")
        
        self._sample.name = "test"
        
        self.assertEqual(self._sample.name,"test")
        
        #must be str or unicode
        with self.assertRaises(TypeError):
            self._sample.name = 1
            
        self.assertEqual(self._sample.name,"test")
        
        # test unicode
        self._sample.name = u"àèé"
        
    
    def test_muons_property(self):
        self._sample._reset(cell=True,muon=True,sym=True,magdefs=True)
        self._set_a_cell()
        
        with self.assertRaises(MuonError):
            self._sample.muons
            
        
        
        
    def test_add_muon_property(self):
        self._sample._reset(cell=True,muon=True,sym=True,magdefs=True)

        with self.assertRaises(CellError):
            self._sample.add_muon([0,0,0])
            
        self._set_a_cell()
        
        with self.assertRaises(TypeError):
            self._sample.add_muon('0 0 0')
            
        with self.assertRaises(ValueError):
            self._sample.add_muon([0,0,0,0])
        with self.assertRaises(ValueError):
            self._sample.add_muon(np.array([0,0,0,0]))
        
        self._sample.add_muon([0,0,0])
        np.testing.assert_array_equal(self._sample.muons[0], np.zeros(3))
        
        self._sample.add_muon([1,1,1])
        np.testing.assert_array_equal(self._sample.muons[1], np.ones(3))
        
        self._sample.add_muon([1,1,1], cartesian=True)
        np.testing.assert_array_equal(self._sample.muons[2], np.ones(3)/3.)
        
        a = 4.0  # some lattice constant
        b = a / 2
        self._sample.cell = Atoms(symbols=['Au'],
                                  positions=[0,0,0],
                                  cell=[(0, b, b), (b, 0, b), (b, b, 0)],
                                  pbc=True)
        
        self._sample.add_muon([1.,1.,1.], cartesian=True)
        np.testing.assert_array_equal(self._sample.muons[3], np.ones(3)/4.)
        
        self._sample.add_muon([.5,.5,.5], cartesian=False)
        self._sample.add_muon([2.,2.,2.], cartesian=True)
        np.testing.assert_array_equal(self._sample.muons[4], self._sample.muons[5])
        
        
    
    def test_mm_property(self):
        self._sample._reset(cell=True,magdefs=True,muon=True,sym=True)
        
        with self.assertRaises(MagDefError):
            self._sample.mm

        with self.assertRaises(CellError):
            self._sample.mm = MM(19) # randomly large number
                    
        
        self._sample._reset(magdefs=True)
        self._set_a_cell()
        with self.assertRaises(TypeError):
            self._sample.mm = 1
            
        self._sample._reset(magdefs=True, cell=True, muon=True, sym=True)
        self._sample.cell = Atoms(symbols=['C'],
                                  scaled_positions=[[0,0,0]],
                                  cell=[[3.,0,0],
                                        [0,3.,0],
                                        [0,0,3.]])
                                        
        with self.assertRaises(MagDefError):
            self._sample.mm = MM(198) # randomly large number        
            
        self._sample.mm = MM(1)
        

    def test_new_mm(self):
        self._sample._reset(magdefs=True, cell=True, muon=True, sym=True)
        with self.assertRaises(CellError):
            self._sample.new_mm()
        
        self._set_a_cell()
                                        
        self._sample.new_mm()            
        self.assertTrue(isinstance(self._sample.mm, MM))
        self.assertEqual(len(self._sample.mm.fc), 1)
        
        
    
    def test_new_smm(self):
        if have_sympy:
            self._sample._reset(magdefs=True, cell=True, muon=True, sym=True)
            with self.assertRaises(CellError):
                self._sample.new_smm("x,y,z")
            
            # TODO TESTING
        else:
            pass
            
    def test_current_mm_idx_property(self):
        self._sample._reset(magdefs=True, cell=True,muon=True, sym=True)
        self._sample.cell = Atoms(symbols=['C'],
                                  scaled_positions=[[0,0,0]],
                                  cell=[[3.,0,0],
                                        [0,3.,0],
                                        [0,0,3.]])        
        
        self._sample.new_mm()
        self._sample.mm.k=np.array([0,0,1.])
        self.assertEqual(self._sample.current_mm_idx,0)
        self._sample.new_mm()
        self._sample.mm.k=np.array([0,0,2.])
        self.assertEqual(self._sample.current_mm_idx,1)
        self._sample.new_mm()
        self._sample.mm.k=np.array([0,0,3.])
        self.assertEqual(self._sample.current_mm_idx,2)
        
        self._sample.current_mm_idx = 0
        self.assertEqual(self._sample.current_mm_idx,0)
        np.testing.assert_array_equal(self._sample.mm.k, np.array([0,0,1.]))
        
        with self.assertRaises(IndexError):
            self._sample.current_mm_idx = 3

        with self.assertRaises(IndexError):
            self._sample.current_mm_idx = -1

            
        self.assertEqual(self._sample.current_mm_idx,0)

        
    def test_sym_property(self):
        
        self._sample._reset(cell=True,muon=True,sym=True,magdefs=True)
        
        with self.assertRaises(SymmetryError):
            self._sample.sym
            
        with self.assertRaises(TypeError):
            self._sample.sym = 1
            
        self._sample.sym = Spacegroup(113)
        
        self.assertEqual(self._sample.sym.no,113)
        self.assertEqual(self._sample.sym.setting,1)
        

    def test_cell_property(self): 
        #needs better testing
        with self.assertRaises(CellError):
            self._sample.cell
            
        with self.assertRaises(TypeError):
            self._sample.cell = 1
            
        self._set_a_cell()
        current_cell = self._sample.cell
        self.assertEqual(current_cell.get_chemical_symbols(),['Co'])
        current_cell.set_chemical_symbols(['Co'])
        self.assertEqual(current_cell.get_chemical_symbols(),['Co'])

    def test_reset(self):
        
        # test cell reset
        with warnings.catch_warnings(record=True) as w:
            # Cause all warnings to always be triggered.
            warnings.simplefilter("always")
            self._sample._reset(cell=True)
            assert len(w) == 3
            for wi in w:
                assert issubclass(wi.category, RuntimeWarning)
                
        self.assertEqual(self._sample._cell, None)
        with self.assertRaises(CellError):
            self._sample.cell
        
        # test magdef reset    
        self._sample._reset(magdefs=True)
        self.assertEqual(self._sample._magdefs, [])
        self.assertEqual(self._sample._selected_mm, -1)
        with self.assertRaises(MagDefError):
            self._sample.mm
            
        # test muon reset
        self._set_a_cell()
        self._sample.add_muon([0,1.,2])
        self._sample._reset(muon=True)
        self.assertEqual(self._sample._muon, [])
        with self.assertRaises(MuonError):
            self._sample.muons
        
        self._sample._reset(cell=True,muon=True,sym=True,magdefs=True)
            
        #test symmetry reset
        self._sample.sym = Spacegroup(113)
        self._sample._reset(sym=True)
        self.assertEqual(self._sample._sym, None)
        with self.assertRaises(SymmetryError):
            self._sample.sym
            
                       

    # TODO
    def test_check_sym(self):
        self._sample._reset(cell=True,muon=True,sym=True,magdefs=True)
        
        with self.assertRaises(SymmetryError):
            self._sample._check_sym()
        
        # vary bad from user side
        self._sample._sym = 1
        with self.assertRaises(SymmetryError):
            self._sample._check_sym()
        
        self._sample.sym = Spacegroup(113)
        self.assertTrue(self._sample._check_sym())
        
    def test_check_lattice(self):
        self._sample._reset(cell=True,muon=True,sym=True,magdefs=True)
        
        with self.assertRaises(CellError):
            self._sample._check_lattice()
        
        self._set_a_cell()
        self.assertTrue(self._sample._check_lattice())
        self._sample._cell = 1
        with self.assertRaises(CellError):
            self._sample._check_lattice()
        
            
        
    def test_check_magdefs(self):
        self._sample._reset(cell=True,muon=True,sym=True,magdefs=True)
        
        with self.assertRaises(MagDefError):
            self._sample._check_magdefs()
            
        self._set_a_cell()
        self._sample.new_mm()
        self.assertTrue(self._sample._check_magdefs())
        
        self._sample._magdefs = 1
        with self.assertRaises(MagDefError):
            self._sample._check_magdefs()        
        
        
    def test_check_muon(self):
        self._sample._reset(cell=True,muon=True,sym=True,magdefs=True)
        
        with self.assertRaises(MuonError):
            self._sample._check_muon()

        self._set_a_cell()
        self._sample.add_muon(np.zeros(3))
        self.assertTrue(self._sample._check_muon())
        
        self._sample.add_muon(np.zeros(3))
        self._sample._muon[1] = 'a'
        with self.assertRaises(MuonError):
            self._sample._check_muon()        
示例#20
0
文件: sampleIO.py 项目: bonfus/muesr
def load_sample(filename="", fileobj=None):

    """
    This function load a sample from a file in YAML format.
        
    :param str filename: the filename used to store data.
    :param file fileobj: an optional file object. If specified, this
                         supersede the filename input.
    :return: a sample object
    :rtype: :py:class:`~Sample` object or None
    :raises: ValueError, FileNotFoundError, IsADirectoryError
    
    """      
    
    # fail if YAML is not available
    if not have_yaml:
        warnings.warn("Warning, YAML python package not present!")
        return
    
    sample = Sample()
    
    data = {}
    if fileobj is None:
        if filename == "":
            raise ValueError("Specify filename or File object")
        with open(filename,'r') as f:
            data = load(f, Loader=Loader)
    else:
        data = load(fileobj, Loader=Loader)

    if not(type(data) is dict):
        raise ValueError('Invalid data file. (problems with YAML?)')

    
    if data is None:
        raise ValueError('Invalid/empty data file. (problems with YAML?)')
    
    if 'Name' in data.keys():
        sample.name = str(data['Name'])
    
    if 'Lattice' in data.keys():
        l = data['Lattice']
        
        spos = None
        cpos = None
        if 'ScaledPositions' in l.keys():
            spos = np.array(l['ScaledPositions'])
        elif 'CartesianPositions' in l.keys():
            cpos = np.array(l['CartesianPositions'])
        
        cell = None
        if 'Cell' in l.keys():
            cell = np.array(l['Cell'])
            
        symbols = None
        if 'Symbols' in l.keys():
            symbols = l['Symbols']
        
        if (cell is None) or (symbols is None):
            warnings.warn('Cell not loaded!', RuntimeWarning)
        else:
            if not spos is None:
                sample.cell = Atoms(symbols = symbols, scaled_positions = spos, cell=cell, pbc=True)
            elif not cpos is None:
                sample.cell = Atoms(symbols = symbols, positions = cpos, cell=cell, pbc=True)
            else:
                warnings.warn('Cell not loaded!', RuntimeWarning)

    else:
        warnings.warn('Cell not loaded!', RuntimeWarning)

            
    if 'Muon' in data.keys():
        m = data['Muon']
        if 'Positions' in m:
            for p in m['Positions']:
                sample.add_muon(p)
        else:
            warnings.warn('Muon positions not loaded!', RuntimeWarning)
    else:
        warnings.warn('Muon positions not loaded!', RuntimeWarning)
                
    if 'Symmetry' in data.keys():
        s = data['Symmetry']
        
        if ('Number' in s.keys()) and \
            ('Symbol' in s.keys()) and \
            ('Rotations' in s.keys()) and \
            ('Translations' in s.keys()):
            sample.sym = spacegroup_from_data(s['Number'],s['Symbol'],
                                            rotations=np.array(s['Rotations']),
                                            translations=np.array(s['Translations'])) 
        else:
            warnings.warn('Symmetry not loaded.', RuntimeWarning)
    else:
        warnings.warn('Symmetry not loaded!', RuntimeWarning)
            
    if 'MagneticOrders' in data.keys():
        m = data['MagneticOrders']
        
        if len(m) > 0:
        
            msize = int(m['Size'])
    
            for mo in m['Orders']:
                
                if 'lattice' in mo.keys():                
                    n = MM(msize, \
                            np.array(mo['lattice']))
                else:
                    n = MM(msize)
                
                sample.mm = n
                sample.mm.k = np.array(mo['k'])
                sample.mm.phi = np.array(mo['phi'])
                
                if 'desc' in mo.keys():
                    sample.mm.desc = str(mo['desc'])
                
                rfcs, ifcs = np.hsplit(np.array(mo['fc']),2)
                
            
                if mo['format'].lower() in ['bohr-cartesian', 'b-c']:
                    sample.mm.fcCart=(rfcs + 1.j*ifcs)
                    
                elif mo['format'].lower() in ['bohr/angstrom-lattic', 'b/a-l']:
                    sample.mm.fcLattBMA=(rfcs + 1.j*ifcs)
                    
                elif mo['format'].lower() in ['bohr-lattice','b-l']:
                    sample.mm.fcLattBM=(rfcs + 1.j*ifcs)
                    
                else:
                    raise ValueError('Invalid Fourier Components format specifier in YAML file.')
        else:
            warnings.warn('Magnetic definitions not loaded!', RuntimeWarning)
    else:
        warnings.warn('Magnetic definitions not loaded!', RuntimeWarning)
                
    return sample
示例#21
0
    def test_compare_rass_and_incass(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir, 'crys.xsf'))
        mm = MM(1)
        # define three orthogonal vectors
        rp1 = np.random.rand(3)  # used for k
        r2 = np.random.rand(3)
        rp2 = np.cross(rp1, r2)
        rp3 = np.cross(rp1, rp2)

        # normalize a and b vectors
        rp2 /= np.linalg.norm(rp2)
        rp3 /= np.linalg.norm(rp3)

        #chose a random value for stag moment
        stm = np.random.ranf() * 10.
        rp2 *= stm
        rp3 *= stm

        mm.k = np.array(rp1)
        mm.fc_set((rp2 + 1.j * rp3).reshape(1, 3))
        m.mm = mm
        m.add_muon(np.random.rand(3))
        m.add_muon(np.random.rand(3))
        r1 = locfield(m, 's', [50, 50, 50], 50)
        r2 = locfield(m, 'r', [50, 50, 50], 50, nangles=1200, axis=rp1)
        r3 = locfield(m, 'i', [50, 50, 50], 50, nangles=1200)

        r1[0].ACont = 1.0
        r2[0].ACont = 1.0
        r3[0].ACont = 1.0
        r1[1].ACont = 1.0
        r2[1].ACont = 1.0
        r3[1].ACont = 1.0

        min_oom = min(self.oom(r1[0].T), self.oom(r2[0].T[0]))
        np.testing.assert_array_almost_equal(r1[0].T,
                                             r2[0].T[0],
                                             decimal=7 - min_oom)
        min_oom = min(self.oom(r1[1].T), self.oom(r2[1].T[0]))
        np.testing.assert_array_almost_equal(r1[1].T,
                                             r2[1].T[0],
                                             decimal=7 - min_oom)

        r2_norms = np.apply_along_axis(np.linalg.norm, 1, r2[0].D)
        r3_norms = np.apply_along_axis(np.linalg.norm, 1, r3[0].D)

        min_oom = min(self.oom(np.max(r2_norms)), self.oom(np.max(r3_norms)))
        np.testing.assert_array_almost_equal(np.max(r2_norms),
                                             np.max(r3_norms),
                                             decimal=4 - min_oom)

        min_oom = min(self.oom(np.min(r2_norms)), self.oom(np.min(r3_norms)))
        np.testing.assert_array_almost_equal(np.min(r2_norms),
                                             np.min(r3_norms),
                                             decimal=4 - min_oom)

        r2_norms = np.apply_along_axis(np.linalg.norm, 1, r2[1].T)
        r3_norms = np.apply_along_axis(np.linalg.norm, 1, r3[1].T)

        min_oom = min(self.oom(np.max(r2_norms)), self.oom(np.max(r3_norms)))
        np.testing.assert_array_almost_equal(np.max(r2_norms),
                                             np.max(r2_norms),
                                             decimal=5 - min_oom)

        min_oom = min(self.oom(np.min(r2_norms)), self.oom(np.min(r3_norms)))
        np.testing.assert_array_almost_equal(np.min(r3_norms),
                                             np.min(r3_norms),
                                             decimal=5 - min_oom)
示例#22
0
    def test_mcif3(self):
        m = Sample()
        load_mcif(m, os.path.join(self._stdir, 'LiFeSO4F.mcif'))
        muon_set_frac(m, '0.25 0.25 0.25')

        # symmetry null
        r1 = locfield(m, 's', [
            np.random.randint(10, 14),
            np.random.randint(10, 14),
            np.random.randint(10, 14)
        ], 22, 4, 10.)
        r1[0].ACont = 1.

        # total field is 0
        np.testing.assert_array_almost_equal(r1[0].T, np.zeros(3), decimal=7)

        muon_reset(m)
        m.add_muon([float(x) for x in '0.15990  0.17820  0.14580'.split()
                    ])  # position of O3

        # one atom, distance is 2.14251 AA
        #  dipolar field should be:
        #
        #       def bfield(r,m):
        #           return 0.9274009*(3*r*np.dot(r,m)/(np.linalg.norm(r)**5)-m/(np.linalg.norm(r)**3))
        #       bfield(np.array([1.07574,1.59328,0.945826]),np.array([-1.70376,3.14961,-1.22045]))
        #
        r1 = locfield(m, 's', [
            np.random.randint(1, 4),
            np.random.randint(1, 4),
            np.random.randint(1, 4)
        ], 2.2, 1, 2.14251 + 20. * np.random.ranf())
        r1[0].ACont = 1.

        np.testing.assert_array_almost_equal(
            r1[0].D,
            np.array([0.29531083, -0.09756855, 0.23347458]),
            decimal=6)

        # contact field is (2/3)⋅magnetic_constant ([-1.70376 bohr_magneton ,3.14961bohr_magneton,-1.22045bohr_magneton])⋅(1angstrom^−3) =
        #   [-13.2372 T, 24.4705 T, -9.48213 T]

        np.testing.assert_array_almost_equal(
            r1[0].C, np.array([-13.2372, 24.4705, -9.48213]), decimal=4)

        r2 = locfield(m, 's', [
            np.random.randint(3, 5),
            np.random.randint(3, 5),
            np.random.randint(3, 5)
        ], 4.2, 3, 5. + 20. * np.random.ranf())
        r2[0].ACont = 1.14299  # effective interaction increased since more nnn involved in acont
        # still only 14% more

        # three atoms, distances are 2.14251 AA, 4.191093 AA, 4.19413AA
        #
        #      bfield(np.array([1.07574,1.59328,0.945826]),np.array([-1.70376,3.14961,-1.22045])) + \
        #      bfield(np.array([2.14396,2.77751,-2.29775]),np.array([1.70376,-3.14961,1.22045])) + \
        #      bfield(np.array([-2.28034,-2.66189,-2.29775]),np.array([1.70376,-3.14961,1.22045]))

        np.testing.assert_array_almost_equal(
            r2[0].D,
            np.array([0.20781014, -0.07504131, 0.23329355]),
            decimal=6)
示例#23
0
文件: test_clfc.py 项目: stur86/muesr
class TestCLFC(unittest.TestCase):
    def setUp(self):
        self.assertTrue(have_lfclib)
        self.sample = Sample()

    def _set_a_cell(self):
        self.sample.cell = Atoms(symbols=['Co'],
                                 scaled_positions=[[0, 0, 0]],
                                 cell=[[3., 0, 0], [0, 3., 0], [0, 0, 3.]])

    def test_find_largest_sphere(self):

        self.sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        with self.assertRaises(CellError):
            find_largest_sphere(self.sample, [3, 3, 3])

        self._set_a_cell()

        with self.assertRaises(MuonError):
            find_largest_sphere(self.sample, [3, 3, 3])

        self.sample.add_muon([0.5, 0.5, 0.5])

        with self.assertRaises(TypeError):
            find_largest_sphere(self.sample, 1)

        with self.assertRaises(ValueError):
            find_largest_sphere(self.sample, [0, 1, 2])

        self.assertEqual(find_largest_sphere(self.sample, [1, 1, 1]), 1.5)
        self.sample.add_muon([1., 1., 1.], cartesian=True)
        self.assertEqual(find_largest_sphere(self.sample, [1, 1, 1]), 1.)

    def test_locfield(self):

        self.sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        # sample, ctype, supercellsize, radius, nnn = 2, rcont = 10.0, nangles = None, axis = None):
        with self.assertRaises(TypeError):
            locfield(None, None, None, None)

        with self.assertRaises(TypeError):
            locfield(self.sample, None, None, None)

        with self.assertRaises(TypeError):
            locfield(self.sample, 's', None, None)

        with self.assertRaises(TypeError):
            locfield(self.sample, 's', [2, 2, 2], None)

        #with self.assertRaises(TypeError):
        #    locfield(self.sample, 's', [2,2,2], 3.)

        with self.assertRaises(TypeError):
            locfield(self.sample, 's', [2, 2, 2], 3., '2a')

        with self.assertRaises(TypeError):
            locfield(self.sample, 's', [2, 2, 2], 3., '2', '10b')

        with self.assertRaises(ValueError):
            locfield(self.sample, 'a', [2, 2, 2], 3.)

        with self.assertRaises(ValueError):
            locfield(self.sample, 'i', [2, 2, 2], 3.)

        with self.assertRaises(ValueError):
            locfield(self.sample, 's', [0, 2, 2], 3.)
print("Create sample...")
s = Sample()
print("done!")

print("Load CIF file...")

load_cif(s,os.path.join(head,'MnSi.cif'))
print("done!")

print("Calculate dipolar tensor for equivalent sites...\n")

# this is a general position along the 111, 
# just to identify the form of the dipolar tensor for the sites 
# along the 111
s.add_muon([0.45,0.45,0.45])

# we find the remainig eq muon sites
muon_find_equiv(s)

# apply an arbitrary small field to select magnetic atoms.
# the abslute value is not used, but it must be different from 0.
APP_FCs = 0.001*np.array([[0,0,1],
                          [0,0,1],
                          [0,0,1],
                          [0,0,1],
                          [0,0,0],
                          [0,0,0],
                          [0,0,0],
                          [0,0,0]], dtype=np.complex)
示例#25
0
def load_sample(filename="", fileobj=None):
    """
    This function load a sample from a file in YAML format.
        
    :param str filename: the filename used to store data.
    :param file fileobj: an optional file object. If specified, this
                         supersede the filename input.
    :return: a sample object
    :rtype: :py:class:`~Sample` object or None
    :raises: ValueError, FileNotFoundError, IsADirectoryError
    
    """

    # fail if YAML is not available
    if not have_yaml:
        warnings.warn("Warning, YAML python package not present!")
        return

    sample = Sample()

    data = {}
    if fileobj is None:
        if filename == "":
            raise ValueError("Specify filename or File object")
        with open(filename, 'r') as f:
            data = load(f, Loader=Loader)
    else:
        data = load(fileobj, Loader=Loader)

    if not (type(data) is dict):
        raise ValueError('Invalid data file. (problems with YAML?)')

    if data is None:
        raise ValueError('Invalid/empty data file. (problems with YAML?)')

    if 'Name' in data.keys():
        sample.name = str(data['Name'])

    if 'Lattice' in data.keys():
        l = data['Lattice']

        spos = None
        cpos = None
        if 'ScaledPositions' in l.keys():
            spos = np.array(l['ScaledPositions'])
        elif 'CartesianPositions' in l.keys():
            cpos = np.array(l['CartesianPositions'])

        cell = None
        if 'Cell' in l.keys():
            cell = np.array(l['Cell'])

        symbols = None
        if 'Symbols' in l.keys():
            symbols = l['Symbols']

        if (cell is None) or (symbols is None):
            warnings.warn('Cell not loaded!', RuntimeWarning)
        else:
            if not spos is None:
                sample.cell = Atoms(symbols=symbols,
                                    scaled_positions=spos,
                                    cell=cell,
                                    pbc=True)
            elif not cpos is None:
                sample.cell = Atoms(symbols=symbols,
                                    positions=cpos,
                                    cell=cell,
                                    pbc=True)
            else:
                warnings.warn('Cell not loaded!', RuntimeWarning)

    else:
        warnings.warn('Cell not loaded!', RuntimeWarning)

    if 'Muon' in data.keys():
        m = data['Muon']
        if 'Positions' in m:
            for p in m['Positions']:
                sample.add_muon(p)
        else:
            warnings.warn('Muon positions not loaded!', RuntimeWarning)
    else:
        warnings.warn('Muon positions not loaded!', RuntimeWarning)

    if 'Symmetry' in data.keys():
        s = data['Symmetry']

        if ('Number' in s.keys()) and \
            ('Symbol' in s.keys()) and \
            ('Rotations' in s.keys()) and \
            ('Translations' in s.keys()):
            sample.sym = spacegroup_from_data(
                s['Number'],
                s['Symbol'],
                rotations=np.array(s['Rotations']),
                translations=np.array(s['Translations']))
        else:
            warnings.warn('Symmetry not loaded.', RuntimeWarning)
    else:
        warnings.warn('Symmetry not loaded!', RuntimeWarning)

    if 'MagneticOrders' in data.keys():
        m = data['MagneticOrders']

        if len(m) > 0:

            msize = int(m['Size'])

            for mo in m['Orders']:

                if 'lattice' in mo.keys():
                    n = MM(msize, \
                            np.array(mo['lattice']))
                else:
                    n = MM(msize)

                sample.mm = n
                sample.mm.k = np.array(mo['k'])
                sample.mm.phi = np.array(mo['phi'])

                if 'desc' in mo.keys():
                    sample.mm.desc = str(mo['desc'])

                rfcs, ifcs = np.hsplit(np.array(mo['fc']), 2)

                if mo['format'].lower() in ['bohr-cartesian', 'b-c']:
                    sample.mm.fcCart = (rfcs + 1.j * ifcs)

                elif mo['format'].lower() in ['bohr/angstrom-lattic', 'b/a-l']:
                    sample.mm.fcLattBMA = (rfcs + 1.j * ifcs)

                elif mo['format'].lower() in ['bohr-lattice', 'b-l']:
                    sample.mm.fcLattBM = (rfcs + 1.j * ifcs)

                else:
                    raise ValueError(
                        'Invalid Fourier Components format specifier in YAML file.'
                    )
        else:
            warnings.warn('Magnetic definitions not loaded!', RuntimeWarning)
    else:
        warnings.warn('Magnetic definitions not loaded!', RuntimeWarning)

    return sample
示例#26
0
    def test_rotation(self):
        m = Sample()
        load_xsf(m, os.path.join(self._stdir, 'crys3.xsf'))
        mm = MM(1)
        mm.k = np.array([0., 0., 0.])
        mm.fc_set(np.array([[0. + 0j, 1. + 0.j, 0. + 0.j]]))
        m.mm = mm
        m.add_muon([0.0, 0.001, 0.0])
        r = locfield(m,
                     'r', [1, 1, 1],
                     1.2,
                     nnn=0,
                     nangles=300,
                     axis=[1, 0, 0])[0]

        # r for angle = 0 should be: [0 T, 1.8548 T, 0 T]
        #
        #    (magnetic_constant/4pi)⋅((1/(1angstrom⋅sqrt(1^2)))^3)⋅(3⋅(1 bohr_magneton)⋅cos(0)⋅([0,1,0]/sqrt(1))−1bohr_magneton⋅[0,1,0])
        #
        #
        # r for angle = 90 should be: [0 T, 0 T, −0.927401 T]
        #
        #    (magnetic_constant/4pi)⋅((1/(1angstrom⋅sqrt(1^2)))^3)⋅(3⋅(1 bohr_magneton)⋅cos(pi/2)⋅([0,1,0]/sqrt(1))−1bohr_magneton⋅[0,0,1])
        #
        # Opposite moments produce opposite fields. 150 is half of 300
        np.testing.assert_array_almost_equal(r.D[0], -r.D[150], decimal=7)
        np.testing.assert_array_almost_equal(r.D[0],
                                             np.array([0., 1.8548018, 0.]),
                                             decimal=7)
        np.testing.assert_array_almost_equal(r.D[75],
                                             np.array([0., 0, -0.9274009]),
                                             decimal=6)

        rnorms = np.apply_along_axis(np.linalg.norm, 1, r.T - r.L)
        self.assertAlmostEqual(np.min(rnorms),
                               0.9274009,
                               places=6,
                               msg=None,
                               delta=None)
        self.assertAlmostEqual(np.max(rnorms),
                               1.8548018,
                               places=6,
                               msg=None,
                               delta=None)

        r = locfield(m,
                     'r', [5, 1, 1],
                     1.5,
                     nnn=0,
                     nangles=300,
                     axis=[1, 0, 0])[0]
        np.testing.assert_array_almost_equal(r.D[0], -r.D[150], decimal=7)
        np.testing.assert_array_almost_equal(r.D[0],
                                             np.array([0., 2.18268753, 0.]),
                                             decimal=7)
        np.testing.assert_array_almost_equal(r.D[75],
                                             np.array([0., 0, -1.58317237]),
                                             decimal=6)

        rnorms = np.apply_along_axis(np.linalg.norm, 1, r.T - r.L)
        self.assertAlmostEqual(np.min(rnorms),
                               1.58317237,
                               places=6,
                               msg=None,
                               delta=None)
        self.assertAlmostEqual(np.max(rnorms),
                               2.18268753,
                               places=6,
                               msg=None,
                               delta=None)

        # Now test incomm
        mm = MM(1)
        mm.k = np.array([0., 0., 0.])
        mm.fc_set(np.array([[0. + 0j, 1. + 0.j, 0. + 1.j]]))
        m.mm = mm
        i = locfield(m, 'i', [1, 1, 1], 1.2, nnn=0, nangles=300)[0]

        inorms = np.apply_along_axis(np.linalg.norm, 1, i.T - i.L)

        self.assertAlmostEqual(np.min(inorms),
                               0.9274009,
                               places=6,
                               msg=None,
                               delta=None)
        self.assertAlmostEqual(np.max(inorms),
                               1.8548018,
                               places=6,
                               msg=None,
                               delta=None)

        i = locfield(m, 'i', [5, 1, 1], 1.5, nnn=0, nangles=300)[0]

        rnorms = np.apply_along_axis(np.linalg.norm, 1, i.T - i.L)
        self.assertAlmostEqual(np.min(rnorms),
                               1.58317237,
                               places=6,
                               msg=None,
                               delta=None)
        self.assertAlmostEqual(np.max(rnorms),
                               2.18268753,
                               places=6,
                               msg=None,
                               delta=None)
示例#27
0
class TestSample(unittest.TestCase):
    def setUp(self):
        self._sample = Sample()

    def _set_a_cell(self):
        self._sample.cell = Atoms(symbols=['Co'],
                                  scaled_positions=[[0, 0, 0]],
                                  cell=[[3., 0, 0], [0, 3., 0], [0, 0, 3.]])

    def test_set_attribute(self):
        with self.assertRaises(TypeError):
            self._sample.blabla = 1

    def test_name_property(self):

        self.assertEqual(self._sample.name, "No name")

        self._sample.name = "test"

        self.assertEqual(self._sample.name, "test")

        #must be str or unicode
        with self.assertRaises(TypeError):
            self._sample.name = 1

        self.assertEqual(self._sample.name, "test")

        # test unicode
        self._sample.name = u"àèé"

    def test_muons_property(self):
        self._sample._reset(cell=True, muon=True, sym=True, magdefs=True)
        self._set_a_cell()

        with self.assertRaises(MuonError):
            self._sample.muons

    def test_add_muon_property(self):
        self._sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        with self.assertRaises(CellError):
            self._sample.add_muon([0, 0, 0])

        self._set_a_cell()

        with self.assertRaises(TypeError):
            self._sample.add_muon('0 0 0')

        with self.assertRaises(ValueError):
            self._sample.add_muon([0, 0, 0, 0])
        with self.assertRaises(ValueError):
            self._sample.add_muon(np.array([0, 0, 0, 0]))

        self._sample.add_muon([0, 0, 0])
        np.testing.assert_array_equal(self._sample.muons[0], np.zeros(3))

        self._sample.add_muon([1, 1, 1])
        np.testing.assert_array_equal(self._sample.muons[1], np.ones(3))

        self._sample.add_muon([1, 1, 1], cartesian=True)
        np.testing.assert_array_equal(self._sample.muons[2], np.ones(3) / 3.)

        a = 4.0  # some lattice constant
        b = a / 2
        self._sample.cell = Atoms(symbols=['Au'],
                                  positions=[0, 0, 0],
                                  cell=[(0, b, b), (b, 0, b), (b, b, 0)],
                                  pbc=True)

        self._sample.add_muon([1., 1., 1.], cartesian=True)
        np.testing.assert_array_equal(self._sample.muons[3], np.ones(3) / 4.)

        self._sample.add_muon([.5, .5, .5], cartesian=False)
        self._sample.add_muon([2., 2., 2.], cartesian=True)
        np.testing.assert_array_equal(self._sample.muons[4],
                                      self._sample.muons[5])

    def test_mm_property(self):
        self._sample._reset(cell=True, magdefs=True, muon=True, sym=True)

        with self.assertRaises(MagDefError):
            self._sample.mm

        with self.assertRaises(CellError):
            self._sample.mm = MM(19)  # randomly large number

        self._sample._reset(magdefs=True)
        self._set_a_cell()
        with self.assertRaises(TypeError):
            self._sample.mm = 1

        self._sample._reset(magdefs=True, cell=True, muon=True, sym=True)
        self._sample.cell = Atoms(symbols=['C'],
                                  scaled_positions=[[0, 0, 0]],
                                  cell=[[3., 0, 0], [0, 3., 0], [0, 0, 3.]])

        with self.assertRaises(MagDefError):
            self._sample.mm = MM(198)  # randomly large number

        self._sample.mm = MM(1)

    def test_new_mm(self):
        self._sample._reset(magdefs=True, cell=True, muon=True, sym=True)
        with self.assertRaises(CellError):
            self._sample.new_mm()

        self._set_a_cell()

        self._sample.new_mm()
        self.assertTrue(isinstance(self._sample.mm, MM))
        self.assertEqual(len(self._sample.mm.fc), 1)

    def test_new_smm(self):
        if have_sympy:
            self._sample._reset(magdefs=True, cell=True, muon=True, sym=True)
            with self.assertRaises(CellError):
                self._sample.new_smm("x,y,z")

            # TODO TESTING
        else:
            pass

    def test_current_mm_idx_property(self):
        self._sample._reset(magdefs=True, cell=True, muon=True, sym=True)
        self._sample.cell = Atoms(symbols=['C'],
                                  scaled_positions=[[0, 0, 0]],
                                  cell=[[3., 0, 0], [0, 3., 0], [0, 0, 3.]])

        self._sample.new_mm()
        self._sample.mm.k = np.array([0, 0, 1.])
        self.assertEqual(self._sample.current_mm_idx, 0)
        self._sample.new_mm()
        self._sample.mm.k = np.array([0, 0, 2.])
        self.assertEqual(self._sample.current_mm_idx, 1)
        self._sample.new_mm()
        self._sample.mm.k = np.array([0, 0, 3.])
        self.assertEqual(self._sample.current_mm_idx, 2)

        self._sample.current_mm_idx = 0
        self.assertEqual(self._sample.current_mm_idx, 0)
        np.testing.assert_array_equal(self._sample.mm.k, np.array([0, 0, 1.]))

        with self.assertRaises(IndexError):
            self._sample.current_mm_idx = 3

        with self.assertRaises(IndexError):
            self._sample.current_mm_idx = -1

        self.assertEqual(self._sample.current_mm_idx, 0)

    def test_sym_property(self):

        self._sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        with self.assertRaises(SymmetryError):
            self._sample.sym

        with self.assertRaises(TypeError):
            self._sample.sym = 1

        self._sample.sym = Spacegroup(113)

        self.assertEqual(self._sample.sym.no, 113)
        self.assertEqual(self._sample.sym.setting, 1)

    def test_cell_property(self):
        #needs better testing
        with self.assertRaises(CellError):
            self._sample.cell

        with self.assertRaises(TypeError):
            self._sample.cell = 1

        self._set_a_cell()
        current_cell = self._sample.cell
        self.assertEqual(current_cell.get_chemical_symbols(), ['Co'])
        current_cell.set_chemical_symbols(['Co'])
        self.assertEqual(current_cell.get_chemical_symbols(), ['Co'])

    def test_reset(self):

        # test cell reset
        with warnings.catch_warnings(record=True) as w:
            # Cause all warnings to always be triggered.
            warnings.simplefilter("always")
            self._sample._reset(cell=True)
            assert len(w) == 3
            for wi in w:
                assert issubclass(wi.category, RuntimeWarning)

        self.assertEqual(self._sample._cell, None)
        with self.assertRaises(CellError):
            self._sample.cell

        # test magdef reset
        self._sample._reset(magdefs=True)
        self.assertEqual(self._sample._magdefs, [])
        self.assertEqual(self._sample._selected_mm, -1)
        with self.assertRaises(MagDefError):
            self._sample.mm

        # test muon reset
        self._set_a_cell()
        self._sample.add_muon([0, 1., 2])
        self._sample._reset(muon=True)
        self.assertEqual(self._sample._muon, [])
        with self.assertRaises(MuonError):
            self._sample.muons

        self._sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        #test symmetry reset
        self._sample.sym = Spacegroup(113)
        self._sample._reset(sym=True)
        self.assertEqual(self._sample._sym, None)
        with self.assertRaises(SymmetryError):
            self._sample.sym

    # TODO
    def test_check_sym(self):
        self._sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        with self.assertRaises(SymmetryError):
            self._sample._check_sym()

        # vary bad from user side
        self._sample._sym = 1
        with self.assertRaises(SymmetryError):
            self._sample._check_sym()

        self._sample.sym = Spacegroup(113)
        self.assertTrue(self._sample._check_sym())

    def test_check_lattice(self):
        self._sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        with self.assertRaises(CellError):
            self._sample._check_lattice()

        self._set_a_cell()
        self.assertTrue(self._sample._check_lattice())
        self._sample._cell = 1
        with self.assertRaises(CellError):
            self._sample._check_lattice()

    def test_check_magdefs(self):
        self._sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        with self.assertRaises(MagDefError):
            self._sample._check_magdefs()

        self._set_a_cell()
        self._sample.new_mm()
        self.assertTrue(self._sample._check_magdefs())

        self._sample._magdefs = 1
        with self.assertRaises(MagDefError):
            self._sample._check_magdefs()

    def test_check_muon(self):
        self._sample._reset(cell=True, muon=True, sym=True, magdefs=True)

        with self.assertRaises(MuonError):
            self._sample._check_muon()

        self._set_a_cell()
        self._sample.add_muon(np.zeros(3))
        self.assertTrue(self._sample._check_muon())

        self._sample.add_muon(np.zeros(3))
        self._sample._muon[1] = 'a'
        with self.assertRaises(MuonError):
            self._sample._check_muon()
示例#28
0
文件: test_clfc.py 项目: bonfus/muesr
class TestCLFC(unittest.TestCase):
 
    def setUp(self):
        self.assertTrue(have_lfclib)
        self.sample = Sample()

    def _set_a_cell(self):
        self.sample.cell = Atoms(symbols=['Co'],
                                  scaled_positions=[[0,0,0]],
                                  cell=[[3.,0,0],
                                        [0,3.,0],
                                        [0,0,3.]])
        
    def test_find_largest_sphere(self):
        
        self.sample._reset(cell=True,muon=True,sym=True,magdefs=True)
        
        with self.assertRaises(CellError):
            find_largest_sphere(self.sample,[3,3,3])
        
        
        
        self._set_a_cell() 

        with self.assertRaises(MuonError):
            find_largest_sphere(self.sample,[3,3,3])
        
        self.sample.add_muon([0.5,0.5,0.5])
        
        
        with self.assertRaises(TypeError):
            find_largest_sphere(self.sample,1)

        with self.assertRaises(ValueError):
            find_largest_sphere(self.sample,[0,1,2])
            
        self.assertEqual(find_largest_sphere(self.sample,[1,1,1]),1.5)
        self.sample.add_muon([1.,1.,1.],cartesian=True)
        self.assertEqual(find_largest_sphere(self.sample,[1,1,1]),1.)
        
    def test_locfield(self):
        
        self.sample._reset(cell=True,muon=True,sym=True,magdefs=True)
      
        # sample, ctype, supercellsize, radius, nnn = 2, rcont = 10.0, nangles = None, axis = None):
        with self.assertRaises(TypeError):
            locfield(None, None, None, None)
        
        with self.assertRaises(TypeError):
            locfield(self.sample, None, None, None)

        with self.assertRaises(TypeError):
            locfield(self.sample, 's', None, None)
            
        with self.assertRaises(TypeError):
            locfield(self.sample, 's', [2,2,2], None)

        #with self.assertRaises(TypeError):
        #    locfield(self.sample, 's', [2,2,2], 3.)

        with self.assertRaises(TypeError):
            locfield(self.sample, 's', [2,2,2], 3., '2a')

        with self.assertRaises(TypeError):
            locfield(self.sample, 's', [2,2,2], 3., '2', '10b')

        with self.assertRaises(ValueError):
            locfield(self.sample, 'a', [2,2,2], 3.)
            
        with self.assertRaises(ValueError):
            locfield(self.sample, 'i', [2,2,2], 3.)

        with self.assertRaises(ValueError):
            locfield(self.sample, 's', [0,2,2], 3.)