Ejemplo n.º 1
0
    def test_qangle_NoGC_NoOC_right(self):
        # No geometry constraints, no omega constraints, all parameters are arrays,
        # except for sign=-1
        test_case5 = array([[10, 0, 1, 0, 0, 0.72, 0, 0.12, -19, 0, 80.5, 0, 80.5, 0],
                            [10, 0, 0, 1, 0, 0.72, 0, 0.12, -19, 0, 80.5, 0, 20.5, 0],
                            [10, 0, -1, 0, 0, 0.72, 0, 0.12, -19, 0, 80.5, 0, -99.5, 0],
                            [10, 0, 0, -1, 0, 0.72, 0, 0.12, -19, 0, 80.5, 0, -159.5, 0],
                            [10, 0, 1, 1, 0, 1.2, 0, 0.36, -33.2, 0, 73.4, 0, 43.4, 0],
                            [10, 0, 0.2, 0, 0, 0.14, 0, 0, -3.8, 0, 88.1, 0, 88.1, 0],
                            [10, 0, 0.02, 0, 0, 0.015, 0, 5e-05, -0.4, 0, 89.8, 0, 89.8, 0],
                            [10, 5, 1, 0, 0, 0.28, 0, 0.67, -10.4, 0, 22.8, 0, 22.8, 0],
                            [10, -5, 1, 0, 0, 0.59, 0, -0.43, -12.6, 0, 126.3, 0, 126.3, 0],
                            [10, 0, 5, 0, 0, 2.05, 0, 3, -111.3, 0, 34.4, 0, 34.3, 0]])

        a=10
        b=10
        c=10
        alpha=90
        beta=90
        gamma=120
        u=[1,0,0]
        v=[0,1,0]
        ol=OrientedLattice(a, b, c, alpha, beta, gamma)
        ol.setUFromVectors(u,v)

        sign=-1
        (Ei, DE, H, K, L, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_kf_angle,
         expected_out_plane_kf_angle, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
         expected_omega, expected_error_code) = test_case5.T

        HKL = vstack([H,K,L]).T
        pars = {'Ei': Ei, 'hkl': HKL, 'DeltaE': DE, 'sign': sign}
        expected_error_code = [ErrorCodes(ec) for ec in expected_error_code]
        self.run_test(ol, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
                 expected_in_plane_kf_angle, expected_out_plane_kf_angle, expected_omega, expected_error_code, **pars)
Ejemplo n.º 2
0
 def qe_para(self):
     self.orien = OrientedLattice(*Alignment.para)
     self.para = Alignment.para
     self.hkl = [self.point.h, self.point.k, self.point.l]
     self.len = self.orien.qFromHKL(self.hkl).norm()
     self.mono = Monochromator(en=self.point.ei)
     self.ana = Monochromator(en=self.point.ef)
Ejemplo n.º 3
0
 def test_qFromHKL(self):
     ol = OrientedLattice(1,1,1)
     hkl = V3D(1,1,1)
     qVec = ol.qFromHKL(hkl)
     self.assertAlmostEqual(hkl.X() * 2 * np.pi, qVec.X(), 9)
     self.assertAlmostEqual(hkl.Y() * 2 * np.pi, qVec.Y(), 9)
     self.assertAlmostEqual(hkl.Z() * 2 * np.pi, qVec.Z(), 9)
Ejemplo n.º 4
0
 def test_hklFromQ(self):
     ol = OrientedLattice(1, 1, 1)
     qVec = V3D(1, 1, 1)
     hkl = ol.hklFromQ(qVec)
     self.assertAlmostEqual(hkl.X() * 2 * np.pi, qVec.X(), 9)
     self.assertAlmostEqual(hkl.Y() * 2 * np.pi, qVec.Y(), 9)
     self.assertAlmostEqual(hkl.Z() * 2 * np.pi, qVec.Z(), 9)
Ejemplo n.º 5
0
 def test_qFromHKL(self):
     ol = OrientedLattice(1, 1, 1)
     hkl = V3D(1, 1, 1)
     qVec = ol.qFromHKL(hkl)
     self.assertAlmostEqual(hkl.X() * 2 * np.pi, qVec.X(), 9)
     self.assertAlmostEqual(hkl.Y() * 2 * np.pi, qVec.Y(), 9)
     self.assertAlmostEqual(hkl.Z() * 2 * np.pi, qVec.Z(), 9)
Ejemplo n.º 6
0
 def test_hklFromQ(self):
     ol = OrientedLattice(1,1,1)
     qVec = V3D(1,1,1)
     hkl = ol.hklFromQ(qVec)
     self.assertAlmostEqual(hkl.X() * 2 * np.pi, qVec.X(), 9)
     self.assertAlmostEqual(hkl.Y() * 2 * np.pi, qVec.Y(), 9)
     self.assertAlmostEqual(hkl.Z() * 2 * np.pi, qVec.Z(), 9)
    def test_create_nonorthogonal_transform_with_nonorthogonal_lattice_and_nonorthogonal_projections(
            self):
        lattice = OrientedLattice(1, 1, 2, 90, 90, 120.)
        x_proj, y_proj = (1, 0, 0), (1, 1, 0)
        transform = NonOrthogonalTransform.from_lattice(
            lattice, x_proj, y_proj)

        self.assertAlmostEqual(transform.angle,
                               np.radians(lattice.recAngle(*x_proj, *y_proj)))
Ejemplo n.º 8
0
    def test_hklFromQ_input_types(self):
        '''
        Test that you can provide input q values as different python types.
        '''
        ol = OrientedLattice(1,1,1)

        self.assertTrue(isinstance( ol.hklFromQ(V3D(1,1,1)), V3D), "Should work with V3D input")

        self.assertTrue(isinstance( ol.hklFromQ([1,1,1]), V3D), "Should work with python array input" )

        self.assertTrue(isinstance( ol.hklFromQ(np.array([1,1,1])), V3D), "Should work with numpy array input" )
Ejemplo n.º 9
0
    def test_simple_values(self):
        u1 = OrientedLattice()
        self.assertEquals(u1.a1(),1)
        self.assertEquals(u1.alpha(),90)

        u2 = OrientedLattice(3,4,5)
        self.assertAlmostEqual(u2.b1(),1./3.,10)
        self.assertAlmostEqual(u2.alphastar(),90,10)
        u3 = u2;
        self.assertAlmostEqual(u3.volume(),1./u2.recVolume(),10)
        u2.seta(3);
        self.assertAlmostEqual(u2.a(),3,10)
Ejemplo n.º 10
0
    def test_qangle_NoGC_NoOC(self):
        # No geometry constraints, no omega constraints, all parameters are arrays
        test_case1 = array([[10, 0, 1, 0, 0, 1, -0.72, 0, 0.12, 19, 0, -80.5, 0, -80.5, 0],
                            [10, 0, 0, 1, 0, 1, -0.72, 0, 0.12, 19, 0, -80.5, 0, -140.5, 0],
                            [10, 0, -1, 0, 0, 1, -0.72, 0, 0.12, 19, 0, -80.5, 0, 99.5, 0],
                            [10, 0, 0, -1, 0, 1, -0.72, 0, 0.12, 19, 0, -80.5, 0, 39.5, 0],
                            [10, 0, 1, 1, 0, 1, -1.2, 0, 0.36, 33.2, 0, -73.4, 0, -103.4, 0],
                            [10, 0, 0.2, 0, 0, 1, -0.14, 0, 0, 3.8, 0, -88.1, 0, -88.1, 0],
                            [10, 0, 0.02, 0, 0, 1, -0.015, 0, 5e-05, 0.4, 0, -89.8, 0, -89.8, 0],
                            [10, 5, 1, 0, 0, 1, -0.28, 0, 0.67, 10.4, 0, -22.8, 0, -22.7, 0],
                            [10, -5, 1, 0, 0, 1, -0.59, 0, -0.43, 12.6, 0, -126.3, 0, -126.3, 0],
                            [10, 0, 5, 0, 0, 1, -2.05, 0, 3, 111.3, 0, -34.4, 0, -34.3, 0],
                            [10, 0, 1, -0.01, -0.18, 1, -0.71, -0.11, 0.12, 19, 3, -80.3, -9, -79.7, 0],
                            [10, 0, 1, 0, -0.6, 1, -0.72, -0.38, 0.15, 19.13, 10, -77.8, -27.5, -77.9, 0],
                            [10, 0, 1, 0, 0, -1, 0.72, 0, 0.12, -19, 0, 80.5, 0, 80.5, 0],
                            [10, 0, 0, 1, 0, -1, 0.72, 0, 0.12, -19, 0, 80.5, 0, 20.5, 0],
                            [10, 0, -1, 0, 0, -1, 0.72, 0, 0.12, -19, 0, 80.5, 0, -99.5, 0],
                            [10, 0, 0, -1, 0, -1, 0.72, 0, 0.12, -19, 0, 80.5, 0, -159.5, 0],
                            [10, 0, 1, 1, 0, -1, 1.2, 0, 0.36, -33.2, 0, 73.4, 0, 43.4, 0],
                            [10, 0, 0.2, 0, 0, -1, 0.14, 0, 0, -3.8, 0, 88.1, 0, 88.1, 0],
                            [10, 0, 0.02, 0, 0, -1, 0.015, 0, 5e-05, -0.4, 0, 89.8, 0, 89.8, 0],
                            [10, 5, 1, 0, 0, -1, 0.28, 0, 0.67, -10.4, 0, 22.8, 0, 22.8, 0],
                            [10, -5, 1, 0, 0, -1, 0.59, 0, -0.43, -12.6, 0, 126.3, 0, 126.3, 0],
                            [10, 0, 5, 0, 0, -1, 2.05, 0, 3, -111.3, 0, 34.4, 0, 34.3, 0],
                            [20, 0, 1, 0, 0, 1, -0.72, 0, 0.08, 13.4, 0, -83.3, 0, -83.3, 0],
                            [10, 0, 8, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 2],
                            [10, 20, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 2],
                            [-10, 0, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 1],
                            [10, 0, 1, 0, nan, 1, nan, nan, nan, nan, nan, nan, nan, nan, 1],
                            [10, 0, -1.3, 3.4, -3.5, -1, nan, nan, nan, nan, nan, nan, nan, nan, 3],
                            [10, 0, -1.3, 3.4, 3.5, -1, nan, nan, nan, nan, nan, nan, nan, nan, 3]])

        a=10
        b=10
        c=10
        alpha=90
        beta=90
        gamma=120
        u=[1,0,0]
        v=[0,1,0]
        ol=OrientedLattice(a, b, c, alpha, beta, gamma)
        ol.setUFromVectors(u,v)

        (Ei, DE, H, K, L, sign, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_kf_angle,
         expected_out_plane_kf_angle, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
         expected_omega, expected_error_code) = test_case1.T

        HKL = vstack([H,K,L]).T
        pars = {'Ei': Ei, 'hkl': HKL, 'DeltaE': DE, 'sign': sign}
        expected_error_code = [ErrorCodes(ec) for ec in expected_error_code]
        self.run_test(ol, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
                 expected_in_plane_kf_angle, expected_out_plane_kf_angle, expected_omega, expected_error_code, **pars)
Ejemplo n.º 11
0
    def test_hklFromQ_input_types(self):
        '''
        Test that you can provide input q values as different python types.
        '''
        ol = OrientedLattice(1, 1, 1)

        self.assertTrue(isinstance(ol.hklFromQ(V3D(1, 1, 1)), V3D),
                        "Should work with V3D input")

        self.assertTrue(isinstance(ol.hklFromQ([1, 1, 1]), V3D),
                        "Should work with python array input")

        self.assertTrue(isinstance(ol.hklFromQ(np.array([1, 1, 1])), V3D),
                        "Should work with numpy array input")
Ejemplo n.º 12
0
    def test_qangle_GC_OC(self):
        # Geometry constraints, no omega constraints, all parameters are arrays
        test_case8 = array([[10, 0, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0, 1, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, -1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0, -1, 0, 1, -0.72, 0, 0.12, 19, 0, -80.5, 0, 39.5, 0],
                            [10, 0, 1, 1, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0.2, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 0.02, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 5, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, -5, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 5, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 1, -0.01, -0.18, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 1, 0, -0.6, 1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 1, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 0, 1, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, -1, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 0, -1, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 1, 1, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 0.2, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 0.02, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 5, 1, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, -5, 1, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [10, 0, 5, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 4],
                            [20, 0, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 8, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 2],
                            [10, 20, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 2]])

        a=10
        b=10
        c=10
        alpha=90
        beta=90
        gamma=120
        u=[1,0,0]
        v=[0,1,0]
        ol=OrientedLattice(a, b, c, alpha, beta, gamma)
        ol.setUFromVectors(u,v)

        (Ei, DE, H, K, L, sign, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_kf_angle,
         expected_out_plane_kf_angle, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
         expected_omega, expected_error_code) = test_case8.T

        HKL = vstack([H,K,L]).T
        pars = {'Ei': Ei, 'hkl': HKL, 'DeltaE': DE, 'sign': sign, 'detector_constraints': True, 'horizontal_extent': [5.,65.],
                'vertical_extent': [-7.5, 7.5], 'horizontal_extent_low': [-1,1.], 'vertical_extent_low': [-1.,1.],
                'goniometer_constraints': True, 'goniometer_range': [-20., 50]}
        expected_error_code = [ErrorCodes(ec) for ec in expected_error_code]
        self.run_test(ol, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
                 expected_in_plane_kf_angle, expected_out_plane_kf_angle, expected_omega, expected_error_code, **pars)
Ejemplo n.º 13
0
    def test_qangle_NoGC_OC(self):
        # Geometry constraints, no omega constraints, all parameters are arrays
        test_case7 = array([[10, 0, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0, 1, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, -1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0, -1, 0, 1, -0.72, 0, 0.12, 19, 0, -80.5, 0, 39.5, 0],
                            [10, 0, 1, 1, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0.2, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0.02, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 5, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, -5, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 5, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 1, -0.01, -0.18, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 1, 0, -0.6, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 1, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0, 1, 0, -1, 0.72, 0, 0.12, -19, 0, 80.5, 0, 20.5, 0],
                            [10, 0, -1, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0, -1, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 1, 1, 0, -1, 1.2, 0, 0.36, -33.2, 0, 73.4, 0, 43.4, 0],
                            [10, 0, 0.2, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 0.02, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 5, 1, 0, 0, -1, 0.28, 0, 0.67, -10.4, 0, 22.8, 0, 22.8, 0],
                            [10, -5, 1, 0, 0, -1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 5, 0, 0, -1, 2.05, 0, 3, -111.3, 0, 34.4, 0, 34.3, 0],
                            [20, 0, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 6],
                            [10, 0, 8, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 2],
                            [10, 20, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 2]])

        a=10
        b=10
        c=10
        alpha=90
        beta=90
        gamma=120
        u=[1,0,0]
        v=[0,1,0]
        ol=OrientedLattice(a, b, c, alpha, beta, gamma)
        ol.setUFromVectors(u,v)

        (Ei, DE, H, K, L, sign, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_kf_angle,
         expected_out_plane_kf_angle, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
         expected_omega, expected_error_code) = test_case7.T

        HKL = vstack([H,K,L]).T
        pars = {'Ei': Ei, 'hkl': HKL, 'DeltaE': DE, 'sign': sign, 'goniometer_constraints': True, 'goniometer_range': [-20., 50]}
        expected_error_code = [ErrorCodes(ec) for ec in expected_error_code]
        self.run_test(ol, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
                 expected_in_plane_kf_angle, expected_out_plane_kf_angle, expected_omega, expected_error_code, **pars)
Ejemplo n.º 14
0
class Monochromator():
    # only for PG
    __slots__ = ['lambdan', 'tth', 'en']

    def __init__(self, reflect=[0, 0, 2], **kargs):
        self.kargs = kargs
        self.pgo = OrientedLattice(2.461, 2.461, 6.708, 90, 90, 60)
        self.q = self.pgo.qFromHKL(reflect).norm()
        if 'lambdan' in self.kargs.keys():
            self.lambdan = self.kargs['lambdan']
            self.en = (9.045 / self.lambdan)**2
            self.k = 2 * math.pi / self.lambdan
            self.lambda2m2()
        if 'tth' in self.kargs.keys():
            self.tth = abs(self.kargs['tth'])
            self.monolambda()
        if 'en' in self.kargs.keys():
            self.en = self.kargs['en']
            self.lambdan = 9.045 / (math.sqrt(self.en))
            self.k = 2 * math.pi / self.lambdan
            self.lambda2m2()

    def lambda2m2(self):
        stth = self.q / 2.0 / self.k
        self.tth = math.asin(stth) * 360 / math.pi

    def monolambda(self):
        self.k = self.q / 2 / math.sin(self.tth * math.pi / 360)
        self.lambdan = 2 * math.pi / self.k
        self.en = (9.045 / self.lambdan)**2
Ejemplo n.º 15
0
 def from_lattice(cls, lattice: OrientedLattice, x_proj: Sequence, y_proj: Sequence):
     """
     :param lattice: An OrientedLattice object defining the unit cell
     :param x_proj: Projection vector of dimension associated with X coordinate
     :param y_proj: Projection vector of dimension associated with Y coordinate
     """
     return cls(np.radians(lattice.recAngle(*x_proj, *y_proj)))
Ejemplo n.º 16
0
    def test_qangle_NoGC_NoOC_newOL(self):
        # No geometry constraints, no omega constraints, all parameters are arrays
        test_case9 = array([[10, 0, 1, 0, 0, 1, -2.02, 0, 1.33, 66.8, 0, -56.6, 0, -56.6, 0],
                            [10, 0, 0, 1, 0, 1, -1.01, 0, 0.24, 27.3, 0, -76.4, 0, -136.4, 0],
                             [10, 0, -1, 0, 0, 1, -2.02, 0, 1.33, 66.8, 0, -56.6, 0, 123.4, 0],
                             [10, 0, 0, -1, 0, 1, -1.01, 0, 0.24, 27.3, 0, -76.4, 0, 43.6, 0],
                             [10, 0, 1, 1, 0, 1, -2.2, 0, 2.15, 88.7, 0, -45.7, 0, -62.7, 0],
                             [10, 0, 0.2, 0, 0, 1, -0.48, 0, 0.05, 12.6, 0, -83.7, 0, -83.7, 0],
                             [10, 0, 0.02, 0, 0, 1, -0.04984, 0, 0.00057, 1.3, 0, -89.4, 0, -89.4, 0],
                             [10, 5, 1, 0, 0, 1, -1.52, 0, 1.88, 78.2, 0, -39, 0, -39, 0],
                             [10, -5, 1, 0, 0, 1, -2.29, 0, 0.78, 58.3, 0, -71.1, 0, -71.1, 0],
                             [10, 0, 1.5, 0, 0, 1, -2.05, 0, 3, 111.3, 0, -34.4, 0, -34.3, 0],
                             [10, 0, 1, 0, -0.2, 1, -2.02, -0.13, 1.33, 66.8, 3.3, -56.5, -3, -56.6, 0],
                             [10, 0, 1, 0, -0.6, 1, -1.99, -0.38, 1.36, 67.4, 10, -55.7, -9, -55.7, 0], #Qz
                             [10, 0, 1, 0, 0, -1, 2.02, 0, 1.33, -66.8, 0, 56.6, 0, 56.6, 0],
                             [10, 0, 0, 1, 0, -1, 1.01, 0, 0.24, -27.3, 0, 76.4, 0, 16.4, 0],
                             [10, 0, -1, 0, 0, -1, 2.02, 0, 1.33, -66.8, 0, 56.6, 0, -123.4, 0],
                             [10, 0, 0, -1, 0, -1, 1.01, 0, 0.24, -27.3, 0, 76.4, 0, -163.6, 0],
                             [10, 0, 1, 1, 0, -1, 2.2, 0, 2.15, -88.7, 0, 45.7, 0, 28.7, 0],
                             [10, 0, 0.2, 0, 0, -1, 0.48, 0, 0.05, -12.6, 0, 83.7, 0, 83.7, 0],
                             [10, 0, 0.02, 0, 0, -1, 0.04984, 0, 0.00057, -1.3, 0, 89.4, 0, 89.4, 0],
                             [10, 5, 1, 0, 0, -1, 1.52, 0, 1.88, -78.2, 0, 39, 0, 39, 0],
                             [10, -5, 1, 0, 0, -1, 2.29, 0, 0.78, -58.3, 0, 71.1, 0, 71.1, 0],
                             [20, 0, 1, 0, 0, 1, -2.23, 0, 0.94, 45.8, 0, -67.1, 0, -67.1, 0],
                             [10, 0, 8, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 2],
                             [10, 20, 1, 0, 0, 1, nan, nan, nan, nan, nan, nan, nan, nan, 2]])

        a=3
        b=7
        c=10
        alpha=90
        beta=90
        gamma=120
        u=[1,0,0]
        v=[0,1,0]
        ol=OrientedLattice(a, b, c, alpha, beta, gamma)
        ol.setUFromVectors(u,v)

        (Ei, DE, H, K, L, sign, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_kf_angle,
         expected_out_plane_kf_angle, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
         expected_omega, expected_error_code) = test_case9.T

        HKL = vstack([H,K,L]).T
        pars = {'Ei': Ei, 'hkl': HKL, 'DeltaE': DE, 'sign': sign}
        expected_error_code = [ErrorCodes(ec) for ec in expected_error_code]
        self.run_test(ol, expected_Qx, expected_Qy, expected_Qz, expected_in_plane_Q_angle, expected_out_plane_Q_angle,
                 expected_in_plane_kf_angle, expected_out_plane_kf_angle, expected_omega, expected_error_code, **pars)
Ejemplo n.º 17
0
 def __init__(self, reflect=[0, 0, 2], **kargs):
     self.kargs = kargs
     self.pgo = OrientedLattice(2.461, 2.461, 6.708, 90, 90, 60)
     self.q = self.pgo.qFromHKL(reflect).norm()
     if 'lambdan' in self.kargs.keys():
         self.lambdan = self.kargs['lambdan']
         self.en = (9.045 / self.lambdan)**2
         self.k = 2 * math.pi / self.lambdan
         self.lambda2m2()
     if 'tth' in self.kargs.keys():
         self.tth = abs(self.kargs['tth'])
         self.monolambda()
     if 'en' in self.kargs.keys():
         self.en = self.kargs['en']
         self.lambdan = 9.045 / (math.sqrt(self.en))
         self.k = 2 * math.pi / self.lambdan
         self.lambda2m2()
Ejemplo n.º 18
0
    def test_create_nonorthogonal_transform_with_orthogonal_lattice_and_nonorthogonal_projections(
            self):
        lattice = OrientedLattice()  # default angle=90 degrees
        transform = NonOrthogonalTransform.from_lattice(lattice,
                                                        x_proj=(1, 0, 0),
                                                        y_proj=(1, 1, 0))

        self.assertAlmostEqual(transform.angle, 0.25 * np.pi)
Ejemplo n.º 19
0
def convertQSampleToHKL(ws,
                        OutputWorkspace='__md_hkl',
                        norm=None,
                        UB=None,
                        Extents=[-10, 10, -10, 10, -10, 10],
                        Bins=[101, 101, 101],
                        Append=False):
    ol = OrientedLattice()
    ol.setUB(UB)
    q1 = ol.qFromHKL([1, 0, 0])
    q2 = ol.qFromHKL([0, 1, 0])
    q3 = ol.qFromHKL([0, 0, 1])
    BinMD(InputWorkspace=ws,
          AxisAligned=False,
          NormalizeBasisVectors=False,
          BasisVector0='[H,0,0],A^-1,{},{},{}'.format(q1.X(), q1.Y(), q1.Z()),
          BasisVector1='[0,K,0],A^-1,{},{},{}'.format(q2.X(), q2.Y(), q2.Z()),
          BasisVector2='[0,0,L],A^-1,{},{},{}'.format(q3.X(), q3.Y(), q3.Z()),
          OutputExtents=Extents,
          OutputBins=Bins,
          TemporaryDataWorkspace=OutputWorkspace
          if Append and mtd.doesExist(OutputWorkspace) else None,
          OutputWorkspace=OutputWorkspace)
    if norm is not None:
        mtd[str(norm)].run().getGoniometer().setR(
            mtd[str(ws)].getExperimentInfo(0).run().getGoniometer().getR())
        convertToHKL(norm,
                     OutputWorkspace=str(OutputWorkspace) + '_norm',
                     UB=UB,
                     Extents=Extents,
                     Bins=Bins,
                     Append=Append)
    return OutputWorkspace
Ejemplo n.º 20
0
def _create_mock_workspace(ws_type,
                           coords: SpecialCoordinateSystem = None,
                           has_oriented_lattice: bool = None,
                           ndims: int = 2):
    """
    :param ws_type: Used this as spec for Mock
    :param coords: MD coordinate system for MD workspaces
    :param has_oriented_lattice: If the mock should claim to have an attached a lattice
    :param ndims: The number of dimensions
    """
    ws = MagicMock(spec=ws_type)
    if hasattr(ws, 'getExperimentInfo'):
        ws.getNumDims.return_value = ndims
        ws.getNumNonIntegratedDims.return_value = ndims
        if ws_type == IMDHistoWorkspace:
            ws.isMDHistoWorkspace.return_value = True
            ws.getNonIntegratedDimensions.return_value = [
                MagicMock(), MagicMock()
            ]
            ws.hasOriginalWorkspace.return_value = False
            basis_mat = np.eye(ndims)
            ws.getBasisVector.side_effect = lambda idim: basis_mat[:, idim]
        else:
            ws.isMDHistoWorkspace.return_value = False

        ws.getSpecialCoordinateSystem.return_value = coords
        run = MagicMock()
        run.get.return_value = MagicMock()
        run.get().value = np.eye(3).flatten()  # proj matrix is always 3x3
        expt_info = MagicMock()
        sample = MagicMock()
        sample.hasOrientedLattice.return_value = has_oriented_lattice
        if has_oriented_lattice:
            lattice = OrientedLattice(1, 1, 1, 90, 90, 90)
            sample.getOrientedLattice.return_value = lattice
        expt_info.sample.return_value = sample
        expt_info.run.return_value = run
        ws.getExperimentInfo.return_value = expt_info
        ws.getExperimentInfo().sample()
    elif hasattr(ws, 'getNumberHistograms'):
        ws.getNumDims.return_value = 2
        ws.getNumberHistograms.return_value = 3
        mock_dimension = MagicMock()
        mock_dimension.getNBins.return_value = 3
        ws.getDimension.return_value = mock_dimension
    return ws
Ejemplo n.º 21
0
 def run_test(v1, v2):
     cell = OrientedLattice()
     testhelpers.assertRaisesNothing(self, cell.setUFromVectors, v1, v2)
     rot = cell.getUB();
     expected = np.array([(0,1.,0.), (0.,0.,1.), (1.,0.,0.)])
     np.testing.assert_array_almost_equal(expected, rot, 8)
Ejemplo n.º 22
0
    def plot_Qpeaks(self):
        proj3d.persp_transformation = self.orthogonal_proj
        try:
            # Find size of screen
            import curses
            stdscr = curses.initscr()
            self.screen_x, self.screen_y = stdscr.getmaxyx()
            self.screen_x = min(self.screen_x, self.screen_y)
            self.screen_y = self.screen_x
        except:
            self.screen_x = 40
            self.screen_y = 40
        plt.rcParams.update({'font.size': 10})
        if len(self.mod) == 0:
            IndexPeaks(PeaksWorkspace=self.peaks_ws,
                       Tolerance=self.tolerance,
                       RoundHKLs=False,
                       CommonUBForAll=True)
        elif len(self.mod) > 0:
            IndexPeaksWithSatellites(PeaksWorkspace=self.peaks_ws,
                                     RoundHKLs=False,
                                     ModVector1=self.mod,
                                     MaxOrder=1)
        npeaksTotal = self.peaks_ws.getNumberPeaks()
        self.c = []
        self.x = []
        self.y = []
        self.z = []
        self.s = []
        for i in range(npeaksTotal):
            peak = self.peaks_ws.getPeak(i)
            hklp = V3D(peak.getH() - math.floor(peak.getH()),
                       peak.getK() - math.floor(peak.getK()),
                       peak.getL() - math.floor(peak.getL()))
            if peak.getSigmaIntensity() != 0.0:
                IsigI = peak.getIntensity() / peak.getSigmaIntensity()
            else:
                IsigI = 0.0
            #if IsigI < 50:
            #continue
            intensity = max(self.minIntensity, peak.getIntensity())
            for i in range(-1, 1):
                for j in range(-1, 1):
                    for k in range(-1, 1):
                        if (abs(hklp[0] + i) < 1.0 and abs(hklp[1] + j) < 1.0
                                and abs(hklp[2] + k) < 1.0):
                            self.x.append(hklp[0] + i)
                            self.y.append(hklp[1] + j)
                            self.z.append(hklp[2] + k)
                            self.c.append(intensity)
                            self.s.append(5)
        nPts = 100
        x_grid = np.linspace(-1, 1, nPts + 1)
        x_half = np.zeros(nPts)
        for j in range(nPts):
            x_half[j] = 0.5 * (x_grid[j] + x_grid[j + 1])
        sumIntensityX = np.zeros(nPts)
        for i in range(len(self.x)):
            for j in range(nPts):
                if self.x[i] > x_grid[j] and self.x[i] < x_grid[j + 1]:
                    sumIntensityX[j] = sumIntensityX[j] + self.c[i]
        sumIntensityY = np.zeros(nPts)
        for i in range(len(self.y)):
            for j in range(nPts):
                if self.y[i] > x_grid[j] and self.y[i] < x_grid[j + 1]:
                    sumIntensityY[j] = sumIntensityY[j] + self.c[i]
        sumIntensityZ = np.zeros(nPts)
        for i in range(len(self.z)):
            for j in range(nPts):
                if self.z[i] > x_grid[j] and self.z[i] < x_grid[j + 1]:
                    sumIntensityZ[j] = sumIntensityZ[j] + self.c[i]
        # Plot figure with subplots of different sizes
        fig = plt.figure("Modulated Structures",
                         figsize=(self.screen_x, self.screen_y))
        # set up subplot grid
        gridspec.GridSpec(3, 3)
        ax = plt.subplot2grid((3, 3), (0, 2))
        plt.plot(x_half, sumIntensityX)
        maxGrid = "max\n"
        for i in range(2, nPts - 2):
            if abs(x_half[i]) > 0.55 or abs(x_half[i]) < 0.05:
                continue
            if sumIntensityX[i] > sumIntensityX[
                    i - 1] and sumIntensityX[i] > sumIntensityX[
                        i + 1] and sumIntensityX[i - 1] > sumIntensityX[
                            i - 2] and sumIntensityX[i + 1] > sumIntensityX[i +
                                                                            2]:
                maxGrid += "{:f}\n".format(x_half[i])
        ax.text(0.05, 0.60, maxGrid, fontsize=10, transform=ax.transAxes)
        ax.set_yscale('log')
        ax.set_xlabel('H')
        ax.set_ylabel(r'$\Sigma$I')
        ax = plt.subplot2grid((3, 3), (1, 2))
        plt.plot(x_half, sumIntensityY)
        maxGrid = "max\n"
        for i in range(2, nPts - 2):
            if abs(x_half[i]) > 0.5 or abs(x_half[i]) < 0.05:
                continue
            if sumIntensityY[i] > sumIntensityY[
                    i - 1] and sumIntensityY[i] > sumIntensityY[
                        i + 1] and sumIntensityY[i - 1] > sumIntensityY[
                            i - 2] and sumIntensityY[i + 1] > sumIntensityY[i +
                                                                            2]:
                maxGrid += "{:f}\n".format(x_half[i])
        ax.text(0.05, 0.60, maxGrid, fontsize=10, transform=ax.transAxes)
        ax.set_yscale('log')
        ax.set_xlabel('K')
        ax.set_ylabel(r'$\Sigma$I')
        ax = plt.subplot2grid((3, 3), (2, 2))
        plt.plot(x_half, sumIntensityZ)
        maxGrid = "max\n"
        for i in range(2, nPts - 2):
            if abs(x_half[i]) > 0.5 or abs(x_half[i]) < 0.05:
                continue
            if sumIntensityZ[i] > sumIntensityZ[
                    i - 1] and sumIntensityZ[i] > sumIntensityZ[
                        i + 1] and sumIntensityZ[i - 1] > sumIntensityZ[
                            i - 2] and sumIntensityZ[i + 1] > sumIntensityZ[i +
                                                                            2]:
                maxGrid += "{:f}\n".format(x_half[i])
        ax.text(0.05, 0.60, maxGrid, fontsize=10, transform=ax.transAxes)
        ax.set_yscale('log')
        ax.set_xlabel('L')
        ax.set_ylabel(r'$\Sigma$I')

        vmin = min(self.c)
        vmax = max(self.c)
        logNorm = colors.LogNorm(vmin=vmin, vmax=vmax)
        self.axP = plt.subplot2grid((3, 3), (0, 0),
                                    colspan=2,
                                    rowspan=3,
                                    projection='3d')
        sp = self.axP.scatter(self.x,
                              self.y,
                              self.z,
                              c=self.c,
                              vmin=vmin,
                              vmax=vmax,
                              norm=logNorm,
                              s=self.s,
                              cmap='rainbow',
                              picker=True,
                              alpha=0.2)

        self.props = dict(boxstyle='round', facecolor='wheat', alpha=1.0)

        #cid = fig.canvas.mpl_connect('pick_event', self.onpick3)
        pid = fig.canvas.mpl_connect('key_press_event', self.onpress)

        try:
            lattice = self.peaks_ws.sample().getOrientedLattice()
        except:
            lattice = OrientedLattice(1, 1, 1)
        astar = V3D(0.5, 0, 0)
        bstar = V3D(0, 0.5, 0)
        cstar = V3D(0, 0, 0.5)
        hkls = np.array(
            [np.array([x, y, z]) for x, y, z in zip(self.x, self.y, self.z)])
        labels, centroids = self.dbscan(hkls, eps=.0425, min_points=6)

        i = 0
        modTest = str(self.peaks_ws.getPeak(0).getRunNumber())
        lastRun = str(self.peaks_ws.getPeak(npeaksTotal - 1).getRunNumber())
        if lastRun != modTest:
            modTest = modTest + "-" + lastRun
        modTest = modTest + " Type a, b, or c for axis alignment"
        for x in centroids:
            self.axP.plot([x[0]], [x[1]], [x[2]],
                          'wo',
                          ms=40,
                          markerfacecolor="None",
                          markeredgecolor='red',
                          markeredgewidth=3)
            if x[0] * x[0] + x[1] * x[1] + x[2] * x[2] > 0.01 and x[
                    0] >= -0.5 and x[1] >= -0.5 and x[2] >= -0.5 and x[
                        0] <= 0.5 and x[1] <= 0.5 and x[2] <= 0.5:
                modTest += "\nModulation Vector = " + "{:.3f}".format(
                    x[0]) + ", " + "{:.3f}".format(
                        x[1]) + ", " + "{:.3f}".format(x[2])
                if len(self.mod) == 0:
                    self.mod = "{:.3f}".format(x[0]) + "," + "{:.3f}".format(
                        x[1]) + "," + "{:.3f}".format(x[2])
                    IndexPeaksWithSatellites(PeaksWorkspace=self.peaks_ws,
                                             RoundHKLs=False,
                                             ModVector1=self.mod,
                                             MaxOrder=1)

        self.axP.plot([0, astar[0]], [0, astar[1]], [0, astar[2]], color='r')
        self.axP.text(astar[0],
                      astar[1],
                      astar[2],
                      '%s' % ('a*'),
                      size=20,
                      zorder=1,
                      color='r')
        self.axP.plot([0, bstar[0]], [0, bstar[1]], [0, bstar[2]], color='b')
        self.axP.text(bstar[0],
                      bstar[1],
                      bstar[2],
                      '%s' % ('b*'),
                      size=20,
                      zorder=1,
                      color='b')
        self.axP.plot([0, cstar[0]], [0, cstar[1]], [0, cstar[2]], color='g')
        self.axP.text(cstar[0],
                      cstar[1],
                      cstar[2],
                      '%s' % ('c*'),
                      size=20,
                      zorder=1,
                      color='g')

        self.axP.text2D(0.05,
                        0.80,
                        modTest + "\nLattice = " + " " +
                        "{:.3f}".format(lattice.a()) + " " +
                        "{:.3f}".format(lattice.b()) + " " +
                        "{:.3f}".format(lattice.c()) + " " +
                        "{:.3f}".format(lattice.alpha()) + " " +
                        "{:.3f}".format(lattice.beta()) + " " +
                        "{:.3f}".format(lattice.gamma()) + "\nError = " + " " +
                        "{:.3E}".format(lattice.errora()) + " " +
                        "{:.3E}".format(lattice.errorb()) + " " +
                        "{:.3E}".format(lattice.errorc()) + " " +
                        "{:.3E}".format(lattice.erroralpha()) + " " +
                        "{:.3E}".format(lattice.errorbeta()) + " " +
                        "{:.3E}".format(lattice.errorgamma()),
                        fontsize=10,
                        transform=self.axP.transAxes)
        self.axP.set_xlabel('H')
        self.axP.set_ylabel('K')
        self.axP.set_zlabel('L')

        # Create cubic bounding box to simulate equal aspect ratio
        max_range = max([
            max(self.x) - min(self.x),
            max(self.y) - min(self.y),
            max(self.z) - min(self.z)
        ])
        Xb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, -1:2:2][0].flatten(
        ) + 0.5 * (max(self.x) + min(self.x))
        Yb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, -1:2:2][1].flatten(
        ) + 0.5 * (max(self.y) + min(self.y))
        Zb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, -1:2:2][2].flatten(
        ) + 0.5 * (max(self.z) + min(self.z))
        # Comment or uncomment following both lines to test the fake bounding box:
        for xb, yb, zb in zip(Xb, Yb, Zb):
            self.axP.plot([xb], [yb], [zb], 'w')
        plt.show()
        #fig.canvas.mpl_disconnect(cid)
        fig.canvas.mpl_disconnect(pid)
Ejemplo n.º 23
0
def _qangle_validate_inputs(
        hkl: np.array, Ei: float or np.array, DeltaE: float or np.array,
        sign: float or np.array, lattice: OrientedLattice,
        detector_constraints: bool, horizontal_extent: np.array,
        vertical_extent: np.array, horizontal_extent_low: np.array,
        vertical_extent_low: np.array, goniometer_constraints: bool,
        goniometer_range):
    """
    Validate inputs for qangle function, according to the rules for
    that function
    """
    try:
        len_hkl = len(hkl)
        if len(hkl[0]) != 3:
            raise ValueError()
    except (TypeError, ValueError):
        raise ValueError('hkl is not an array of triplets')

    try:
        # check if float
        Ei = float(Ei)
        Ei = np.full(len_hkl, Ei)
    except ValueError:
        raise ValueError('Ei is not a float or numpy array')
    except TypeError:
        if len(Ei) != len_hkl:
            raise ValueError('Ei has different length than hkl')
    try:
        # check if float
        DeltaE = float(DeltaE)
        DeltaE = np.full(len_hkl, DeltaE)
    except ValueError:
        raise ValueError('DeltaE is not a float or numpy array')
    except TypeError:
        if len(DeltaE) != len_hkl:
            raise ValueError('DeltaE has different length than hkl')

    try:
        # check if int
        sign = int(sign)
        sign = np.full(len_hkl, sign)
    except ValueError:
        raise ValueError('sign is not an int or numpy array')
    except TypeError:
        if len(sign) != len_hkl:
            raise ValueError('sign has different length than hkl')

    try:
        UB = lattice.getUB() * 2. * np.pi
    except:
        raise ValueError("Can't get the UB matrix from the lattice object")

    # inputs for geometry and goniometer constraints
    if detector_constraints:
        if horizontal_extent[0] < -180 or horizontal_extent[
                1] < horizontal_extent[0] or horizontal_extent[1] > 180:
            raise ValueError(
                f"Horizontal constraints must obey -180 <= horizontal_extent[0]"
                f" ({horizontal_extent[0]}) <= horizontal_extent[1] ({horizontal_extent[1]})<=180"
            )
        if vertical_extent[0] < -180 or vertical_extent[1] < vertical_extent[
                0] or vertical_extent[1] > 180:
            raise ValueError(
                f"Vertical constraints must obey -180 <= vertical_extent[0] ({vertical_extent[0]}) "
                f"<= vertical_extent[1] ({vertical_extent[1]}) <=180")
        if horizontal_extent_low[0] < -180 or horizontal_extent_low[
                1] < horizontal_extent_low[0] or horizontal_extent_low[1] > 180:
            raise ValueError(
                f"Horizontal constraints must obey -180 <= horizontal_extent_low[0]"
                f" ({horizontal_extent_low[0]}) <= horizontal_extent_low[1] ({horizontal_extent_low[1]}) <=180"
            )
        if vertical_extent_low[0] < -180 or vertical_extent_low[
                1] < vertical_extent_low[0] or vertical_extent_low[1] > 180:
            raise ValueError(
                f"Vertical constraints must obey -180 <= vertical_extent_low[0] ({vertical_extent_low[0]}) "
                f"<= vertical_extent_low[1] ({vertical_extent_low[1]}) <=180")

    if goniometer_constraints:
        if goniometer_range[1]<goniometer_range[0] or \
           goniometer_range[0]<-180. or goniometer_range[1]>180.:
            raise ValueError("goniometer_range must be an increasing array, "
                             "with both limits between -180 and 180 degrees")

    return (Ei, DeltaE, sign, UB)
Ejemplo n.º 24
0
 def run_test(v1, v2):
     cell = OrientedLattice()
     testhelpers.assertRaisesNothing(self, cell.setUFromVectors, v1, v2)
     rot = cell.getUB()
     expected = np.array([(0, 1., 0.), (0., 0., 1.), (1., 0., 0.)])
     np.testing.assert_array_almost_equal(expected, rot, 8)
Ejemplo n.º 25
0
from mantid.simpleapi import *
from mantid.geometry import OrientedLattice

van = LoadNexus(
    '/HFIR/HB2C/IPTS-7776/shared/autoreduce/HB2C_{}.nxs'.format(6558))
LoadIsawUB('van', '/SNS/users/rwp/wand/single5/PNO_T.mat')
ub = mtd['van'].sample().getOrientedLattice().getUB().copy()

ol = OrientedLattice()
ol.setUB(ub)
q1 = ol.qFromHKL([1, 0, 0])
q2 = ol.qFromHKL([0, 1, 0])
q3 = ol.qFromHKL([0, 0, 1])

if 'data' in mtd:
    mtd.remove('data')

if 'norm' in mtd:
    mtd.remove('norm')

for run in range(4756, 6558, 1):
    print(run)
    md = LoadMD(
        Filename='/HFIR/HB2C/IPTS-7776/shared/autoreduce/HB2C_{}_MDE.nxs'.
        format(run))
    mtd['van'].run().getGoniometer().setR(
        mtd['md'].getExperimentInfo(0).run().getGoniometer().getR())

    #BinMD(InputWorkspace='md', OutputWorkspace='mdh', AlignedDim0='Q_sample_x,-10,10,401', AlignedDim1='Q_sample_y,-1,1,41', AlignedDim2='Q_sample_z,-10,10,401')
    BinMD(InputWorkspace='md',
          OutputWorkspace='mdh',
Ejemplo n.º 26
0
    def test_simple_values(self):
        u1 = OrientedLattice()
        self.assertEquals(u1.a1(), 1)
        self.assertEquals(u1.alpha(), 90)

        u2 = OrientedLattice(3, 4, 5)
        self.assertAlmostEqual(u2.b1(), 1. / 3., 10)
        self.assertAlmostEqual(u2.alphastar(), 90, 10)
        u3 = u2
        self.assertAlmostEqual(u3.volume(), 1. / u2.recVolume(), 10)
        u2.seta(3)
        self.assertAlmostEqual(u2.a(), 3, 10)
Ejemplo n.º 27
0
      OutputWorkspace='tzero2D',
      Params='0.1,-0.005,20')
DiffractionFocussing('tzero2D',
                     OutputWorkspace='tzero2D',
                     GroupingWorkspace='group')

DReference = [
    0.9179, 0.9600, 1.0451, 1.1085, 1.2458, 1.3576, 1.6374, 1.9200, 3.1353
]  # Si


def get_d(ol, h, k, l):
    return 2 * np.pi / np.linalg.norm(ol.qFromHKL([h, k, l]))


ol = OrientedLattice(3.905044, 3.905044, 11.166629, 90, 90, 90)

DReference = [
    get_d(ol, 0, 0, 1),
    get_d(ol, 0, 0, 2),
    get_d(ol, 1, 0, 0),
    get_d(ol, 0, 0, 3),
    #get_d(ol, 1, 0, 1), #0
    get_d(ol, 1, 0, 2),
    #get_d(ol, 0, 0, 4), #0
    get_d(ol, 1, 1, 0),
    get_d(ol, 1, 0, 3),
    get_d(ol, 1, 1, 1),
    get_d(ol, 1, 1, 2),
    get_d(ol, 1, 0, 4),
    get_d(ol, 0, 0, 5),
from mantid.simpleapi import *
from mantid.geometry import OrientedLattice
from itertools import permutations
import numpy as np

ol = OrientedLattice(5, 7, 12, 90, 90, 120)
ub = ol.getUB()
print(ub)

peaks = CreatePeaksWorkspace(NumberOfPeaks=0)

peaks.addPeak(peaks.createPeakQSample(2 * np.pi * np.dot(ub, [1, 1, 1])))
peaks.addPeak(peaks.createPeakQSample(2 * np.pi * np.dot(ub, [1, 1, 0])))
peaks.addPeak(peaks.createPeakQSample(2 * np.pi * np.dot(ub, [1, 2, 0])))

peaks2 = CreatePeaksWorkspace(NumberOfPeaks=0)

peaks2.addPeak(peaks2.createPeakQSample(2 * np.pi * np.dot(ub, [1, 1, 1])))
peaks2.addPeak(peaks2.createPeakQSample(2 * np.pi * np.dot(ub, [1, 1, 0])))
peaks2.addPeak(peaks2.createPeakQSample(2 * np.pi * np.dot(ub, [1, 2, 0])))

CompareWorkspaces(peaks, peaks2, Tolerance=1e-4)

ws = CreateSampleWorkspace()
peaks = CreatePeaksWorkspace(InstrumentWorkspace='ws')
peaks2 = CreatePeaksWorkspace(InstrumentWorkspace='ws')
peaks.getPeak(0).setRunNumber(123)
CompareWorkspaces(peaks, peaks2, Tolerance=1e-4)
Ejemplo n.º 29
0
class Scisoft():
    def __init__(self, point):
        # input  : qe
        # output : qe+tas
        self.point = point
        self.qe_para()
        self.qe_limit()
        if self.limit_qe == 1:
            self.scisoft()
            if tp.ModeChoice.mode == 3:
                # add sample stick rotation s0
                self.scisoft_premium()
                self.tas = tl.TasLimit(self.tas).point
            else:
                self.tas = tl.TasLimit(self.tas).point
        else:
            self.tas = pd.Series(data=None,
                                 index=tp.TasStatus.tas_status.index.drop(
                                     ['mts', 'sta', 'dtx']).copy())
            self.tas['s1s2_limit'] = 1
            self.tas['soft_limit'] = 1
        self.tas['qe_limit'] = self.limit_qe
        # raise Exception as

    def qe_para(self):
        self.orien = OrientedLattice(*Alignment.para)
        self.para = Alignment.para
        self.hkl = [self.point.h, self.point.k, self.point.l]
        self.len = self.orien.qFromHKL(self.hkl).norm()
        self.mono = Monochromator(en=self.point.ei)
        self.ana = Monochromator(en=self.point.ef)

    def qe_limit(self):
        if self.mono.k + self.ana.k < self.len:
            self.limit_qe = tp.LimitNumb.Modenumb[tp.LimitNumb.mode]
        else:
            self.limit_qe = 1

    def angdif(self):
        # angle between point and refa
        p0 = self.hkl
        p1 = Alignment.refa
        p2 = Alignment.refb
        theta1 = self.orien.recAngle(p0[0], p0[1], p0[2], p1.h, p1.k, p1.l)
        valcos1 = math.cos(math.radians(theta1))
        theta2 = self.orien.recAngle(p0[0], p0[1], p0[2], p2.h, p2.k, p2.l)
        valcos2 = math.cos(math.radians(theta2))
        if valcos1 * valcos2 == 0:
            self.angdiff = theta1 * (valcos1 + valcos2)
        else:
            self.angdiff = theta1 * abs(valcos2) / valcos2

    def scisoft(self):
        s2_value = (self.mono.k**2 + self.ana.k**2 -
                    self.len**2) / 2.0 / self.mono.k / self.ana.k
        self.tth = math.degrees(math.acos(s2_value))
        self.angdif()
        s2 = self.tth * tp.TasConfig.tas_config.s
        s1dif = (self.mono.k**2 - self.ana.k**2 +
                 self.len**2) / 2.0 / self.mono.k / self.len
        s1dif = math.acos(s1dif)
        s1dif = s1dif * 180 / math.pi
        s1 = -1 * Alignment.delta - self.angdiff - s1dif * tp.TasConfig.tas_config.s
        index = ['m1', 'm2', 's1', 's2', 'a1', 'a2']
        self.tas = pd.Series(data=[
            self.mono.tth / 2, self.mono.tth, s1, s2, self.ana.tth / 2,
            self.ana.tth
        ],
                             index=index)

    def s1p_split(self):
        # s0 first : magnet
        # s1 first : crystat
        s1p = self.tas.s1
        delta_s1p = s1p - (tp.TasStatus.tas_status.s1 +
                           tp.TasStatus.tas_status.s0)
        if tp.SplitMode.mode == 0:
            s0 = tp.TasStatus.tas_status.s0 + delta_s1p
            s1 = tp.TasStatus.tas_status.s1
        elif tp.SplitMode.mode == 1:
            s1 = tp.TasStatus.tas_status.s1 + delta_s1p
            s0 = tp.TasStatus.tas_status.s0
        return pd.Series(data=[s0, s1], index=['s0', 's1'])

    def scisoft_premium(self):
        junk = self.tas
        addition = self.s1p_split()
        junk.pop('s1')
        self.tas = junk.append(addition)
Ejemplo n.º 30
0
    def runTest(self):
        # Na Mn Cl3
        # R -3 H (148)
        # 6.592 6.592 18.585177 90 90 120

        # UB/wavelength from /HFIR/HB3A/IPTS-25470/shared/autoreduce/HB3A_exp0769_scan0040.nxs

        ub = np.array([[1.20297e-01, 1.70416e-01, 1.43000e-04],
                       [8.16000e-04, -8.16000e-04, 5.38040e-02],
                       [1.27324e-01, -4.05110e-02, -4.81000e-04]])

        wavelength = 1.553

        # create fake MDEventWorkspace, similar to what is expected from exp769 after loading with HB3AAdjustSampleNorm
        MD_Q_sample = CreateMDWorkspace(
            Dimensions='3',
            Extents='-5,5,-5,5,-5,5',
            Names='Q_sample_x,Q_sample_y,Q_sample_z',
            Units='rlu,rlu,rlu',
            Frames='QSample,QSample,QSample')

        inst = LoadEmptyInstrument(InstrumentName='HB3A')
        AddTimeSeriesLog(inst, 'omega', '2010-01-01T00:00:00', 0.)
        AddTimeSeriesLog(inst, 'phi', '2010-01-01T00:00:00', 0.)
        AddTimeSeriesLog(inst, 'chi', '2010-01-01T00:00:00', 0.)
        MD_Q_sample.addExperimentInfo(inst)
        SetUB(MD_Q_sample, UB=ub)

        ol = OrientedLattice()
        ol.setUB(ub)

        sg = SpaceGroupFactory.createSpaceGroup("R -3")

        hkl = []
        sat_hkl = []

        for h in range(0, 6):
            for k in range(0, 6):
                for l in range(0, 11):
                    if sg.isAllowedReflection([h, k, l]):
                        if h == k == l == 0:
                            continue
                        q = V3D(h, k, l)
                        q_sample = ol.qFromHKL(q)
                        if not np.any(np.array(q_sample) > 5):
                            hkl.append(q)
                            FakeMDEventData(
                                MD_Q_sample,
                                PeakParams='1000,{},{},{},0.05'.format(
                                    *q_sample))
                        # satellite peaks at 0,0,+1.5
                        q = V3D(h, k, l + 1.5)
                        q_sample = ol.qFromHKL(q)
                        if not np.any(np.array(q_sample) > 5):
                            sat_hkl.append(q)
                            FakeMDEventData(
                                MD_Q_sample,
                                PeakParams='100,{},{},{},0.02'.format(
                                    *q_sample))
                        # satellite peaks at 0,0,-1.5
                        q = V3D(h, k, l - 1.5)
                        q_sample = ol.qFromHKL(q)
                        if not np.any(np.array(q_sample) > 5):
                            sat_hkl.append(q)
                            FakeMDEventData(
                                MD_Q_sample,
                                PeakParams='100,{},{},{},0.02'.format(
                                    *q_sample))

        # Check that this fake workpsace gives us the expected UB
        peaks = FindPeaksMD(MD_Q_sample,
                            PeakDistanceThreshold=1,
                            OutputType='LeanElasticPeak')
        FindUBUsingFFT(peaks, MinD=5, MaxD=20)
        ShowPossibleCells(peaks)
        SelectCellOfType(peaks,
                         CellType='Rhombohedral',
                         Centering='R',
                         Apply=True)
        OptimizeLatticeForCellType(peaks, CellType='Hexagonal', Apply=True)
        found_ol = peaks.sample().getOrientedLattice()
        self.assertAlmostEqual(found_ol.a(), 6.592, places=2)
        self.assertAlmostEqual(found_ol.b(), 6.592, places=2)
        self.assertAlmostEqual(found_ol.c(), 18.585177, places=2)
        self.assertAlmostEqual(found_ol.alpha(), 90)
        self.assertAlmostEqual(found_ol.beta(), 90)
        self.assertAlmostEqual(found_ol.gamma(), 120)

        # nuclear peaks
        predict = HB3APredictPeaks(
            MD_Q_sample,
            Wavelength=wavelength,
            ReflectionCondition='Rhombohedrally centred, obverse',
            SatellitePeaks=True,
            IncludeIntegerHKL=True)
        predict = HB3AIntegratePeaks(MD_Q_sample, predict, 0.25)

        self.assertEqual(predict.getNumberPeaks(), 66)
        # check that the found peaks are expected
        for n in range(predict.getNumberPeaks()):
            HKL = predict.getPeak(n).getHKL()
            self.assertTrue(HKL in hkl, msg=f"Peak {n} with HKL={HKL}")

        # magnetic peaks
        satellites = HB3APredictPeaks(
            MD_Q_sample,
            Wavelength=wavelength,
            ReflectionCondition='Rhombohedrally centred, obverse',
            SatellitePeaks=True,
            ModVector1='0,0,1.5',
            MaxOrder=1,
            IncludeIntegerHKL=False)
        satellites = HB3AIntegratePeaks(MD_Q_sample, satellites, 0.1)

        self.assertEqual(satellites.getNumberPeaks(), 80)
        # check that the found peaks are expected
        for n in range(satellites.getNumberPeaks()):
            HKL = satellites.getPeak(n).getHKL()
            self.assertTrue(HKL in sat_hkl, msg=f"Peak {n} with HKL={HKL}")