class SixCircleGammaOnArmGeometry(VliegGeometry):
    """
    This six-circle diffractometer geometry simply passes through the
    angles from a six circle diffractometer with the same geometry and
    angle names as those defined in Vliegs's paper defined internally.
    """

    def __init__(self):
        VliegGeometry.__init__(
            self,
            name='sixc_gamma_on_arm',
            supported_mode_groups=('fourc', 'fivecFixedGamma',
                                    'fivecFixedAlpha', 'zaxis'),
            fixed_parameters={},
            gamma_location='arm')

    def physical_angles_to_internal_position(self, physicalAngles):
        """ (a,d,g,o,c,p) = physicalAnglesToInternal(a,d,g,o,c,p)
        """
        assert (len(physicalAngles) == 6), "Wrong length of input list"
        return VliegPosition(*physicalAngles)

    def internal_position_to_physical_angles(self, internalPosition):
        """ (a,d,g,o,c,p) = physicalAnglesToInternal(a,d,g,o,c,p)
        """
        return internalPosition.totuple() class VliegPosition(AbstractPosition):
    """The position of all six diffractometer axis"""
    def __init__(self, alpha=None, delta=None, gamma=None, omega=None,
                 chi=None, phi=None):
        self.alpha = alpha
        self.delta = delta
        self.gamma = gamma
        self.omega = omega
        self.chi = chi
        self.phi = phi

    def clone(self):
        return VliegPosition(self.alpha, self.delta, self.gamma, self.omega,
                             self.chi, self.phi)

    def changeToRadians(self):
        self.alpha *= TORAD
        self.delta *= TORAD
        self.gamma *= TORAD
        self.omega *= TORAD
        self.chi *= TORAD
        self.phi *= TORAD

    def changeToDegrees(self):
        self.alpha *= TODEG
        self.delta *= TODEG
        self.gamma *= TODEG
        self.omega *= TODEG
        self.chi *= TODEG
        self.phi *= TODEG

    def inRadians(self):
        pos = self.clone()
        pos.changeToRadians()
        return pos

    def inDegrees(self):
        pos = self.clone()
        pos.changeToDegrees()
        return pos

    def nearlyEquals(self, pos2, maxnorm):
        for a, b in zip(self.totuple(), pos2.totuple()):
            if abs(a - b) > maxnorm:
                return False
        return True

    def totuple(self):
        return (self.alpha, self.delta, self.gamma, self.omega,
                self.chi, self.phi)

    def __str__(self):
        return ("VliegPosition(alpha %r delta: %r gamma: %r omega: %r chi: %r"
                "  phi: %r)" % self.totuple())

    def __repr__(self):
        return self.__str__()

    def __eq__(self, b):
        return self.nearlyEquals(b, .001) class SixCircle(YouGeometry):
    def __init__(self, beamline_axes_transform=None):
        YouGeometry.__init__(self, 'sixc', {}, beamline_axes_transform)

    def physical_angles_to_internal_position(self, physical_angle_tuple):
        # mu, delta, nu, eta, chi, phi
        return YouPosition(*physical_angle_tuple, unit='DEG')

    def internal_position_to_physical_angles(self, internal_position):
        clone_position = internal_position.clone()
        clone_position.changeToDegrees()
        return clone_position.totuple() class DummyHardwareAdapter(HardwareAdapter):

    def __init__(self, diffractometerAngleNames):
        super(self.__class__, self).__init__(diffractometerAngleNames)
#         HardwareAdapter.__init__(self, diffractometerAngleNames)

        self._position = [0.] * len(diffractometerAngleNames)
        self._upperLimitDict = {}
        self._lowerLimitDict = {}
        self._wavelength = 1.
        self.energyScannableMultiplierToGetKeV = 1
        self._name = "Dummy"

# Required methods

    def get_position(self):
        """
        pos = getDiffractometerPosition() -- returns the current physical
        diffractometer position as a list in degrees
        """
        return self._position

    def _set_position(self, pos):
        assert len(pos) == len(self.get_axes_names()), \
            "Wrong length of input list"
        self._position = pos

    position = property(get_position, _set_position)

    def get_energy(self):
        """energy = get_energy() -- returns energy in kEv  """
        if self._wavelength is None:
            raise DiffcalcException(
                "Energy or wavelength have not been set")
        return (12.39842 /
                (self._wavelength * self.energyScannableMultiplierToGetKeV))

    def _set_energy(self, energy):
        self._wavelength = 12.39842 / energy

    energy = property(get_energy, _set_energy)

    def get_wavelength(self):
        """wavelength = get_wavelength() -- returns wavelength in Angstroms"""
        if self._wavelength is None:
            raise DiffcalcException(
                "Energy or wavelength have not been set")
        return self._wavelength

    def _set_wavelength(self, wavelength):
        self._wavelength = wavelength

    wavelength = property(get_wavelength, _set_wavelength)

    def get_lower_limit(self, name):
        '''returns lower limits by axis name. Limit may be None if not set
        '''
        if name not in self._diffractometerAngleNames:
            raise ValueError("No angle called %s. Try one of: %s" %
                             (name, self._diffractometerAngleNames))
        return self._lowerLimitDict.get(name)

    def get_upper_limit(self, name):
        '''returns upper limit by axis name. Limit may be None if not set
        '''
        if name not in self._diffractometerAngleNames:
            raise ValueError("No angle called %s. Try one of: %s" %
                             name, self._diffractometerAngleNames)
        return self._upperLimitDict.get(name)

    def set_lower_limit(self, name, value):
        """value may be None to remove limit"""
        if name not in self._diffractometerAngleNames:
            raise ValueError(
                "Cannot set lower Diffcalc limit: No angle called %s. Try one "
                "of: %s" % (name, self._diffractometerAngleNames))
        if value is None:
            try:
                del self._lowerLimitDict[name]
            except KeyError:
                print ("WARNING: There was no lower Diffcalc limit %s set to "
                       "clear" % name)
        else:
            self._lowerLimitDict[name] = value

    def set_upper_limit(self, name, value):
        """value may be None to remove limit"""
        if name not in self._diffractometerAngleNames:
            raise ValueError(
                "Cannot set upper Diffcalc limit: No angle called %s. Try one "
                "of: %s" % (name, self._diffractometerAngleNames))
        if value is None:
            try:
                del self._upperLimitDict[name]
            except KeyError:
                print ("WARNING: There was no upper Diffcalc limit %s set to "
                       "clear" % name)
        else:
            self._upperLimitDict[name] = value

    def is_axis_value_within_limits(self, axis_name, value):
        if axis_name in self._upperLimitDict:
            if value > self._upperLimitDict[axis_name]:
                return False
        if axis_name in self._lowerLimitDict:
            if value < self._lowerLimitDict[axis_name]:
                return False
        return True def format_note(note):
def assert_array_almost_equal(first, second, places=7, msg=None, note=None):
def format_array(a, places):
def assert_2darray_almost_equal(first, second, places=7, msg=None, note=None):
def format_2darray(array, places):
def _array(m):
def assert_matrix_almost_equal(first, second, places=7, msg=None, note=None):
def assert_dict_almost_equal(first, second, places=7, msg=None, note=None):
def assert_second_dict_almost_in_first(value, expected, places=7, msg=None):
def assert_iterable_almost_equal(first, second, places=7, msg=None, note=None):
def meq_(a, b):
def wrap_command_to_print_calls(f, user_syntax=True):
    def print_with_user_syntax(f, args):
    def print_with_python_syntax(f, args):
    def print_and_call_command(f, args):
    def wrapper(*args, **kwds): class UbCalculationNonPersister(UBCalculationPersister):
    """
    A version of UBCalculationPersister that simply stores to a local dict
    rather than a database. Useful for testing.
    """
    def __init__(self):
        self.shelf = dict()
        self.description = 'memory only'
        self.directory = ""
        self.encoder = None class UBCalculationJSONPersister(object):

    def __init__(self, directory, encoder):
        check_directory_appropriate(directory)
        self.directory = directory
        self.description = directory
        self.encoder = encoder
        
    def filepath(self, name):
        return os.path.join(self.directory, name + '.json')
        
    def save(self, state, name):
        # FORMAT = '%Y-%m-%d %H:%M:%S'
        # time_string = datetime.datetime.strftime(datetime.datetime.now(), FORMAT)
        with open(self.filepath(name), 'w') as f:
            json.dump(state, f, indent=4, cls=self.encoder)

    def load(self, name):
        with open(self.filepath(name), 'r') as f:
            return json.load(f)

    def list(self):  # @ReservedAssignment
        files = self._get_save_files()
        return [os.path.basename(f + '.json').split('.json')[0] for f in files]

    def list_metadata(self):       
        metadata = []
        for f in self._get_save_files():            
            dt = datetime.datetime.fromtimestamp(os.path.getmtime(f))
            metadata.append(dt.strftime('%d %b %Y (%H:%M)'))
        return metadata
    
    def _get_save_files(self):
        files = filter(os.path.isfile, glob.glob(os.path.join(self.directory, '*.json')))
        files.sort(key=lambda x: os.path.getmtime(x))
        files.reverse()
        return files

    def remove(self, name):
        os.remove(self.filepath(name)) class UBCalcStateEncoder(json.JSONEncoder):
    
    def default(self, obj):
        
        if isinstance(obj, UBCalcState):
            d = OrderedDict()
            d['name'] = obj.name
            d['crystal'] = obj.crystal
            d['reflist'] = obj.reflist
            d['orientlist'] = obj.orientlist
            d['tau'] = obj.tau
            d['sigma'] = obj.sigma
            d['reference'] = obj.reference
            d['surface'] = obj.surface
            d['u'] = obj.manual_U
            d['ub'] = obj.manual_UB
            d['or0'] = obj.or0
            d['or1'] = obj.or1
            
            return d
        
        if isinstance(obj, CrystalUnderTest):
            return repr([obj._name, obj._system, obj._a1, obj._a2, obj._a3, obj._alpha1 * TODEG,
                         obj._alpha2 * TODEG, obj._alpha3 * TODEG])
            
        if isinstance(obj, matrix):
            l = [', '.join((repr(e) for e in row)) for row in obj.tolist()]
            return l
        
        if isinstance(obj, ReflectionList):
            d = OrderedDict()
            for n, ref in enumerate(obj._reflist):
                d[str(n+1)] = ref
            return d

        if isinstance(obj, _Reflection):
            d = OrderedDict()
            d['tag'] = obj.tag
            d['hkl'] = repr([obj.h, obj.k, obj.l])
            d['pos'] = repr(list(obj.pos.totuple()))
            d['energy'] = obj.energy
            dt = eval(obj.time)  # e.g. --> datetime.datetime(2013, 8, 5, 15, 47, 7, 962432)
            d['time'] = None if dt is None else dt.isoformat()
            return d
        
        if isinstance(obj, OrientationList):
            d = OrderedDict()
            for n, orient in enumerate(obj._orientlist):
                d[str(n+1)] = orient
            return d

        if isinstance(obj, _Orientation):
            d = OrderedDict()
            d['tag'] = obj.tag
            d['hkl'] = repr([obj.h, obj.k, obj.l])
            d['xyz'] = repr([obj.x, obj.y, obj.z])
            d['pos'] = repr(list(obj.pos.totuple()))
            dt = eval(obj.time)  # e.g. --> datetime.datetime(2013, 8, 5, 15, 47, 7, 962432)
            d['time'] = None if dt is None else dt.isoformat()
            return d
        
        if isinstance(obj, YouReference):
            d = OrderedDict()
            if obj.n_hkl_configured is not None:
                d['n_hkl_configured'] = repr(obj.n_hkl_configured.T.tolist()[0])
            else:
                d['n_hkl_configured'] = None
            if obj.n_phi_configured is not None:
                d['n_phi_configured'] = repr(obj.n_phi_configured.T.tolist()[0])
            else:
                d['n_phi_configured'] = None
            return d
        
        
        return json.JSONEncoder.default(self, obj)

    @staticmethod
    def decode_ubcalcstate(state, geometry, diffractometer_axes_names, multiplier):

        # Backwards compatibility code
        orientlist_=OrientationList(geometry, diffractometer_axes_names, [])
        try:
            orientlist_=decode_orientlist(state['orientlist'], geometry, diffractometer_axes_names)
        except KeyError:
            pass
        try:
            surface_=decode_reference(state['surface'], settings.surface_vector, False)
        except KeyError:
            surface_ = YouReference(None)
            surface_._set_n_phi_configured(settings.surface_vector)
        return UBCalcState(
            name=state['name'],
            crystal=state['crystal'] and CrystalUnderTest(*eval(state['crystal'])),
            reflist=decode_reflist(state['reflist'], geometry, diffractometer_axes_names, multiplier),
            orientlist=orientlist_,
            tau=state['tau'],
            sigma=state['sigma'],
            manual_U=state['u'] and decode_matrix(state['u']),
            manual_UB=state['ub'] and decode_matrix(state['ub']),
            or0=state['or0'],
            or1=state['or1'],
            reference=decode_reference(state.get('reference', None), settings.reference_vector, True),
            surface=surface_
        ) class DiffcalcException(Exception):
    """Error caused by user misuse of diffraction calculator.
    """
    def __str__(self):
        lines = []
        for msg_line in self.message.split('\n'):
            lines.append('* ' + msg_line)
        width = max(len(l) for l in lines)
        lines.insert(0, '\n\n' + '*' * width)
        lines.append('*' * width)
        return '\n'.join(lines) class MockRawInput(object):
    def __init__(self, toReturnList):
        if type(toReturnList) != list:
            toReturnList = [toReturnList]
        self.toReturnList = toReturnList

    def __call__(self, prompt):
        toReturn = self.toReturnList.pop(0)
        if type(toReturn) != str:
            raise TypeError
        print prompt + toReturn
        return toReturn def xyz_rotation(u, angle):
    u = [list(u), [0, 0, 0], [0, 0, 0]]
    u = matrix(u) / norm(matrix(u))
    e11=u[0,0]**2+(1-u[0,0]**2)*cos(angle)
    e12=u[0,0]*u[0,1]*(1-cos(angle))-u[0,2]*sin(angle)
    e13=u[0,0]*u[0,2]*(1-cos(angle))+u[0,1]*sin(angle)
    e21=u[0,0]*u[0,1]*(1-cos(angle))+u[0,2]*sin(angle)
    e22=u[0,1]**2+(1-u[0,1]**2)*cos(angle)
    e23=u[0,1]*u[0,2]*(1-cos(angle))-u[0,0]*sin(angle)
    e31=u[0,0]*u[0,2]*(1-cos(angle))-u[0,1]*sin(angle)
    e32=u[0,1]*u[0,2]*(1-cos(angle))+u[0,0]*sin(angle)
    e33=u[0,2]**2+(1-u[0,2]**2)*cos(angle)
    return matrix([[e11,e12,e13],[e21,e22,e23],[e31,e32,e33]]) TODEG = 180 / pi TORAD = pi / 180 class CoordinateConverter(object):
    """Class for converting matrix objects between coordinate frames"""

    def __init__(self, transform=None):
        if transform is None:
            self.R = None
        elif type(transform) in (list, tuple, matrix):
            self.R = matrix(transform)
            self.nrow, self.ncol = self.R.shape
            if self.nrow != self.ncol:
                raise TypeError('Transformation matrix shape is invalid: %d x %d' % (self.nrow, self.ncol))
        else:
            raise TypeError('Invalid object type %s' % str(type(transform)))

    def transform(self, v, inv=False):
        if type(v) in (list, tuple, matrix):
            m = matrix(v)
        else:
            raise TypeError('Invalid object type %s' % str(type(m)))
        if self.R is None:
            return m
        nr, nc = m.shape
        if nc == 1:
            if nr != self.nrow:
                raise TypeError('Invalid number of rows: %d != %d'% (nr, self.nrow))
            if inv:
                return self.R.I * m
            else:
                return self.R * m
        elif nr == 1:
            if nc != self.ncol:
                raise TypeError('Invalid number of columns: %d != %d' % (nc, self.ncol))
            if inv:
                return m * self.R.I
            else:
                return m * self.R
        elif m.shape == self.R.shape:
            if inv:
                return self.R.I * m * self.R
            else:
                return self.R * m * self.R.I
        raise TypeError('Invalid matrix shape: %d x %d' % (nr, nc)) class VliegUbCalcStrategy(PaperSpecificUbCalcStrategy):

    def calculate_q_phi(self, pos):

        [ALPHA, DELTA, GAMMA, OMEGA, CHI, PHI] = createVliegMatrices(
           pos.alpha, pos.delta, pos.gamma, pos.omega, pos.chi, pos.phi)

        u1a = (DELTA * GAMMA - ALPHA.I) * y
        u1p = PHI.I * CHI.I * OMEGA.I * u1a
        return u1p def vliegAnglesToHkl(pos, wavelength, UBMatrix):
    """
    Returns hkl indices from pos object in radians.
    """
    wavevector = 2 * pi / wavelength

    # Create transformation matrices
    [ALPHA, DELTA, GAMMA, OMEGA, CHI, PHI] = createVliegMatrices(
        pos.alpha, pos.delta, pos.gamma, pos.omega, pos.chi, pos.phi)

    # Create the plane normal vector in the alpha axis coordinate frame
    qa = ((DELTA * GAMMA) - ALPHA.I) * matrix([[0], [wavevector], [0]])

    # Transform the plane normal vector from the alpha frame to reciprical
    # lattice frame.
    hkl = UBMatrix.I * PHI.I * CHI.I * OMEGA.I * qa

    return hkl[0, 0], hkl[1, 0], hkl[2, 0] def youAnglesToHkl(pos, wavelength, UBmatrix):
    """Calculate miller indices from position in radians.
    """

    [MU, DELTA, NU, ETA, CHI, PHI] = create_you_matrices(*pos.totuple())

    q_lab = (NU * DELTA - I) * matrix([[0], [2 * pi / wavelength], [0]])   # 12

    hkl = UBmatrix.I * PHI.I * CHI.I * ETA.I * MU.I * q_lab

    return hkl[0, 0], hkl[1, 0], hkl[2, 0] class YouUbCalcStrategy(PaperSpecificUbCalcStrategy):

    def calculate_q_phi(self, pos):

        [MU, DELTA, NU, ETA, CHI, PHI] = create_you_matrices(*pos.totuple())
        # Equation 12: Compute the momentum transfer vector in the lab  frame
        y = matrix('0; 1; 0')
        q_lab = (NU * DELTA - I) * y
        # Transform this into the phi frame.
        return PHI.I * CHI.I * ETA.I * MU.I * q_lab class YouPositionScenario(YouPosition):
class SessionScenario:
class CalculationScenario:
    def __init__(self, alpha=None, delta=None, gamma=None, omega=None,
                 chi=None, phi=None):
    def __init__(self):
    def __str__(self):
    def __init__(self, tag, package, mode, energy, modeToTest, modeNumber):
def sessions(P=VliegPosition): class YouPositionScenario(YouPosition):
    """Convert six-circle Vlieg diffractometer angles into 4S+2D You geometry"""
    def __init__(self, alpha=None, delta=None, gamma=None, omega=None,
                 chi=None, phi=None):
        self.mu = alpha
        self.eta = omega
        self.chi = chi
        self.phi = phi
        self.unit = 'DEG'
        asin_delta = asin(sin(delta*TORAD) * cos(gamma*TORAD))*TODEG  # Eq.(83)
        vals_delta = [asin_delta, 180. - asin_delta]
        idx, _ = min([(i, abs(delta - d)) for i, d in enumerate(vals_delta)], key=lambda x: x[1])
        self.delta = vals_delta[idx]
        sgn = sign(cos(self.delta * TORAD))
        self.nu = atan2(sgn*(cos(delta*TORAD)*cos(gamma*TORAD)*sin(alpha*TORAD) + cos(alpha*TORAD)*sin(gamma*TORAD)),
                        sgn*(cos(delta*TORAD)*cos(gamma*TORAD)*cos(alpha*TORAD) - sin(alpha*TORAD)*sin(gamma*TORAD)))*TODEG   # Eq.(84) NUNAME = 'gam'
from nose.tools import eq_  # @UnresolvedImport
from math import atan, sqrt
from nose import SkipTest
    from numpy import matrix
    from numjy import matrix
from diffcalc.hkl.vlieg.geometry import SixCircleGammaOnArmGeometry,\
    VliegPosition
from diffcalc.hkl.you.geometry import SixCircle
from diffcalc.hardware import DummyHardwareAdapter
from test.tools import assert_iterable_almost_equal, mneq_, arrayeq_
from diffcalc.ub.persistence import UbCalculationNonPersister,\
    UBCalculationJSONPersister
from diffcalc.ub.calcstate import UBCalcStateEncoder
from diffcalc.util import DiffcalcException, MockRawInput, xyz_rotation,\
    TODEG, TORAD, CoordinateConverter
from diffcalc.hkl.vlieg.calc import VliegUbCalcStrategy, vliegAnglesToHkl
from diffcalc.hkl.you.calc import youAnglesToHkl, YouUbCalcStrategy
from test.diffcalc import scenarios
from test.diffcalc.scenarios import YouPositionScenario
from diffcalc import settings
        from diffcalc.ub import ub
import tempfile
import os.path
import pytest
import diffcalc.util  # @UnusedImport
        self.ub.refineub([1, 1, 0], [0, 60, 0, 30, 0, 0])
        getLattice = self.ub.ubcalc._state.crystal.getLattice
        eq_(('xtal', sqrt(2.), sqrt(2.), 1, 90, 90, 90), getLattice())
        mneq_(self.ub.ubcalc.U, self._refineub_matrix,
              4, note="wrong U matrix after refinement")

    def testFitub(self):
        self.ub.newub('testfitub')
        for s in scenarios.sessions(settings.Pos)[-3:]:
            a, b, c, alpha, beta, gamma = s.lattice
            self.ub.clearref()
            for r in s.reflist:
                self.ub.addref(
                    [r.h, r.k, r.l], r.pos.totuple(), r.energy, r.tag)
            self.ub.setlat(s.name, s.system, *s.lattice)
            self.ub.calcub(s.ref1.tag, s.ref2.tag)

            init_latt = (1.06 * a, 1.07 * b, 0.94 * c,
                         1.05 * alpha, 1.06 * beta, 0.95 * gamma)
            self.ub.setlat(s.name, s.system, *init_latt)
            self.ub.addmiscut(3., [0.2, 0.8, 0.1])

            prepareRawInput(['y', 'y'])
            self.ub.fitub(*tuple(r.tag for r in s.reflist))
            assert self.ub.ubcalc._state.crystal._system == s.system
            mneq_(matrix((self.ub.ubcalc._state.crystal.getLattice()[1:])), matrix(s.lattice),
                  2, note="wrong lattice after fitting UB")
            mneq_(self.ub.ubcalc.U, matrix(s.umatrix),
                  3, note="wrong U matrix after fitting UB")

    def testC2th(self):
        self.ub.newub('testc2th')
        self.ub.setlat('cube', 1, 1, 1, 90, 90, 90)
        assert self.ub.c2th((0, 0, 1)) == pytest.approx(60)

    def testHKLangle(self):
        self.ub.newub('testhklangle')
        self.ub.setlat('cube', 1, 1, 1, 90, 90, 90)
        assert self.ub.hklangle((0, 0, 1), (0, 0, 2)) == pytest.approx(0)
        assert self.ub.hklangle((0, 1, 0), (0, 0, 2)) == pytest.approx(90)
        assert self.ub.hklangle((1, 0, 0), (0, 0, 2)) == pytest.approx(90)
        assert self.ub.hklangle((1, 1, 0), (0, 0, 2)) == pytest.approx(90)
        assert self.ub.hklangle((0, 1, 1), (0, 0, 2)) == pytest.approx(45)
        assert self.ub.hklangle((1, 0, 1), (0, 0, 2)) == pytest.approx(45)
        assert self.ub.hklangle((1, 1, 1), (0, 0, 2)) == pytest.approx(atan(sqrt(2))*TODEG)

    def testSigtau(self):
        # sigtau [sig tau]
        with pytest.raises(TypeError):
            self.ub.sigtau(1)
        with pytest.raises(ValueError):
            self.ub.sigtau(1, 'a')
        self.ub.sigtau(1, 2)
        self.ub.sigtau(1, 2.0)
        eq_(self.ub.ubcalc.sigma, 1)
        eq_(self.ub.ubcalc.tau, 2.0)

    def testSigtauInteractive(self):
        prepareRawInput(['1', '2.'])
        self.ub.sigtau()
        eq_(self.ub.ubcalc.sigma, 1)
        eq_(self.ub.ubcalc.tau, 2.0)
        #Defaults:
        prepareRawInput(['', ''])
        self.hardware.position = [None, None, None, None, 3, 4.]
        self.ub.sigtau()
        eq_(self.ub.ubcalc.sigma, -3.)
        eq_(self.ub.ubcalc.tau, -4.)

    def testSetWithString(self):
        with pytest.raises(TypeError):
            self.ub.setlat('alpha')
        with pytest.raises(TypeError):
            self.ub.setlat('alpha', 1, 'a')

    def test_setnphihkl_at_various_phases(self):
        self.ub.setnphi([1, 0, 1])
        self.ub.setnhkl([1, 0, 1])
        self.ub.newub('test')
        self.ub.setnphi([1, 0, 1])
        self.ub.setnhkl([1, 0, 1]) 
        self.ub.setlat('cube', 1, 1, 1, 90, 90, 90)
        self.ub.setnphi([1, 0, 1])
        self.ub.setnhkl([1, 0, 1])
        self.ub.setu([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
        self.ub.setnphi([1, 0, 1])
        self.ub.setnhkl([1, 0, 1])

    def test_surfnphihkl_at_various_phases(self):
        self.ub.surfnphi([1, 0, 1])
        self.ub.surfnhkl([1, 0, 1])
        self.ub.newub('test')
        self.ub.surfnphi([1, 0, 1])
        self.ub.surfnhkl([1, 0, 1]) 
        self.ub.setlat('cube', 1, 1, 1, 90, 90, 90)
        self.ub.surfnphi([1, 0, 1])
        self.ub.surfnhkl([1, 0, 1])
        self.ub.setu([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
        self.ub.surfnphi([1, 0, 1])
        self.ub.surfnhkl([1, 0, 1])

    def testMiscut(self):
        self.ub.newub('testsetmiscut')
        self.ub.ubcalc._state.reference._set_n_phi_configured(matrix('0; 0; 1'))
        self.ub.setlat('cube', 1, 1, 1, 90, 90, 90)
        beam_axis = self.conv.transform(matrix('0; 1; 0'), True).T.tolist()[0]
        beam_maxis = self.conv.transform(matrix('0; -1; 0'), True).T.tolist()[0]
        self.ub.setmiscut(self.t_hand * 30, beam_axis)
        mneq_(self.ub.ubcalc._state.reference.n_hkl, matrix('-0.5000000; 0.00000; 0.8660254'))
        self.ub.addmiscut(self.t_hand * 15, beam_axis)
        mneq_(self.ub.ubcalc._state.reference.n_hkl, matrix('-0.7071068; 0.00000; 0.7071068'))
        self.ub.addmiscut(self.t_hand * 45, beam_maxis)
        mneq_(self.ub.ubcalc._state.reference.n_hkl, matrix('0.0; 0.0; 1.0'))


class TestUbCommandsVlieg(_UBCommandsBase):
    
    def setup_method(self):
        settings.ubcalc_persister = UbCalculationNonPersister()
        settings.geometry = SixCircleGammaOnArmGeometry()

        settings.ubcalc_strategy = VliegUbCalcStrategy()