This commit is contained in:
2019-03-20 13:52:00 +01:00
parent 3084fe0510
commit 5db0f78aee
910 changed files with 191152 additions and 322 deletions

View File

@@ -0,0 +1,253 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
import random
import unittest
from math import pi
from mock import Mock
from test.tools import mneq_
import pytest
try:
from numpy import matrix
from numpy.linalg import norm
except ImportError:
from numjy import matrix
from numjy.linalg import norm
from diffcalc.hkl.vlieg.calc import VliegHklCalculator, \
_findOmegaAndChiToRotateHchiIntoQalpha, check
from diffcalc.hkl.vlieg.geometry import createVliegMatrices
from diffcalc.util import DiffcalcException
from test.diffcalc import scenarios
TORAD = pi / 180
TODEG = 180 / pi
def createMockUbcalc(UB):
ubcalc = Mock()
ubcalc.tau = 0
ubcalc.sigma = 0
ubcalc.UB = UB
ubcalc.n_phi = matrix([[0], [0], [1]])
return ubcalc
def createMockHardwareMonitor():
hardware = Mock()
hardware.get_position.return_value = (0.0, 0.0, 0.0)
hardware.get_axes_names.return_value = 'madeup', 'alpha', 'gamma'
return hardware
def createMockDiffractometerGeometry():
geometry = Mock()
geometry.parameter_fixed.return_value = False
geometry.supports_mode_group.return_value = True
geometry.fixed_parameters = {}
geometry.name = 'mock'
geometry.gamma_location = 'arm'
return geometry
class TestVliegCoreMathBits(object):
def setup_method(self):
self.many = [-91, -90, -89, -46, -45, -44, -1,
0, 1, 44, 45, 46, 89, 90, 91]
self.many = (self.many +
map(lambda x: x + 180, self.many) +
map(lambda x: x - 180, self.many))
def test_check(self):
check(True, 'Should not throw')
with pytest.raises(Exception):
check(False, 'string')
with pytest.raises(DiffcalcException):
check(False, DiffcalcException('dce'))
def acallable(toPrint=None):
if toPrint is None:
print "Not throwing exception"
else:
print toPrint
check(False, acallable)
check(False, acallable, 'this should be printed')
# TODO: Removed 2017-03-06, deprecated started code failing -- RobW.
def SKIP__findOmegaAndChiToRotateHchiIntoQalpha_WithIntegerValues(self):
for omega in self.many:
for chi in self.many:
print str(omega), ",", str(chi)
self.try__findOmegaAndChiToRotateHchiIntoQalpha(omega, chi)
def SKIP_findOmegaAndChiToRotateHchiIntoQalpha_WithRandomValues(self):
for _ in range(10):
for omega in self.many:
for chi in self.many:
omega = omega + random.uniform(-.001, .001)
chi = chi + random.uniform(-.001, .001)
self.try__findOmegaAndChiToRotateHchiIntoQalpha(omega, chi)
#print str(omega), ",", str(chi)
def test__findOmegaAndChiToRotateHchiIntoQalpha_WithTrickyOnes(self):
tricky_ones = [(-45., -180.), (45., -180.), (135., -180.), (2000, 0.),
(225., 0.), (225., -180.), (-225., 0.), (-225., 0.),
(-225., -180.), (-135., -180.), (89.998894, -44.999218)]
for omega, chi in tricky_ones:
self.try__findOmegaAndChiToRotateHchiIntoQalpha(omega, chi)
def try__findOmegaAndChiToRotateHchiIntoQalpha(self, omega, chi):
h_chi = matrix([[1], [1], [1]])
h_chi = h_chi * (1 / norm(h_chi))
[_, _, _, OMEGA, CHI, _] = createVliegMatrices(
None, None, None, omega * TORAD, chi * TORAD, None)
q_alpha = OMEGA * CHI * h_chi
try:
omega_calc, chi_calc = _findOmegaAndChiToRotateHchiIntoQalpha(
h_chi, q_alpha)
except ValueError, e:
raise ValueError(str(e) + "\n, resulting from test where omega:%f"
" chi%f" % (self.omega, self.chi))
[_, _, _, OMEGA, CHI, _] = createVliegMatrices(
None, None, None, omega_calc, chi_calc, None)
self.assertArraysNearlyEqual(OMEGA * CHI * h_chi, q_alpha, .000001,
"omega: %f chi:%f" % (omega, chi))
def assertArraysNearlyEqual(self, first, second, tolerance,
contextString=''):
"""
Fail if the norm of the difference between two arrays is greater than
the given tolerance.
"""
diff = first - second
if norm(diff) >= tolerance:
raise self.failureException(
'\n%r !=\n %r\ncontext: %s' %
(first.tolist(), second.tolist(), contextString))
class BaseTestHklCalculator():
def setSessionAndCalculation(self):
raise Exception("Abstract")
def setup_method(self):
self.ac = VliegHklCalculator(None, createMockDiffractometerGeometry(),
createMockHardwareMonitor())
self.ac.raiseExceptionsIfAnglesDoNotMapBackToHkl = True
self.setSessionAndCalculation()
def testAnglesToHkl(self):
mockUbcalc = createMockUbcalc(
matrix(self.sess.umatrix) * matrix(self.sess.bmatrix))
self.ac = VliegHklCalculator(mockUbcalc,
createMockDiffractometerGeometry(),
createMockHardwareMonitor())
self.ac.raiseExceptionsIfAnglesDoNotMapBackToHkl = True
# Check the two given reflections
(hklactual1, params) = self.ac.anglesToHkl(self.sess.ref1.pos,
self.sess.ref1.wavelength)
del params
(hklactual2, params) = self.ac.anglesToHkl(self.sess.ref2.pos,
self.sess.ref2.wavelength)
mneq_(matrix([hklactual1]), matrix([self.sess.ref1calchkl]), 3)
mneq_(matrix([hklactual2]), matrix([self.sess.ref2calchkl]), 3)
# ... znd in each calculation through the hkl/posiiont pairs
if self.calc:
for hkl, pos, param in zip(self.calc.hklList,
self.calc.posList,
self.calc.paramList):
(hkl_actual, params) = self.ac.anglesToHkl(pos,
self.calc.wavelength)
note = ("wrong hkl calcualted for scenario.name=%s, "
"calculation.tag=%s\n expected hkl=(%f,%f,%f)\n"
"calculated hkl=(%f,%f,%f)" %
(self.sess.name, self.calc.tag, hkl[0], hkl[1], hkl[2],
hkl_actual[0], hkl_actual[1], hkl_actual[2]))
mneq_(matrix([hkl_actual]), matrix([hkl]), 3, note=note)
print "***anglesToHkl***"
print "*** ", str(hkl), " ***"
print params
print param
def testHklToAngles(self):
if self.calc:
# Configure the angle calculator for this session scenario
UB = matrix(self.sess.umatrix) * matrix(self.sess.bmatrix)
mockUbcalc = createMockUbcalc(UB)
hw = createMockHardwareMonitor()
ac = VliegHklCalculator(mockUbcalc,
createMockDiffractometerGeometry(), hw)
ac.raiseExceptionsIfAnglesDoNotMapBackToHkl = True
## configure the angle calculator for this calculation
ac.mode_selector.setModeByName(self.calc.modeToTest)
# Set fixed parameters
if self.calc.modeToTest in ('4cBeq', '4cFixedw'):
#ac.setParameter('alpha', self.calc.alpha )
ac.parameter_manager.setTrackParameter('alpha', True)
hw.get_position.return_value = 888, self.calc.alpha, 999
ac.parameter_manager.set_constraint('gamma', self.calc.gamma)
# Test each hkl/position pair
for idx in range(len(self.calc.hklList)):
hkl = self.calc.hklList[idx]
expectedpos = self.calc.posList[idx]
(pos, params) = ac.hklToAngles(hkl[0], hkl[1], hkl[2],
self.calc.wavelength)
note = ("wrong positions calculated for TestScenario=%s, "
"AngleTestScenario=%s, hkl=(%f,%f,%f):\n"
" expected pos=%s;\n"
" returned pos=%s " %
(self.sess.name, self.calc.tag, hkl[0], hkl[1], hkl[2],
str(expectedpos), str(pos)))
assert pos.nearlyEquals(expectedpos, 0.01), note
print "*** hklToAngles ***"
print "*** ", str(hkl), " ***"
print params
try:
print self.calc.paramList[idx]
except IndexError: # Not always specified
pass
class TestVliegHklCalculatorSess1NoCalc(BaseTestHklCalculator):
def setSessionAndCalculation(self):
self.sess = scenarios.session1
self.calc = None
class TestVliegHklCalculatorSess2Calc0(BaseTestHklCalculator):
def setSessionAndCalculation(self):
self.sess = scenarios.session2
self.calc = scenarios.session2.calculations[0]
class TestVliegHklCalculatorSess3Calc0(
BaseTestHklCalculator):
def setSessionAndCalculation(self):
self.sess = scenarios.session3
self.calc = scenarios.session3.calculations[0]

View File

@@ -0,0 +1,92 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
import unittest
from diffcalc.hkl.vlieg.constraints import ModeSelector, VliegParameterManager
from diffcalc.util import DiffcalcException
from test.diffcalc.hkl.vlieg.test_calc import \
createMockHardwareMonitor, createMockDiffractometerGeometry
import pytest
class TestModeSelector(object):
def setup_method(self):
self.ms = ModeSelector(createMockDiffractometerGeometry(),
parameterManager=None)
self.pm = VliegParameterManager(createMockDiffractometerGeometry(),
None, self.ms)
self.ms.setParameterManager(self.pm)
def testSetModeByIndex(self):
self.ms.setModeByIndex(0)
assert self.ms.getMode().name == '4cFixedw'
self.ms.setModeByIndex(1)
assert self.ms.getMode().name == '4cBeq'
def testGetMode(self):
# tested implicetely by testSetmode
pass
def testShowAvailableModes(self):
print self.ms.reportAvailableModes()
class TestParameterManager(object):
def setup_method(self):
self.hw = createMockHardwareMonitor()
self.ms = ModeSelector(createMockDiffractometerGeometry())
self.pm = VliegParameterManager(createMockDiffractometerGeometry(),
self.hw, self.ms)
def testDefaultParameterValues(self):
assert self.pm.get_constraint('alpha') == 0
assert self.pm.get_constraint('gamma') == 0
with pytest.raises(DiffcalcException):
self.pm.get_constraint('not-a-parameter-name')
def testSetParameter(self):
self.pm.set_constraint('alpha', 10.1)
assert self.pm.get_constraint('alpha') == 10.1
def testSetTrackParameter_isParameterChecked(self):
assert not self.pm.isParameterTracked('alpha')
self.pm.set_constraint('alpha', 9)
self.pm.setTrackParameter('alpha', True)
assert self.pm.isParameterTracked('alpha') == True
with pytest.raises(DiffcalcException):
self.pm.set_constraint('alpha', 10)
self.hw.get_position.return_value = 888, 11, 999
assert self.pm.get_constraint('alpha') == 11
print self.pm.reportAllParameters()
print "**"
print self.ms.reportCurrentMode()
print self.pm.reportParametersUsedInCurrentMode()
self.pm.setTrackParameter('alpha', False)
assert not self.pm.isParameterTracked('alpha')
assert self.pm.get_constraint('alpha') == 11
self.hw.get_position.return_value = 888, 12, 999
assert self.pm.get_constraint('alpha') == 11
self.pm.set_constraint('alpha', 13)
assert self.pm.get_constraint('alpha') == 13

View File

@@ -0,0 +1,248 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
import random
import unittest
from math import pi
try:
from numpy import matrix
from numpy.linalg import norm
except ImportError:
from numjy import matrix
from numjy.linalg import norm
from test.tools import mneq_
from diffcalc.hkl.vlieg.geometry import SixCircleGammaOnArmGeometry, \
gammaOnArmToBase, gammaOnBaseToArm, SixCircleGeometry, Fivec, Fourc
from diffcalc.hkl.vlieg.geometry import createVliegMatrices
from diffcalc.hkl.vlieg.geometry import VliegPosition
from diffcalc.util import nearlyEqual, radiansEquivilant as radeq
random.seed() # uses time
TORAD = pi / 180
TODEG = 180 / pi
class TestSixCirclePlugin(object):
def setup_method(self):
self.geometry = SixCircleGeometry()
def testGetName(self):
assert self.geometry.name == "sixc"
def testPhysicalAnglesToInternalPosition(self):
pos = [0, 0, 0, 0, 0, 0]
expected = self.geometry.physical_angles_to_internal_position(pos)
assert VliegPosition(*pos) == expected
def testInternalPositionToPhysicalAngles(self):
pos = VliegPosition(0, 0, 0, 0, 0, 0)
result = self.geometry.internal_position_to_physical_angles(pos)
assert norm(matrix([pos.totuple()]) - matrix([result])) < 0.001
def testGammaOn(self):
assert self.geometry.gamma_location == 'base'
def testSupportsModeGroup(self):
assert self.geometry.supports_mode_group('fourc')
assert not self.geometry.supports_mode_group('made up mode')
def testGetFixedParameters(self):
self.geometry.fixed_parameters # check for exceptions
def isParamaterUnchangable(self):
assert not self.geometry.isParamaterUnchangable('made up parameter')
class TestSixCircleGammaOnArmGeometry(object):
def setup_method(self):
self.geometry = SixCircleGammaOnArmGeometry()
def testGetName(self):
assert self.geometry.name == "sixc_gamma_on_arm"
def testPhysicalAnglesToInternalPosition(self):
pos = [1, 2, 3, 4, 5, 6]
expected = self.geometry.physical_angles_to_internal_position(pos)
assert VliegPosition(*pos) == expected
def testInternalPositionToPhysicalAngles(self):
pos = VliegPosition(1, 2, 3, 4, 5, 6)
result = self.geometry.internal_position_to_physical_angles(pos)
mneq_(matrix([pos.totuple()]), matrix([result]), 4)
def testSupportsModeGroup(self):
assert self.geometry.supports_mode_group('fourc')
assert not self.geometry.supports_mode_group('made up mode')
def testGetFixedParameters(self):
self.geometry.fixed_parameters # check for exceptions
def isParamaterUnchangable(self):
assert not self.geometry.isParamaterUnchangable('made up parameter')
y_vector = matrix([[0], [1], [0]])
TOLERANCE = 1e-5
def armAnglesToLabVector(alpha, delta, gamma):
[ALPHA, DELTA, GAMMA, _, _, _] = createVliegMatrices(
alpha, delta, gamma, None, None, None)
return ALPHA * DELTA * GAMMA * y_vector
def baseAnglesToLabVector(delta, gamma):
[_, DELTA, GAMMA, _, _, _] = createVliegMatrices(
None, delta, gamma, None, None, None)
return GAMMA * DELTA * y_vector
def checkGammaOnArmToBase(alpha, deltaA, gammaA):
deltaB, gammaB = gammaOnArmToBase(deltaA, gammaA, alpha)
labA = armAnglesToLabVector(alpha, deltaA, gammaA)
labB = baseAnglesToLabVector(deltaB, gammaB)
if not nearlyEqual(labA, labB, TOLERANCE):
strLabA = ("[%f, %f, %f]" %
(labA.get(0, 0), labA.get(1, 0), labA.get(2, 0)))
strLabB = ("[%f, %f, %f]" %
(labB.get(0, 0), labB.get(1, 0), labB.get(2, 0)))
rep = ("alpha=%f, delta=%f, gamma=%f" %
(alpha * TODEG, deltaB * TODEG, gammaB * TODEG))
raise AssertionError('\nArm-->Base ' + rep + '\n' +
"arm (delta, gamma) = (%f,%f) <==>\t labA = %s\n" %
(deltaA * TODEG, gammaA * TODEG, strLabA) +
"base(delta, gamma) = (%f,%f) <==>\t labB = %s\n" %
(deltaB * TODEG, gammaB * TODEG, strLabB))
def checkBaseArmBaseReciprocity(alpha, delta_orig, gamma_orig):
(deltaB, gammaB) = (delta_orig, gamma_orig)
(deltaA, gammaA) = gammaOnBaseToArm(deltaB, gammaB, alpha)
(deltaB, gammaB) = gammaOnArmToBase(deltaA, gammaA, alpha)
if ((not radeq(deltaB, delta_orig, TOLERANCE)) or
(not radeq(gammaB, gamma_orig, TOLERANCE))):
s = "\nBase-Arm-Base reciprocity\n"
s += 'alpha=%f\n' % (alpha * TODEG,)
s += (' (deltaB, gammaB) = (%f, %f)\n' %
(delta_orig * TODEG, gamma_orig * TODEG))
s += (' ->(deltaA, gammaA) = (%f, %f)\n' %
(deltaA * TODEG, gammaA * TODEG))
s += (' ->(deltaB, gammaB) = (%f, %f)\n' %
(deltaB * TODEG, gammaB * TODEG))
raise AssertionError(s)
def checkArmBaseArmReciprocity(alpha, delta_orig, gamma_orig):
(deltaA, gammaA) = (delta_orig, gamma_orig)
(deltaB, gammaB) = gammaOnArmToBase(deltaA, gammaA, alpha)
(deltaA, gammaA) = gammaOnBaseToArm(deltaB, gammaB, alpha)
if ((not radeq(deltaA, delta_orig, TOLERANCE)) or
(not radeq(gammaA, gamma_orig, TOLERANCE))):
s = "\nArm-Base-Arm reciprocity\n"
s += "alpha=%f\n" % (alpha * TODEG,)
s += (" (deltaA, gammaA) = (%f, %f)\n" %
(delta_orig * TODEG, gamma_orig * TODEG))
s += (" ->(deltaB, gammaB) = (%f, %f)\n" %
(deltaB * TODEG, gammaB * TODEG))
s += (" ->(deltaA, gammaA) = (%f, %f)\n" %
(deltaA * TODEG, gammaA * TODEG))
raise AssertionError(s)
def test_generator_for_cases():
for alpha in [-89.9, -45, -1, 0, 1, 45, 89.9]:
for gamma in [-89.9, -46, -45, -44, -1, 0, 1, 44, 45, 46, 89.9]:
for delta in [-179.9, -135, -91, -89.9, -89, -46, -45, -44, -1, 0,
1, 44, 45, 46, 89, 89.9, 91, 135, 179.9]:
yield (checkGammaOnArmToBase, alpha * TORAD, delta * TORAD,
gamma * TORAD)
yield (checkArmBaseArmReciprocity, alpha * TORAD,
delta * TORAD, gamma * TORAD)
class TestFiveCirclePlugin(object):
def setup_method(self):
self.geometry = Fivec()
def testGetName(self):
assert self.geometry.name == "fivec"
def testPhysicalAnglesToInternalPosition(self):
expected = self.geometry.physical_angles_to_internal_position(
(1, 2, 4, 5, 6))
assert VliegPosition(1, 2, 0, 4, 5, 6) == expected
def testInternalPositionToPhysicalAngles(self):
result = self.geometry.internal_position_to_physical_angles(
VliegPosition(1, 2, 0, 4, 5, 6))
assert (norm(matrix([[1, 2, 4, 5, 6]]) - (matrix([list(result)])))
< 0.001)
def testSupportsModeGroup(self):
assert self.geometry.supports_mode_group('fourc')
assert not self.geometry.supports_mode_group('fivecFixedAlpha')
assert self.geometry.supports_mode_group('fivecFixedGamma')
def testGetFixedParameters(self):
self.geometry.fixed_parameters # check for exceptions
def testisParamaterFixed(self):
assert not self.geometry.parameter_fixed('made up parameter')
assert self.geometry.parameter_fixed('gamma')
class TestFourCirclePlugin(object):
def setup_method(self):
self.geometry = Fourc()
def testGetName(self):
assert self.geometry.name == "fourc"
def testPhysicalAnglesToInternalPosition(self):
expected = self.geometry.physical_angles_to_internal_position((2, 4, 5, 6))
assert VliegPosition(0, 2, 0, 4, 5, 6) == expected
def testInternalPositionToPhysicalAngles(self):
result = self.geometry.internal_position_to_physical_angles(
VliegPosition(0, 2, 0, 4, 5, 6))
assert (norm(matrix([[2, 4, 5, 6]]) - matrix([list(result)]))
< 0.001)
def testSupportsModeGroup(self):
assert self.geometry.supports_mode_group('fourc')
assert not self.geometry.supports_mode_group('fivecFixedAlpha')
assert not self.geometry.supports_mode_group('fivecFixedGamma')
def testGetFixedParameters(self):
self.geometry.fixed_parameters # check for exceptions
def testisParamaterFixed(self):
assert not self.geometry.parameter_fixed('made up parameter')
assert self.geometry.parameter_fixed('gamma')
assert self.geometry.parameter_fixed('alpha')

View File

@@ -0,0 +1,84 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
import unittest
from mock import Mock
import diffcalc.util # @UnusedImport to overide raw_input
from diffcalc.hkl.vlieg.geometry import SixCircleGammaOnArmGeometry
from diffcalc.hardware import DummyHardwareAdapter
from diffcalc.util import MockRawInput
from diffcalc.hkl.vlieg.calc import VliegHklCalculator
from diffcalc.ub.calc import UBCalculation
from diffcalc.ub.persistence import UbCalculationNonPersister
import pytest
try:
from gdascripts.pd.dummy_pds import DummyPD # @UnusedImport
except ImportError:
from diffcalc.gdasupport.minigda.scannable import DummyPD
def prepareRawInput(listOfStrings):
diffcalc.util.raw_input = MockRawInput(listOfStrings)
prepareRawInput([])
class TestHklCommands(object):
def setup_method(self):
self.geometry = SixCircleGammaOnArmGeometry()
dummy = 'alpha', 'delta', 'gamma', 'omega', 'chi', 'phi'
self.hardware = DummyHardwareAdapter(dummy)
self.mock_ubcalc = Mock(spec=UBCalculation)
self.hklcalc = VliegHklCalculator(self.mock_ubcalc, self.geometry,
self.hardware, True)
from diffcalc import settings
settings.hardware = self.hardware
settings.geometry = self.geometry
settings.ubcalc_persister = UbCalculationNonPersister()
from diffcalc.hkl.vlieg import hkl
reload(hkl)
hkl.hklcalc = self.hklcalc
self.hkl = hkl
prepareRawInput([])
def testHklmode(self):
with pytest.raises(TypeError):
self.hkl.hklmode(1, 2)
with pytest.raises(ValueError):
self.hkl.hklmode('unwanted_string')
print self.hkl.hklmode()
print self.hkl.hklmode(1)
def testSetWithString(self):
self.hkl.setpar()
self.hkl.setpar('alpha')
self.hkl.setpar('alpha', 1)
self.hkl.setpar('alpha', 1.1)
pm = self.hkl.hklcalc.parameter_manager
assert pm.get_constraint('alpha') == 1.1
def testSetWithScannable(self):
alpha = DummyPD('alpha')
self.hkl.setpar(alpha, 1.1)
pm = self.hkl.hklcalc.parameter_manager
assert pm.get_constraint('alpha') == 1.1

View File

@@ -0,0 +1,463 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
from nose.tools import eq_
import unittest
from mock import Mock
from diffcalc.hkl.vlieg.geometry import SixCircleGammaOnArmGeometry
from diffcalc.hardware import DummyHardwareAdapter
from diffcalc.hkl.vlieg.geometry import VliegPosition as P, \
VliegPosition as Pos
from diffcalc.hkl.vlieg.transform import TransformA, TransformB, TransformC, \
transformsFromSector, TransformCommands, \
VliegTransformSelector, VliegPositionTransformer
import diffcalc.util # @UnusedImport
import pytest
class TestVliegPositionTransformer(object):
def setup_method(self):
names = 'a', 'd', 'g', 'o', 'c', 'phi'
self.hardware = DummyHardwareAdapter(names)
self.geometry = SixCircleGammaOnArmGeometry()
self.transform_selector = VliegTransformSelector()
self.transformer = VliegPositionTransformer(
self.geometry, self.hardware, self.transform_selector)
self.transform_commands = TransformCommands(self.transform_selector)
diffcalc.util.RAISE_EXCEPTIONS_FOR_ALL_ERRORS = True
def map(self, pos): # @ReservedAssignment
pos = self.transformer.transform(pos)
angle_tuple = self.geometry.internal_position_to_physical_angles(pos)
angle_tuple = self.hardware.cut_angles(angle_tuple)
return angle_tuple
def testMapDefaultSector(self):
eq_(self.map(Pos(1, 2, 3, 4, 5, 6)),
(1, 2, 3, 4, 5, 6))
eq_(self.map(Pos(-180, -179, 0, 179, 180, 359)),
(-180, -179, 0, 179, 180, 359))
eq_(self.map(Pos(0, 0, 0, 0, 0, 0)),
(0, 0, 0, 0, 0, 0))
eq_(self.map(Pos(-270, 270, 0, 0, 0, -90)),
(90, -90, 0, 0, 0, 270))
def testMapSector1(self):
self.transform_commands._sectorSelector.setSector(1)
eq_(self.map(Pos(1, 2, 3, 4, 5, 6)),
(1, 2, 3, 4 - 180, -5, (6 - 180) + 360))
eq_(self.map(Pos(-180, -179, 0, 179, 180, 359)),
(-180, -179, 0, 179 - 180, -180, 359 - 180))
eq_(self.map(Pos(0, 0, 0, 0, 0, 0)),
(0, 0, 0, 0 - 180, 0, (0 - 180) + 360))
eq_(self.map(Pos(-270, 270, 0, 0, 0, -90)),
(90, -90, 0, 0 - 180, 0, 270 - 180))
def testMapAutoSector(self):
self.transform_commands._sectorSelector.addAutoTransorm(1)
self.hardware.set_lower_limit('c', 0)
eq_(self.map(Pos(1, 2, 3, 4, -5, 6)),
(1, 2, 3, 4 - 180, 5, (6 - 180) + 360))
eq_(self.map(Pos(-180, -179, 0, 179, -180, 359)),
(-180, -179, 0, 179 - 180, 180, 359 - 180))
eq_(self.map(Pos(0, 0, 0, 0, -5, 0)),
(0, 0, 0, 0 - 180, 5, (0 - 180) + 360))
eq_(self.map(Pos(-270, 270, 0, 0, -5, -90)),
(90, -90, 0, 0 - 180, 5, 270 - 180))
def testTransform(self):
# mapper
self.transform_commands.transform() # should print its state
with pytest.raises(TypeError):
self.transform_commands.transform(1)
with pytest.raises(TypeError):
self.transform_commands.transform('a', 1)
def testTransformsOnOff(self):
# transforma [on/off/auto/manual]
ss = self.transform_commands._sectorSelector
self.transform_commands.transforma() # should print mapper state
eq_(ss.transforms, [], "test assumes transforms are off to start")
self.transform_commands.transforma('on')
eq_(ss.transforms, ['a'])
self.transform_commands.transformb('on')
eq_(ss.transforms, ['a', 'b'])
self.transform_commands.transformc('off')
eq_(ss.transforms, ['a', 'b'])
self.transform_commands.transformb('off')
eq_(ss.transforms, ['a'])
def testTransformsAuto(self):
ss = self.transform_commands._sectorSelector
eq_(ss.autotransforms, [], "test assumes transforms are off to start")
self.transform_commands.transforma('auto')
eq_(ss.autotransforms, ['a'])
self.transform_commands.transformb('auto')
eq_(ss.autotransforms, ['a', 'b'])
self.transform_commands.transformc('manual')
eq_(ss.autotransforms, ['a', 'b'])
self.transform_commands.transformb('manual')
eq_(ss.autotransforms, ['a'])
def testTransformsBadInput(self):
transforma = self.transform_commands.transforma
with pytest.raises(TypeError):
transforma(1)
with pytest.raises(TypeError):
transforma('not_valid')
with pytest.raises(TypeError):
transforma('auto', 1)
def testSector(self):
#sector [0-7]
ss = self.transform_commands._sectorSelector
self.transform_commands.sector() # should print mapper state
eq_(ss.sector, 0, "test assumes sector is 0 to start")
self.transform_commands.sector(1)
eq_(ss.sector, 1)
with pytest.raises(TypeError):
self.transform_commands.sector(1, 2)
with pytest.raises(TypeError):
self.transform_commands.sector('a')
def testAutosectors(self):
#autosector [0-7]
ss = self.transform_selector
self.transform_commands.autosector() # should print mapper state
eq_(ss.autosectors, [], "test assumes no auto sectors to start")
self.transform_commands.autosector(1)
eq_(ss.autosectors, [1])
self.transform_commands.autosector(1, 2)
eq_(ss.autosectors, [1, 2])
self.transform_commands.autosector(1)
eq_(ss.autosectors, [1])
self.transform_commands.autosector(3)
eq_(ss.autosectors, [3])
with pytest.raises(TypeError):
self.transform_commands.autosector(1, 'a')
with pytest.raises(TypeError):
self.transform_commands.autosector('a')
class MockLimitChecker(object):
def __init__(self):
self.okay = True
def isPoswithiLimits(self, pos):
return self.okay
def isDeltaNegative(self, pos):
return pos.delta <= 0
class TestVliegTransformSelector(object):
def setup_method(self):
self.limitChecker = MockLimitChecker()
self.ss = VliegTransformSelector()
self.ss.limitCheckerFunction = self.limitChecker.isPoswithiLimits
def test__init__(self):
assert (self.ss.sector, 0)
def testCutPosition(self):
d = .1
tocut = P(-180., 180., 180. - d, 180. + d, -180. + d, -180. - d)
expected = P(-180., 180., 180. - d, -180. + d, -180. + d, 180. - d)
assert (self.ss.cutPosition(tocut) == expected)
def testTransformNWithoutCut(self):
pos = P(1, 2, 3, 4, 5, 6)
assert (self.ss.transformNWithoutCut(0, pos) == pos)
def testTransformPosition(self):
pos = P(0 - 360, .1 + 360, .2 - 360, .3 + 360, .4, 5)
res = self.ss.transformPosition(pos)
des = P(0, .1, .2, .3, .4, 5)
assert (res == des, '%s!=\n%s' % (res, des))
def testSetSector(self):
self.ss.setSector(4)
assert (self.ss.sector, 4)
assert (self.ss.transforms, ['b', 'c'])
def testSetTransforms(self):
self.ss.setTransforms(('c', 'b'))
assert (self.ss.sector, 4)
assert (self.ss.transforms, ['b', 'c'])
def testAddAutoTransormWithBadInput(self):
assert (self.ss.autosectors, [])
assert (self.ss.autotransforms, [])
with pytest.raises(ValueError):
self.ss.addAutoTransorm('not transform')
with pytest.raises(ValueError):
self.ss.addAutoTransorm(9999)
with pytest.raises(ValueError):
self.ss.addAutoTransorm([])
def testAddAutoTransormWithTransforms(self):
self.ss.autosectors = [1, 2, 3, 4, 5]
self.ss.addAutoTransorm('a')
print "Should now print a warning..."
self.ss.addAutoTransorm('a') # twice
self.ss.addAutoTransorm('b')
assert (self.ss.autosectors, [])
assert (self.ss.autotransforms, ['a', 'b'])
def testAddAutoTransormWithSectors(self):
self.ss.autotransforms = ['a', 'c']
self.ss.addAutoTransorm(2)
print "Should now print a warning..."
self.ss.addAutoTransorm(2) # twice
self.ss.addAutoTransorm(3)
assert (self.ss.autosectors, [2, 3])
assert (self.ss.autotransforms, [])
def testis_position_within_limits(self):
assert (self.ss.is_position_within_limits(None), True)
self.limitChecker.okay = False
assert (self.ss.is_position_within_limits(None), False)
def test__repr__(self):
self.ss.setSector(0)
print "************************"
print self.ss
print "************************"
self.ss.setTransforms('a')
print self.ss
print "************************"
self.ss.setTransforms(('a', 'b', 'c'))
print self.ss
print "************************"
class TestSectorSelectorAutoCode(object):
def setup_method(self):
self.limitChecker = MockLimitChecker()
self.ss = VliegTransformSelector()
self.ss.limitCheckerFunction = self.limitChecker.isDeltaNegative
self.pos = P(0, .1, .2, .3, .4, 5)
self.pos_in2 = self.ss.cutPosition(
self.ss.transformNWithoutCut(2, self.pos))
self.pos_in3 = self.ss.cutPosition(
self.ss.transformNWithoutCut(3, self.pos))
def testAddautoTransformWithSectors(self):
self.ss.addAutoTransorm(2)
self.ss.addAutoTransorm(3)
assert (self.ss.autosectors, [2, 3])
assert (self.ss.autotransforms, [])
self.ss.removeAutoTransform(3)
assert (self.ss.autosectors, [2])
def testAddautoTransformTransforms(self):
self.ss.addAutoTransorm('a')
self.ss.addAutoTransorm('b')
assert (self.ss.autosectors, [])
assert (self.ss.autotransforms, ['a', 'b'])
def testRemoveAutoTransformWithSectors(self):
self.ss.addAutoTransorm(2)
self.ss.addAutoTransorm(3)
self.ss.removeAutoTransform(3)
assert (self.ss.autosectors, [2])
self.ss.removeAutoTransform(2)
assert (self.ss.autosectors, [])
def testRemoveAutoTransformTransforms(self):
self.ss.addAutoTransorm('a')
self.ss.addAutoTransorm('b')
self.ss.removeAutoTransform('b')
assert (self.ss.autotransforms, ['a'])
self.ss.removeAutoTransform('a')
assert (self.ss.autotransforms, [])
def testTransformPosition(self):
# Check that with no transforms set to autoapply, the limit
# checker function is ignored
ss = VliegTransformSelector()
ss.limitCheckerFunction = self.limitChecker.isPoswithiLimits
self.limitChecker.okay = False
ss.transformPosition(P(0, .1, .2, .3, .4, 5))
def testMockLimitChecker(self):
assert not self.limitChecker.isDeltaNegative(P(0, .1, .2, .3, .4, 5))
assert self.limitChecker.isDeltaNegative(P(0, -.1, .2, .3, .4, 5))
def testAutoTransformPositionWithSectors(self):
self.ss.addAutoTransorm(2)
print "Should print 'INFO: Autosector changed sector from 0 to 2':"
result = self.ss.autoTransformPositionBySector(self.pos)
assert (result == self.pos_in2)
assert (self.ss.sector, 2)
def testAutoTransformPositionWithSectorChoice(self):
self.ss.addAutoTransorm(2)
self.ss.addAutoTransorm(3)
print "Should print 'WARNING: Autosector found multiple sectors...':"
print "Should print 'INFO: Autosector changed sector from 0 to 2':"
result = self.ss.autoTransformPositionBySector(self.pos)
assert (result == self.pos_in2)
assert (self.ss.sector, 2)
def testAutoTransformPositionWithSectorsFails(self):
self.ss.addAutoTransorm(0)
self.ss.addAutoTransorm(1)
self.ss.addAutoTransorm(4)
self.ss.addAutoTransorm(5)
print "Should print 'INFO: Autosector changed sector from 0 to 2':"
with pytest.raises(Exception):
self.ss.autoTransformPositionBySector(self.pos)
#self.ss.autoTransformPositionBySector(self.pos)
assert (self.ss.sector, 0) # unchanged
def testCreateListOfPossibleTransforms(self):
self.ss.addAutoTransorm('a')
assert (self.ss.createListOfPossibleTransforms(),
[(), ['a', ]])
self.ss.addAutoTransorm('b')
assert (self.ss.createListOfPossibleTransforms(),
[(), ['b', ], ['a', ], ['a', 'b']])
self.ss.transforms = ['a', 'c']
def testAutoTransformPositionWithTransforms(self):
self.ss.addAutoTransorm('a')
print "Should print 'INFO: ':"
result = self.ss.autoTransformPositionByTransforms(self.pos)
assert (result == self.pos_in2)
assert (self.ss.sector, 2)
def testAutoTransformPositionWithTansformsChoice(self):
self.ss.addAutoTransorm('a')
self.ss.addAutoTransorm('c')
print "Should print 'WARNING:':"
print "Should print 'INFO: ':"
result = self.ss.autoTransformPositionByTransforms(self.pos)
assert (result == self.pos_in2)
assert (self.ss.sector, 2)
def testTransformPositionWithAutoTransforms(self):
self.ss.addAutoTransorm('a')
assert (self.ss.transformPosition(self.pos) == self.pos_in2)
assert (self.ss.sector, 2)
print "Should not print 'INFO...'"
assert (self.ss.transformPosition(self.pos) == self.pos_in2)
assert (self.ss.sector, 2)
def testTransformPositionWithAutoTransforms2(self):
self.ss.addAutoTransorm(2)
assert (self.ss.transformPosition(self.pos) == self.pos_in2)
assert (self.ss.sector, 2)
print "Should not print 'INFO...'"
assert (self.ss.transformPosition(self.pos) == self.pos_in2)
assert (self.ss.sector, 2)
def test__repr__(self):
self.ss.setSector(0)
print "************************"
print self.ss
print "************************"
self.ss.setTransforms('a')
print self.ss
print "************************"
self.ss.setTransforms(('a', 'b', 'c'))
print self.ss
print "************************"
self.ss.addAutoTransorm(1)
self.ss.addAutoTransorm(2)
self.ss.addAutoTransorm(3)
print self.ss
print "************************"
self.ss.addAutoTransorm('a')
self.ss.addAutoTransorm('c')
print self.ss
print "************************"
class TestTransforms(object):
def setup_method(self):
self.limitCheckerFunction = Mock()
self.ss = VliegTransformSelector()
self.ss.limitCheckerFunction = self.limitCheckerFunction
def applyTransforms(self, transforms, pos):
result = pos.clone()
for transform in transforms:
if transform == 'a':
result = TransformA().transform(result)
if transform == 'b':
result = TransformB().transform(result)
if transform == 'c':
result = TransformC().transform(result)
return self.ss.cutPosition(result)
def _testTransformN(self, n):
transforms = transformsFromSector[n]
pos = P(1, 2, 3, 4, 5, 6)
self.ss.setSector(n)
fromss = self.ss.transformPosition(pos)
fromhere = self.applyTransforms(transforms, pos)
assert (fromss == fromhere,
("sector: %i\ntransforms:%s\n%s !=\n%s" %
(n, transforms, fromss, fromhere)))
def testTransform0(self):
self._testTransformN(0)
def testTransform1(self):
self._testTransformN(1)
def testTransform2(self):
self._testTransformN(2)
def testTransform3(self):
self._testTransformN(3)
def testTransform4(self):
self._testTransformN(5)
def testTransform5(self):
self._testTransformN(5)
def testTransform6(self):
self._testTransformN(6)
def testTransform7(self):
self._testTransformN(7)

View File

@@ -0,0 +1,323 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
# TODO: class largely copied from test_calc
from math import pi
from mock import Mock
from nose.tools import raises
try:
from numpy import matrix
except ImportError:
from numjy import matrix
from diffcalc.hkl.willmott.calc import \
WillmottHorizontalUbCalcStrategy, WillmottHorizontalCalculator, \
WillmottHorizontalPosition as Pos, WillmottHorizontalGeometry
from test.tools import assert_array_almost_equal, \
assert_second_dict_almost_in_first, matrixeq_
from diffcalc.ub.calc import UBCalculation
from diffcalc.ub.crystal import CrystalUnderTest
from diffcalc.ub.persistence import UbCalculationNonPersister
from diffcalc.util import DiffcalcException
from test.diffcalc.test_hardware import SimpleHardwareAdapter
from test.diffcalc.hkl.vlieg.test_calc import createMockUbcalc, \
createMockDiffractometerGeometry
import diffcalc.hkl.willmott.calc # @UnusedImport
TORAD = pi / 180
TODEG = 180 / pi
class _BaseTest():
def setup_method(self):
self.mock_ubcalc = createMockUbcalc(None)
self.mock_geometry = createMockDiffractometerGeometry()
self.mock_hardware = SimpleHardwareAdapter(
['delta', 'gamma', 'omegah', 'phi'])
self.constraints = Mock()
self.calc = WillmottHorizontalCalculator(self.mock_ubcalc,
self.mock_geometry, self.mock_hardware, self.constraints)
self.places = 12
def _check_hkl_to_angles(self, testname, zrot, yrot, hkl, pos_expected,
wavelength, virtual_expected={}):
print ('_check_hkl_to_angles(%s, %.1f, %.1f, %s, %s, %.2f, %s)'
% (testname, zrot, yrot, hkl, pos_expected, wavelength,
virtual_expected))
self.zrot, self.yrot = zrot, yrot
self._configure_ub()
pos, virtual = self.calc.hklToAngles(hkl[0], hkl[1], hkl[2],
wavelength)
assert_array_almost_equal(pos.totuple(), pos_expected.totuple(),
self.places)
assert_second_dict_almost_in_first(virtual, virtual_expected)
def _check_angles_to_hkl(self, testname, zrot, yrot, hkl_expected, pos,
wavelength, virtual_expected={}):
print ('_check_angles_to_hkl(%s, %.1f, %.1f, %s, %s, %.2f, %s)' %
(testname, zrot, yrot, hkl_expected, pos, wavelength,
virtual_expected))
self.zrot, self.yrot = zrot, yrot
self._configure_ub()
hkl, virtual = self.calc.anglesToHkl(pos, wavelength)
assert_array_almost_equal(hkl, hkl_expected, self.places)
assert_second_dict_almost_in_first(virtual, virtual_expected)
@raises(DiffcalcException)
def _check_hkl_to_angles_fails(self, *args):
self._check_hkl_to_angles(*args)
# Primary and secondary reflections found with the help of DDIF on Diamond's
# i07 on Jan 27 2010
Si_5_5_12_WAVELENGTH = 0.6358
Si_5_5_12_HKL0 = 2, 19, 32
Si_5_5_12_REF0 = Pos(delta=21.975, gamma=4.419, omegah=2, phi=326.2)
Si_5_5_12_HKL1 = 0, 7, 22
Si_5_5_12_REF1 = Pos(delta=11.292, gamma=2.844, omegah=2, phi=124.1)
# This is U matrix displayed by DDIF
U_FROM_DDIF = matrix([[0.233140, 0.510833, 0.827463],
[-0.65596, -0.545557, 0.521617],
[0.717888, -0.664392, 0.207894]])
# This is the version that Diffcalc comes up with ( see following test)
Si_5_5_12_U_DIFFCALC = matrix([[-0.7178876, 0.6643924, -0.2078944],
[-0.6559596, -0.5455572, 0.5216170],
[0.2331402, 0.5108327, 0.8274634]])
class TestUBCalculationWithWillmotStrategy_Si_5_5_12():
def setup_method(self):
hardware = Mock()
hardware.get_axes_names.return_value = ('d', 'g', 'oh', 'p')
self.ubcalc = UBCalculation(hardware, WillmottHorizontalGeometry(),
UbCalculationNonPersister(),
WillmottHorizontalUbCalcStrategy())
def testAgainstResultsFromJan_27_2010(self):
self.ubcalc.start_new('test')
self.ubcalc.set_lattice('Si_5_5_12', 7.68, 53.48, 75.63, 90, 90, 90)
self.ubcalc.add_reflection(
Si_5_5_12_HKL0[0], Si_5_5_12_HKL0[1], Si_5_5_12_HKL0[2],
Si_5_5_12_REF0, 12.39842 / Si_5_5_12_WAVELENGTH, 'ref0', None)
self.ubcalc.add_reflection(
Si_5_5_12_HKL1[0], Si_5_5_12_HKL1[1], Si_5_5_12_HKL1[2],
Si_5_5_12_REF1, 12.39842 / Si_5_5_12_WAVELENGTH, 'ref1', None)
self.ubcalc.calculate_UB()
print "U: ", self.ubcalc.U
print "UB: ", self.ubcalc.UB
matrixeq_(self.ubcalc.U, Si_5_5_12_U_DIFFCALC)
class TestSurfaceNormalVertical_Si_5_5_12_PosGamma(_BaseTest):
def setup_method(self):
_BaseTest.setup_method(self)
self.constraints.reference = {'betain': 2}
self.wavelength = 0.6358
B = CrystalUnderTest('xtal', 7.68, 53.48,
75.63, 90, 90, 90).B
self.UB = Si_5_5_12_U_DIFFCALC * B
diffcalc.hkl.willmott.calc.CHOOSE_POSITIVE_GAMMA = True
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
self._check_angles_to_hkl('', 999, 999, hkl, pos, self.wavelength,
virtual_expected)
if fails:
self._check_hkl_to_angles_fails('', 999, 999, hkl, pos,
self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles('', 999, 999, hkl, pos, self.wavelength,
virtual_expected)
def testHkl_2_19_32_found_orientation_setting(self):
'''Check that the or0 reflection maps back to the assumed hkl'''
self.places = 2
self._check_angles_to_hkl('', 999, 999, Si_5_5_12_HKL0,
Si_5_5_12_REF0,
self.wavelength, {'betain': 2})
def testHkl_0_7_22_found_orientation_setting(self):
'''Check that the or1 reflection maps back to the assumed hkl'''
self.places = 0
self._check_angles_to_hkl('', 999, 999, Si_5_5_12_HKL1,
Si_5_5_12_REF1,
self.wavelength, {'betain': 2})
def testHkl_2_19_32_calculated_from_DDIF(self):
self.places = 3
self._check((2, 19, 32),
Pos(delta=21.974, gamma=4.419, omegah=2, phi=-33.803),
{'betain': 2})
def testHkl_0_7_22_calculated_from_DDIF(self):
self.places = 3
self._check((0, 7, 22),
Pos(delta=11.242, gamma=3.038, omegah=2, phi=123.064),
{'betain': 2})
def testHkl_2_m5_12_calculated_from_DDIF(self):
self.places = 3
self._check((2, -5, 12),
Pos(delta=5.224, gamma=10.415, omegah=2, phi=-1.972),
{'betain': 2})
# conlcusion:
# given or1 from testHkl_2_19_32_found_orientation_setting and,
# or1 from testHkl_0_7_22_found_orientation_setting
# we can calculate a U matrix which agrees with that from diff except for
# signs and row order
# We can also calculate values for 2_19_32 and 0_7_22 that match those
# calculated by DDIF to the number of recorded decimal places (3)
class SkipTestSurfaceNormalVertical_Si_5_5_12_NegGamma(
TestSurfaceNormalVertical_Si_5_5_12_PosGamma):
"""When choosing -ve gamma delta ends up being -ve too"""
def setup_method(self):
_BaseTest.setup_method(self)
self.constraints.reference = {'betain': 2 * TORAD}
self.wavelength = 0.6358
B = CrystalUnderTest('xtal', 7.68, 53.48,
75.63, 90, 90, 90).B
self.UB = Si_5_5_12_U_DIFFCALC * B
diffcalc.hkl.willmott.calc.CHOOSE_POSITIVE_GAMMA = False
##################################################################
# Primary and secondary reflections found with the help of DDIF on Diamond's
# i07 on Jan 28/29 2010
Pt531_HKL0 = -1.000, 1.000, 6.0000
Pt531_REF0 = Pos(delta=9.465, gamma=16.301, omegah=2,
phi=307.94 - 360)
Pt531_REF0_DIFFCALC = Pos(
9.397102509657, 16.181230279320, 2.000000000000, -52.139290474913)
Pt531_HKL1 = -2.000, -1.000, 7.0000
Pt531_REF1 = Pos(delta=11.094, gamma=11.945, omegah=2, phi=238.991 - 360)
Pt531_REF1_DIFFCALC = Pos(
11.012695836306, 11.863612760237, 2.000000000000, -121.215597507237)
Pt531_HKL2 = 1, 1, 9
Pt531_REF2 = Pos(delta=14.272, gamma=7.806, omegah=2,
phi=22.9)
Pt531_REF2_DIFFCALC = Pos(
14.188161709766, 7.758593908726, 2.000000000000, 23.020313153847)
Pt531_WAVELENGTH = 0.6358
# This is U matrix displayed by DDIF
U_FROM_DDIF = matrix([[-0.00312594, -0.00063417, 0.99999491],
[0.99999229, -0.00237817, 0.00312443],
[0.00237618, 0.99999697, 0.00064159]])
# This is the version that Diffcalc comes up with ( see following test)
Pt531_U_DIFFCALC = matrix([[-0.0023763, -0.9999970, -0.0006416],
[0.9999923, -0.0023783, 0.0031244],
[-0.0031259, -0.0006342, 0.9999949]])
class TestUBCalculationWithWillmotStrategy_Pt531():
def setup_method(self):
hardware = Mock()
hardware.get_axes_names.return_value = ('d', 'g', 'oh', 'p')
self.ubcalc = UBCalculation(hardware, WillmottHorizontalGeometry(),
UbCalculationNonPersister(),
WillmottHorizontalUbCalcStrategy())
def testAgainstResultsFromJan_27_2010(self):
self.ubcalc.start_new('test')
self.ubcalc.set_lattice('Pt531', 6.204, 4.806, 23.215, 90, 90, 49.8)
self.ubcalc.add_reflection(
Pt531_HKL0[0], Pt531_HKL0[1], Pt531_HKL0[2], Pt531_REF0,
12.39842 / Pt531_WAVELENGTH, 'ref0', None)
self.ubcalc.add_reflection(
Pt531_HKL1[0], Pt531_HKL1[1], Pt531_HKL1[2], Pt531_REF1,
12.39842 / Pt531_WAVELENGTH, 'ref1', None)
self.ubcalc.calculate_UB()
print "U: ", self.ubcalc.U
print "UB: ", self.ubcalc.UB
matrixeq_(self.ubcalc.U, Pt531_U_DIFFCALC)
class TestSurfaceNormalVertical_Pt531_PosGamma(_BaseTest):
def setup_method(self):
_BaseTest.setup_method(self)
self.constraints.reference = {'betain': 2}
self.wavelength = Pt531_WAVELENGTH
cut = CrystalUnderTest('Pt531', 6.204, 4.806, 23.215, 90, 90, 49.8)
B = cut.B
self.UB = Pt531_U_DIFFCALC * B
diffcalc.hkl.willmott.calc.CHOOSE_POSITIVE_GAMMA = True
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
# self._check_angles_to_hkl('', 999, 999, hkl, pos, self.wavelength,
# virtual_expected)
if fails:
self._check_hkl_to_angles_fails('', 999, 999, hkl, pos,
self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles('', 999, 999, hkl, pos, self.wavelength,
virtual_expected)
def testHkl_0_found_orientation_setting(self):
'''Check that the or0 reflection maps back to the assumed hkl'''
self.places = 1
self._check_angles_to_hkl('', 999, 999, Pt531_HKL0,
Pt531_REF0,
self.wavelength, {'betain': 2})
def testHkl_1_found_orientation_setting(self):
'''Check that the or1 reflection maps back to the assumed hkl'''
self.places = 0
self._check_angles_to_hkl('', 999, 999, Pt531_HKL1,
Pt531_REF1,
self.wavelength, {'betain': 2})
def testHkl_0_predicted_versus_found_during_oriantation_phase(self):
self._check(Pt531_HKL0,
Pt531_REF0_DIFFCALC, # inspected as close to Pt531_REF0
{'betain': 2})
def testHkl_1_predicted_versus_found_during_oriantation_phase(self):
self._check(Pt531_HKL1,
Pt531_REF1_DIFFCALC, # inspected as close to Pt531_REF1,
{'betain': 2})
def testHkl_2_predicted_versus_found_during_oriantation_phase(self):
self._check(Pt531_HKL2,
Pt531_REF2_DIFFCALC, # inspected as close to Pt531_REF2
{'betain': 2})

View File

@@ -0,0 +1,824 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
from math import pi, cos, sin
from nose.tools import raises
try:
from numpy import matrix
except ImportError:
from numjy import matrix
from diffcalc.hkl.you.calc import YouHklCalculator
from diffcalc.hkl.you.constraints import YouConstraintManager
from test.tools import assert_array_almost_equal, \
assert_second_dict_almost_in_first
from diffcalc.ub.crystal import CrystalUnderTest
from diffcalc.util import y_rotation, z_rotation, DiffcalcException
from test.diffcalc.test_hardware import SimpleHardwareAdapter
from test.diffcalc.hkl.vlieg.test_calc import \
createMockDiffractometerGeometry, createMockUbcalc
from diffcalc.hkl.you.geometry import YouPosition as Pos, YouPosition as P,\
YouPosition
from test.tools import arrayeq_
from diffcalc.hkl.you.calc import youAnglesToHkl
TORAD = pi / 180
TODEG = 180 / pi
I = matrix('1 0 0; 0 1 0; 0 0 1')
from diffcalc.hkl.you.constraints import NUNAME
class Pair:
def __init__(self, name, hkl, position, fails=False):
self.name = name
self.hkl = hkl
self.position = position
self.fails = fails
class _BaseTest():
def setup_method(self):
self.mock_ubcalc = createMockUbcalc(None)
self.mock_geometry = createMockDiffractometerGeometry()
names = ['delta', NUNAME, 'mu', 'eta', 'chi', 'phi']
self.mock_hardware = SimpleHardwareAdapter(names)
self.constraints = YouConstraintManager(self.mock_hardware)
self.calc = YouHklCalculator(self.mock_ubcalc, self.mock_geometry,
self.mock_hardware, self.constraints)
self.mock_hardware.set_lower_limit('delta', 0)
self.mock_hardware.set_upper_limit('delta', 179.999)
self.mock_hardware.set_lower_limit(NUNAME, 0)
self.mock_hardware.set_upper_limit(NUNAME, 179.999)
self.mock_hardware.set_lower_limit('mu', 0)
self.mock_hardware.set_lower_limit('eta', 0)
self.mock_hardware.set_lower_limit('chi', -10)
self.places = 11
def _configure_ub(self):
ZROT = z_rotation(self.zrot * TORAD) # -PHI
YROT = y_rotation(self.yrot * TORAD) # +CHI
U = ZROT * YROT
UB = U * self.B
self.mock_ubcalc.UB = UB
def _check_hkl_to_angles(self, testname, zrot, yrot, hkl, pos_expected,
wavelength, virtual_expected={}):
print ('_check_hkl_to_angles(%s, %.1f, %.1f, %s, %s, %.2f, %s)' %
(testname, zrot, yrot, hkl, pos_expected, wavelength,
virtual_expected))
self.zrot, self.yrot = zrot, yrot
self._configure_ub()
pos, virtual = self.calc.hklToAngles(hkl[0], hkl[1], hkl[2],
wavelength)
assert_array_almost_equal(pos.totuple(), pos_expected.totuple(),
self.places)
assert_second_dict_almost_in_first(virtual, virtual_expected)
def _check_angles_to_hkl(self, testname, zrot, yrot, hkl_expected, pos,
wavelength, virtual_expected={}):
print ('_check_angles_to_hkl(%s, %.1f, %.1f, %s, %s, %.2f, %s)' %
(testname, zrot, yrot, hkl_expected, pos, wavelength,
virtual_expected))
self.zrot, self.yrot = zrot, yrot
self._configure_ub()
hkl, virtual = self.calc.anglesToHkl(pos, wavelength)
assert_array_almost_equal(hkl, hkl_expected, self.places, note="***Test (not diffcalc!) incorrect*** : the desired settings do not map to the target hkl")
assert_second_dict_almost_in_first(virtual, virtual_expected)
@raises(DiffcalcException)
def _check_hkl_to_angles_fails(self, *args):
self._check_hkl_to_angles(*args)
def case_generator(self):
for case in self.cases:
yield (self._check_angles_to_hkl, case.name, self.zrot, self.yrot,
case.hkl, case.position, self.wavelength, {})
test_method = (self._check_hkl_to_angles_fails if case.fails else
self._check_hkl_to_angles)
yield (test_method, case.name, self.zrot, self.yrot, case.hkl,
case.position, self.wavelength, {})
class _TestCubic(_BaseTest):
def setup_method(self):
_BaseTest.setup_method(self)
self.B = I * 2 * pi
class _TestCubicVertical(_TestCubic):
def setup_method(self):
_TestCubic.setup_method(self)
def makes_cases(self, zrot, yrot):
self.zrot = zrot
self.yrot = yrot
self.wavelength = 1
self.cases = (
Pair('100', (1, 0, 0),
Pos(mu=0, delta=60, nu=0, eta=30, chi=0 - self.yrot,
phi=0 + self.zrot)),
Pair('100-->001', (cos(4 * TORAD), 0, sin(4 * TORAD)),
Pos(mu=0, delta=60, nu=0, eta=30, chi=4 - self.yrot,
phi=0 + self.zrot),),
Pair('010', (0, 1, 0),
Pos(mu=0, delta=60, nu=0, eta=30, chi=0, phi=90 + self.zrot)),
Pair('001', (0, 0, 1),
Pos(mu=0, delta=60, nu=0, eta=30, chi=90 - self.yrot,
phi=0 + self.zrot)),
Pair('0.1 0 1.5', (0.1, 0, 1.5), # cover case where delta > 90 !
Pos(mu=0, delta=97.46959231642, nu=0,
eta=97.46959231642/2, chi=86.18592516571 - self.yrot,
phi=0 + self.zrot)),
Pair('001-->100', (cos(86 * TORAD), 0, sin(86 * TORAD)),
Pos(mu=0, delta=60, nu=0, eta=30, chi=86 - self.yrot,
phi=0 + self.zrot)),
)
self.case_dict = {}
for case in self.cases:
self.case_dict[case.name] = case
def test_pairs_zrot0_yrot0(self):
self.makes_cases(0, 0)
self.case_dict['001'].fails = True # q||n
for case_tuple in self.case_generator():
yield case_tuple
def test_pairs_various_zrot_and_yrot0(self):
for zrot in [0, 2, -2, 45, -45, 90, -90]: # -180, 180 work if recut
self.makes_cases(zrot, 0)
self.case_dict['001'].fails = True # q||n
for case_tuple in self.case_generator():
yield case_tuple
def test_hkl_to_angles_zrot1_yrot2(self):
self.makes_cases(1, 2)
for case_tuple in self.case_generator():
yield case_tuple
def test_hkl_to_angles_zrot1_yrotm2(self):
self.makes_cases(1, -2)
for case_tuple in self.case_generator():
yield case_tuple
def testHklDeltaGreaterThan90(self):
wavelength = 1
hkl = (0.1, 0, 1.5)
pos = P(mu=0, delta=97.46959231642, nu=0,
eta=97.46959231642/2, chi=86.18592516571,
phi=0)
self._check_hkl_to_angles('', 0, 0, hkl, pos, wavelength)
class TestCubicVertical_aeqb(_TestCubicVertical):
def setup_method(self):
_TestCubicVertical.setup_method(self)
self.constraints._constrained = {'a_eq_b': None, 'mu': 0, NUNAME: 0}
class TestCubicVertical_psi_90(_TestCubicVertical):
'''mode psi=90 should be the same as mode a_eq_b'''
def setup_method(self):
_TestCubicVertical.setup_method(self)
self.constraints._constrained = {'psi': 90 * TORAD, 'mu': 0, NUNAME: 0}
class TestCubicVertical_qaz_90(_TestCubicVertical):
'''mode psi=90 should be the same as mode a_eq_b'''
def setup_method(self):
_TestCubicVertical.setup_method(self)
self.constraints._constrained = {'a_eq_b': None, 'mu': 0,
'qaz': 90 * TORAD}
class SkipTestYouHklCalculatorWithCubicMode_aeqb_delta_60(_TestCubicVertical):
'''
Works to 4-5 decimal places but chooses different solutions when phi||eta .
Skip all tests.
'''
def setup_method(self):
_TestCubicVertical.setup_method(self)
self.constraints._constrained = {'a_eq_b': None, 'mu': 0,
'delta': 60 * TORAD}
self.places = 5
class _TestCubicHorizontal(_TestCubic):
def setup_method(self):
_TestCubic.setup_method(self)
def makes_cases(self, zrot, yrot):
self.zrot = zrot
self.yrot = yrot
self.wavelength = 1
self.cases = (
Pair('100', (1, 0, 0),
Pos(mu=30, delta=0, nu=60, eta=0, chi=90 + self.yrot,
phi=-180 + self.zrot)),
Pair('100-->001', (cos(4 * TORAD), 0, sin(4 * TORAD)),
Pos(mu=30, delta=0, nu=60, eta=0, chi=90 - 4 + self.yrot,
phi=-180 + self.zrot)),
Pair('010', (0, 1, 0),
Pos(mu=30, delta=0, nu=60, eta=0, chi=90,
phi=-90 + self.zrot)), # no yrot as chi||q
Pair('001', (0, 0, 1),
Pos(mu=30, delta=0, nu=60, eta=0, chi=0 - self.yrot,
phi=0 + self.zrot)),
Pair('001-->100', (cos(86 * TORAD), 0, sin(86 * TORAD)),
Pos(mu=30, delta=0, nu=60, eta=0, chi=0 - 4 - self.yrot,
phi=0 + self.zrot)),
)
self.case_dict = {}
for case in self.cases:
self.case_dict[case.name] = case
def test_pairs_zrot0_yrot0(self):
self.makes_cases(0, 0)
self.case_dict['001'].fails = True # q||n
self.case_dict['100'].position.phi = 180 # not -180
self.case_dict['100-->001'].position.phi = 180 # not -180
for case_tuple in self.case_generator():
yield case_tuple
# def test_pairs_various_zrot_and_yrot0(self):
# for zrot in [0, 2, -2, 45, -45, 90, -90]:
# -180, 180 work but with cut problem
# self.makes_cases(zrot, 0)
# self.case_dict['001'].fails = True # q||n
# for case_tuple in self.case_generator():
# yield case_tuple
def test_hkl_to_angles_zrot1_yrot2(self):
self.makes_cases(1, 2)
for case_tuple in self.case_generator():
yield case_tuple
def test_hkl_to_angles_zrot1_yrotm2(self):
self.makes_cases(1, -2)
for case_tuple in self.case_generator():
yield case_tuple
class TestCubicHorizontal_qaz0_aeqb(_TestCubicHorizontal):
def setup_method(self):
_TestCubicHorizontal.setup_method(self)
self.constraints._constrained = {'a_eq_b': None, 'qaz': 0, 'eta': 0}
class TestCubicHorizontal_delta0_aeqb(_TestCubicHorizontal):
def setup_method(self):
_TestCubicHorizontal.setup_method(self)
self.constraints._constrained = {'a_eq_b': None, 'delta': 0, 'eta': 0}
class TestAgainstSpecSixcB16_270608(_BaseTest):
'''NOTE: copied from test.diffcalc.scenarios.session3'''
def setup_method(self):
_BaseTest.setup_method(self)
U = matrix(((0.997161, -0.062217, 0.042420),
(0.062542, 0.998022, -0.006371),
(-0.041940, 0.009006, 0.999080)))
B = matrix(((1.636204, 0, 0),
(0, 1.636204, 0),
(0, 0, 1.156971)))
self.UB = U * B
self.constraints._constrained = {'a_eq_b': None, 'mu': 0, NUNAME: 0}
self.places = 2 # TODO: the Vlieg code got this to 3 decimal places
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def makes_cases(self, zrot, yrot):
del zrot, yrot # not used
self.wavelength = 1.24
self.cases = (
Pair('7_9_13', (0.7, 0.9, 1.3),
Pos(mu=0, delta=27.352179, nu=0, eta=13.676090,
chi=37.774500, phi=53.965500)),
Pair('100', (1, 0, 0),
Pos(mu=0, delta=18.580230, nu=0, eta=9.290115,
chi=-2.403500, phi=3.589000)),
Pair('010', (0, 1, 0),
Pos(mu=0, delta=18.580230, nu=0, eta=9.290115,
chi=0.516000, phi=93.567000)),
Pair('110', (1, 1, 0),
Pos(mu=0, delta=26.394192, nu=0, eta=13.197096,
chi=-1.334500, phi=48.602000)),
)
self.case_dict = {}
for case in self.cases:
self.case_dict[case.name] = case
def case_generator(self):
zrot, yrot = 999, 999
for case in self.cases:
yield (self._check_angles_to_hkl, case.name, zrot, yrot, case.hkl,
case.position, self.wavelength, {})
test_method = (self._check_hkl_to_angles_fails if case.fails else
self._check_hkl_to_angles)
yield (test_method, case.name, zrot, yrot, case.hkl, case.position,
self.wavelength, {})
def test_hkl_to_angles_given_UB(self):
self.makes_cases(None, None) # xrot, yrot unused
for case_tuple in self.case_generator():
yield case_tuple
class SkipTestThreeTwoCircleForDiamondI06andI10(_BaseTest):
"""
This is a three circle diffractometer with only delta and omega axes
and a chi axis with limited range around 90. It is operated with phi
fixed and can only reach reflections with l (or z) component.
The data here is taken from an experiment performed on Diamonds I06
beamline.
"""
def setup_method(self):
_BaseTest.setup_method(self)
self.constraints._constrained = {'phi': -pi / 2, NUNAME: 0, 'mu': 0}
self.wavelength = 12.39842 / 1.650
def _configure_ub(self):
U = matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
B = CrystalUnderTest('xtal', 5.34, 5.34, 13.2, 90, 90, 90).B
self.mock_ubcalc.UB = U * B
def testHkl001(self):
hkl = (0, 0, 1)
pos = Pos(mu=0, delta=33.07329403295449, nu=0, eta=16.536647016477247,
chi=90, phi=-90)
self._check_angles_to_hkl(
'001', 999, 999, hkl, pos, self.wavelength, {})
self._check_hkl_to_angles(
'001', 999, 999, hkl, pos, self.wavelength, {})
def testHkl100(self):
hkl = (1, 0, 0)
pos = Pos(mu=0, delta=89.42926563609406, nu=0, eta=134.71463281804702,
chi=90, phi=-90)
self._check_angles_to_hkl(
'100', 999, 999, hkl, pos, self.wavelength, {})
self._check_hkl_to_angles(
'100', 999, 999, hkl, pos, self.wavelength, {})
def testHkl101(self):
hkl = (1, 0, 1)
pos = Pos(mu=0, delta=98.74666191021282, nu=0, eta=117.347760720783,
chi=90, phi=-90)
self._check_angles_to_hkl(
'101', 999, 999, hkl, pos, self.wavelength, {})
self._check_hkl_to_angles(
'101', 999, 999, hkl, pos, self.wavelength, {})
class TestFixedChiPhiPsiMode_DiamondI07SurfaceNormalHorizontal(_TestCubic):
"""
The data here is taken from an experiment performed on Diamonds I07
beamline, obtained using Vlieg's DIF software"""
def setup_method(self):
_TestCubic.setup_method(self)
self.mock_hardware.set_lower_limit(NUNAME, 0)
self.mock_hardware.set_upper_limit('delta', 90)
self.constraints._constrained = {'chi': 0, 'phi': 0, 'a_eq_b': None}
self.wavelength = 1
self.UB = I * 2 * pi
self.places = 4
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
self._check_angles_to_hkl(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
if fails:
self._check_hkl_to_angles_fails(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
def testHkl001(self):
self._check((0, 0, 1), # betaout=30
P(mu=30, delta=0, nu=60, eta=90, chi=0, phi=0), fails=True)
def testHkl010(self):
self._check((0, 1, 0), # betaout=0
P(mu=0, delta=60, nu=0, eta=120, chi=0, phi=0))
def testHkl011(self):
self._check((0, 1, 1), # betaout=30
P(mu=30, delta=54.7356, nu=90, eta=125.2644, chi=0, phi=0))
def testHkl100(self):
self._check((1, 0, 0), # betaout=0
P(mu=0, delta=60, nu=0, eta=30, chi=0, phi=0))
def testHkl101(self):
self._check((1, 0, 1), # betaout=30
P(mu=30, delta=54.7356, nu=90, eta=35.2644, chi=0, phi=0))
def testHkl110(self):
self._check((1, 1, 0), # betaout=0
P(mu=0, delta=90, nu=0, eta=90, chi=0, phi=0))
def testHkl11nearly0(self):
self.places = 3
self._check((1, 1, .0001), # betaout=0
P(mu=0.0029, delta=89.9971, nu=90.0058, eta=90, chi=0,
phi=0))
def testHkl111(self):
self._check((1, 1, 1), # betaout=30
P(mu=30, delta=54.7356, nu=150, eta=99.7356, chi=0, phi=0))
def testHklover100(self):
self._check((1.1, 0, 0), # betaout=0
P(mu=0, delta=66.7340, nu=0, eta=33.3670, chi=0, phi=0))
def testHklunder100(self):
self._check((.9, 0, 0), # betaout=0
P(mu=0, delta=53.4874, nu=0, eta=26.7437, chi=0, phi=0))
def testHkl788(self):
self._check((.7, .8, .8), # betaout=23.5782
P(mu=23.5782, delta=59.9980, nu=76.7037, eta=84.2591,
chi=0, phi=0))
def testHkl789(self):
self._check((.7, .8, .9), # betaout=26.7437
P(mu=26.74368, delta=58.6754, nu=86.6919, eta=85.3391,
chi=0, phi=0))
def testHkl7810(self):
self._check((.7, .8, 1), # betaout=30
P(mu=30, delta=57.0626, nu=96.86590, eta=86.6739, chi=0,
phi=0))
class SkipTestFixedChiPhiPsiModeSurfaceNormalVertical(_TestCubic):
def setup_method(self):
_TestCubic.setup_method(self)
self.mock_hardware.set_lower_limit(NUNAME, 0)
self.constraints._constrained = {'chi': 90 * TORAD, 'phi': 0,
'a_eq_b': None}
self.wavelength = 1
self.UB = I * 2 * pi
self.places = 4
self.mock_hardware.set_lower_limit('mu', None)
self.mock_hardware.set_lower_limit('eta', None)
self.mock_hardware.set_lower_limit('chi', None)
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
self._check_angles_to_hkl(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
if fails:
self._check_hkl_to_angles_fails(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
def testHkl001(self):
self._check((0, 0, 1), # betaout=30
P(mu=30, delta=0, nu=60, eta=90, chi=0, phi=0), fails=True)
def testHkl010(self):
self._check((0, 1, 0), # betaout=0
P(mu=120, delta=0, nu=60, eta=0, chi=90, phi=0))
def testHkl011(self):
self._check((0, 1, 1), # betaout=30
P(mu=30, delta=54.7356, nu=90, eta=125.2644, chi=0, phi=0))
def testHkl100(self):
self._check((1, 0, 0), # betaout=0
P(mu=0, delta=60, nu=0, eta=30, chi=0, phi=0))
def testHkl101(self):
self._check((1, 0, 1), # betaout=30
P(mu=30, delta=54.7356, nu=90, eta=35.2644, chi=0, phi=0))
def testHkl110(self):
self._check((1, 1, 0), # betaout=0
P(mu=0, delta=90, nu=0, eta=90, chi=0, phi=0))
def testHkl11nearly0(self):
self.places = 3
self._check((1, 1, .0001), # betaout=0
P(mu=0.0029, delta=89.9971, nu=90.0058, eta=90, chi=0,
phi=0))
def testHkl111(self):
self._check((1, 1, 1), # betaout=30
P(mu=30, delta=54.7356, nu=150, eta=99.7356, chi=0, phi=0))
def testHklover100(self):
self._check((1.1, 0, 0), # betaout=0
P(mu=0, delta=66.7340, nu=0, eta=33.3670, chi=0, phi=0))
def testHklunder100(self):
self._check((.9, 0, 0), # betaout=0
P(mu=0, delta=53.4874, nu=0, eta=26.7437, chi=0, phi=0))
def testHkl788(self):
self._check((.7, .8, .8), # betaout=23.5782
P(mu=23.5782, delta=59.9980, nu=76.7037, eta=84.2591,
chi=0, phi=0))
def testHkl789(self):
self._check((.7, .8, .9), # betaout=26.7437
P(mu=26.74368, delta=58.6754, nu=86.6919, eta=85.3391,
chi=0, phi=0))
def testHkl7810(self):
self._check((.7, .8, 1), # betaout=30
P(mu=30, delta=57.0626, nu=96.86590, eta=86.6739, chi=0,
phi=0))
class SkipTestFixedChiPhiPsiModeSurfaceNormalVerticalI16(_TestCubic):
# testing with Chris N. for pre christmas 2012 i16 experiment
def setup_method(self):
_TestCubic.setup_method(self)
self.mock_hardware.set_lower_limit('nu', 0)
self.constraints._constrained = {'chi': 90 * TORAD, 'phi': 0,
'a_eq_b': None}
self.wavelength = 1
self.UB = I * 2 * pi
self.places = 4
self.mock_hardware.set_lower_limit('mu', None)
self.mock_hardware.set_lower_limit('eta', None)
self.mock_hardware.set_lower_limit('chi', None)
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
# self._check_angles_to_hkl(
# '', 999, 999, hkl, pos, self.wavelength, virtual_expected)
if fails:
self._check_hkl_to_angles_fails(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
def testHkl_1_1_0(self):
self._check((1, 1, 0.001), # betaout=0
P(mu=0, delta=60, nu=0, eta=30, chi=0, phi=0))
#(-89.9714, 89.9570, 90.0382, 90.0143, 90.0000, 0.0000)
def testHkl_1_1_05(self):
self._check((1, 1, 0.5), # betaout=0
P(mu=0, delta=60, nu=0, eta=30, chi=0, phi=0))
def testHkl_1_1_1(self):
self._check((1, 1, 1), # betaout=0
P(mu=0, delta=60, nu=0, eta=30, chi=0, phi=0))
# (-58.6003, 42.7342, 132.9004, 106.3249, 90.0000, 0.0000
def testHkl_1_1_15(self):
self._check((1, 1, 1.5), # betaout=0
P(mu=0, delta=60, nu=0, eta=30, chi=0, phi=0))
class TestConstrain3Sample_ChiPhiEta(_TestCubic):
def setup_method(self):
_TestCubic.setup_method(self)
self.mock_hardware.set_lower_limit(NUNAME, 0)
self.constraints._constrained = {'chi': 90 * TORAD, 'phi': 0,
'a_eq_b': None}
self.wavelength = 1
self.UB = I * 2 * pi
self.places = 4
self.mock_hardware.set_lower_limit('mu', None)
self.mock_hardware.set_lower_limit('eta', None)
self.mock_hardware.set_lower_limit('chi', None)
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
self._check_angles_to_hkl(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
if fails:
self._check_hkl_to_angles_fails(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
def testHkl_all0_001(self):
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 0}
self._check((0, 0, 1),
P(mu=30, delta=0, nu=60, eta=0, chi=0, phi=0))
def testHkl_all0_010(self):
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 0}
self._check((0, 1, 0),
P(mu=120, delta=0, nu=60, eta=0, chi=0, phi=0))
def testHkl_all0_011(self):
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 0}
self._check((0, 1, 1),
P(mu=90, delta=0, nu=90, eta=0, chi=0, phi=0))
def testHkl_phi30_100(self):
self.constraints._constrained = {'chi': 0, 'phi': 30 * TORAD, 'eta': 0}
self._check((1, 0, 0),
P(mu=0, delta=60, nu=0, eta=0, chi=0, phi=30))
def testHkl_eta30_100(self):
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 30 * TORAD}
self._check((1, 0, 0),
P(mu=0, delta=60, nu=0, eta=30, chi=0, phi=0))
def testHkl_phi90_110(self):
self.constraints._constrained = {'chi': 0, 'phi': 90 * TORAD, 'eta': 0}
self._check((1, 1, 0),
P(mu=0, delta=90, nu=0, eta=0, chi=0, phi=90))
def testHkl_eta90_110(self):
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 90 * TORAD}
self._check((1, 1, 0),
P(mu=0, delta=90, nu=0, eta=90, chi=0, phi=0))
def testHkl_all0_1(self):
self.mock_hardware.set_upper_limit('delta', 91)
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 0 * TORAD}
self._check((.01, .01, .1),
P(mu=8.6194, delta=0.5730, nu=5.7607, eta=0, chi=0, phi=0))
def testHkl_all0_2(self):
self.mock_hardware.set_upper_limit('delta', 91)
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 0 * TORAD}
self._check((0, 0, .1),
P(mu=2.8660, delta=0, nu=5.7320, eta=0, chi=0, phi=0))
def testHkl_all0_3(self):
self.mock_hardware.set_upper_limit('delta', 91)
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 0 * TORAD}
self._check((.1, 0, .01),
P(mu=30.3314, delta=5.7392, nu= 0.4970, eta=0, chi=0, phi=0))
def testHkl_show_all_solutionsall0_3(self):
self.mock_hardware.set_upper_limit('delta', 91)
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 0 * TORAD}
self._check((.1, 0, .01),
P(mu=30.3314, delta=5.7392, nu= 0.4970, eta=0, chi=0, phi=0))
print self.calc.hkl_to_all_angles(.1, 0, .01, 1)
def testHkl_all0_010to001(self):
self.constraints._constrained = {'chi': 0, 'phi': 0, 'eta': 0}
self._check((0, cos(4 * TORAD), sin(4 * TORAD)),
P(mu=120-4, delta=0, nu=60, eta=0, chi=0, phi=0))
def testHkl_1(self):
self.wavelength = .1
self.constraints._constrained = {'chi': 0, 'phi': 0 * TORAD, 'eta': 0}
self._check((0, 0, 1),
P(mu=2.8660, delta=0, nu=5.7320, eta=0, chi=0, phi=0))
def testHkl_2(self):
self.wavelength = .1
self.constraints._constrained = {'chi': 0, 'phi': 0 * TORAD, 'eta': 0}
self._check((0, 0, 1),
P(mu=2.8660, delta=0, nu=5.7320, eta=0, chi=0, phi=0))
def testHkl_3(self):
self.mock_hardware.set_upper_limit('delta', 91)
self.wavelength = .1
self.constraints._constrained = {'chi': 0, 'phi': 0 * TORAD, 'eta': 0}
self._check((1, 0, .1),
P(mu= 30.3314, delta=5.7392, nu= 0.4970, eta=0, chi=0, phi=0))
class TestHorizontalDeltaNadeta0_JiraI16_32_failure(_BaseTest):
"""
The data here is taken from a trial experiment which failed. Diamond's internal Jira:
http://jira.diamond.ac.uk/browse/I16-32"""
def setup_method(self):
_BaseTest.setup_method(self)
self.mock_hardware.set_lower_limit(NUNAME, 0)
self.wavelength = 12.39842 / 8
self.UB = matrix([[ -1.46410390e+00, -1.07335571e+00, 2.44799214e-03],
[ 3.94098508e-01, -1.07091934e+00, -6.41132943e-04],
[ 7.93297438e-03, 4.01315826e-03, 4.83650166e-01]])
self.places = 3
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False, skip_test_pair_verification=False):
if not skip_test_pair_verification:
self._check_angles_to_hkl(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
if fails:
self._check_hkl_to_angles_fails(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles(
'', 999, 999, hkl, pos, self.wavelength, virtual_expected)
def test_hkl_bisecting_works_okay_on_i16(self):
self.constraints._constrained = {'delta': 0, 'a_eq_b': None, 'eta': 0}
self._check([-1.1812112493619709, -0.71251524866987204, 5.1997083010199221],
P(mu=26, delta=0, nu=52, eta=0, chi=45.2453, phi=186.6933-360), fails=False)
def test_hkl_psi90_works_okay_on_i16(self):
# This is failing here but on the live one. Suggesting some extreme sensitivity?
self.constraints._constrained = {'delta': 0, 'psi': 90 * TORAD, 'eta': 0}
self._check([-1.1812112493619709, -0.71251524866987204, 5.1997083010199221],
P(mu=26, delta=0, nu=52, eta=0, chi=45.2453, phi=186.6933-360), fails=False)
def test_hkl_alpha_17_9776_used_to_fail(self):
# This is failing here but on the live one. Suggesting some extreme sensitivity?
self.constraints._constrained = {'delta': 0, 'alpha': 17.9776 * TORAD, 'eta': 0}
self._check([-1.1812112493619709, -0.71251524866987204, 5.1997083010199221],
P(mu=26, delta=0, nu=52, eta=0, chi=45.2453, phi=186.6933-360), fails=False)
def test_hkl_alpha_17_9776_failing_after_bigger_small(self):
# This is failing here but on the live one. Suggesting some extreme sensitivity?
self.constraints._constrained = {'delta': 0, 'alpha': 17.8776 * TORAD, 'eta': 0}
self._check([-1.1812112493619709, -0.71251524866987204, 5.1997083010199221],
P(mu=25.85, delta=0, nu=52, eta=0, chi=45.2453, phi=-173.518), fails=False)
#skip_test_pair_verification
def posFromI16sEuler(phi, chi, eta, mu, delta, gamma):
return YouPosition(mu, delta, gamma, eta, chi, phi)
class TestAnglesToHkl_I16Examples():
def __init__(self):
self.UB1 = matrix((
(0.9996954135095477, -0.01745240643728364, -0.017449748351250637),
(0.01744974835125045, 0.9998476951563913, -0.0003045864904520898),
(0.017452406437283505, -1.1135499981271473e-16, 0.9998476951563912))
) * (2 * pi)
self.WL1 = 1 # Angstrom
def test_anglesToHkl_mu_0_gam_0(self):
pos = posFromI16sEuler(1, 1, 30, 0, 60, 0).inRadians()
arrayeq_(youAnglesToHkl(pos, self.WL1, self.UB1), [1, 0, 0])
def test_anglesToHkl_mu_0_gam_10(self):
pos = posFromI16sEuler(1, 1, 30, 0, 60, 10).inRadians()
arrayeq_(youAnglesToHkl(pos, self.WL1, self.UB1),
[1.00379806, -0.006578435, 0.08682408])
def test_anglesToHkl_mu_10_gam_0(self):
pos = posFromI16sEuler(1, 1, 30, 10, 60, 0).inRadians()
arrayeq_(youAnglesToHkl(pos, self.WL1, self.UB1),
[0.99620193, 0.0065784359, 0.08682408])
def test_anglesToHkl_arbitrary(self):
pos = posFromI16sEuler(1.9, 2.9, 30.9, 0.9, 60.9, 2.9).inRadians()
arrayeq_(youAnglesToHkl(pos, self.WL1, self.UB1),
[1.01174189, 0.02368622, 0.06627361])

View File

@@ -0,0 +1,707 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
import math
from math import pi, sin, cos
from nose.plugins.skip import SkipTest
from nose.tools import assert_almost_equal, raises, eq_ # @UnresolvedImport
from mock import Mock
try:
from numpy import matrix
except ImportError:
from numjy import matrix
from diffcalc.hkl.you.calc import YouHklCalculator, I, \
_calc_angle_between_naz_and_qaz, merge_nearly_equal_pairs
from test.tools import assert_matrix_almost_equal, \
assert_2darray_almost_equal, aneq_
from diffcalc.hkl.you.geometry import YouPosition
from test.diffcalc.hkl.vlieg.test_calc import \
createMockDiffractometerGeometry, createMockHardwareMonitor, \
createMockUbcalc
from test.diffcalc.test_hardware import SimpleHardwareAdapter
from diffcalc.util import DiffcalcException
from diffcalc.hkl.you.constraints import NUNAME
TORAD = pi / 180
TODEG = 180 / pi
x = matrix('1; 0; 0')
y = matrix('0; 1; 0')
z = matrix('0; 0; 1')
def isnan(n):
# math.isnan was introduced only in python 2.6 and is not in Jython (2.5.2)
try:
return math.isnan(n)
except AttributeError:
return n != n # for Jython
class Test_anglesToVirtualAngles():
def setup_method(self):
constraints = Mock()
constraints.is_fully_constrained.return_value = True
self.calc = YouHklCalculator(createMockUbcalc(None),
createMockDiffractometerGeometry(),
createMockHardwareMonitor(),
constraints)
def check_angle(self, name, expected, mu=-99, delta=99, nu=99,
eta=99, chi=99, phi=99):
"""All in degrees"""
pos = YouPosition(mu, delta, nu, eta, chi, phi)
pos.changeToRadians()
calculated = self.calc._anglesToVirtualAngles(pos, None)[name] * TODEG
assert_almost_equal(calculated, expected)
# theta
def test_theta0(self):
self.check_angle('theta', 0, delta=0, nu=0)
def test_theta1(self):
self.check_angle('theta', 1, delta=2, nu=0)
def test_theta2(self):
self.check_angle('theta', 1, delta=0, nu=2)
def test_theta3(self):
self.check_angle('theta', 1, delta=-2, nu=0)
def test_theta4(self):
self.check_angle('theta', 1, delta=0, nu=-2)
# qaz
def test_qaz0_degenerate_case(self):
self.check_angle('qaz', 0, delta=0, nu=0)
def test_qaz1(self):
self.check_angle('qaz', 90, delta=2, nu=0)
def test_qaz2(self):
self.check_angle('qaz', 90, delta=90, nu=0)
def test_qaz3(self):
self.check_angle('qaz', 0, delta=0, nu=1,)
# Can't see one by eye
# def test_qaz4(self):
# pos = YouPosition(delta=20*TORAD, nu=20*TORAD)#.inRadians()
# assert_almost_equal(
# self.calc._anglesToVirtualAngles(pos, None)['qaz']*TODEG, 45)
#alpha
def test_defaultReferenceValue(self):
# The following tests depemd on this
assert_matrix_almost_equal(self.calc._ubcalc.n_phi, matrix([[0], [0], [1]]))
def test_alpha0(self):
self.check_angle('alpha', 0, mu=0, eta=0, chi=0, phi=0)
def test_alpha1(self):
self.check_angle('alpha', 0, mu=0, eta=0, chi=0, phi=10)
def test_alpha2(self):
self.check_angle('alpha', 0, mu=0, eta=0, chi=0, phi=-10)
def test_alpha3(self):
self.check_angle('alpha', 2, mu=2, eta=0, chi=0, phi=0)
def test_alpha4(self):
self.check_angle('alpha', -2, mu=-2, eta=0, chi=0, phi=0)
def test_alpha5(self):
self.check_angle('alpha', 2, mu=0, eta=90, chi=2, phi=0)
#beta
def test_beta0(self):
self.check_angle('beta', 0, delta=0, nu=0, mu=0, eta=0, chi=0, phi=0)
def test_beta1(self):
self.check_angle('beta', 0, delta=10, nu=0, mu=0, eta=6, chi=0, phi=5)
def test_beta2(self):
self.check_angle('beta', 10, delta=0, nu=10, mu=0, eta=0, chi=0, phi=0)
def test_beta3(self):
self.check_angle('beta', -10, delta=0, nu=-10, mu=0, eta=0, chi=0,
phi=0)
def test_beta4(self):
self.check_angle('beta', 5, delta=0, nu=10, mu=5, eta=0, chi=0, phi=0)
# azimuth
def test_naz0(self):
self.check_angle('naz', 0, mu=0, eta=0, chi=0, phi=0)
def test_naz1(self):
self.check_angle('naz', 0, mu=0, eta=0, chi=0, phi=10)
def test_naz3(self):
self.check_angle('naz', 0, mu=10, eta=0, chi=0, phi=10)
def test_naz4(self):
self.check_angle('naz', 2, mu=0, eta=0, chi=2, phi=0)
def test_naz5(self):
self.check_angle('naz', -2, mu=0, eta=0, chi=-2, phi=0)
#tau
def test_tau0(self):
self.check_angle('tau', 0, mu=0, delta=0, nu=0, eta=0, chi=0, phi=0)
#self.check_angle('tau_from_dot_product', 90, mu=0, delta=0,
#nu=0, eta=0, chi=0, phi=0)
def test_tau1(self):
self.check_angle('tau', 90, mu=0, delta=20, nu=0, eta=10, chi=0, phi=0)
#self.check_angle('tau_from_dot_product', 90, mu=0, delta=20,
#nu=0, eta=10, chi=0, phi=0)
def test_tau2(self):
self.check_angle('tau', 90, mu=0, delta=20, nu=0, eta=10, chi=0, phi=3)
#self.check_angle('tau_from_dot_product', 90, mu=0, delta=20,
#nu=0, eta=10, chi=0, phi=3)
def test_tau3(self):
self.check_angle('tau', 88, mu=0, delta=20, nu=0, eta=10, chi=2, phi=0)
#self.check_angle('tau_from_dot_product', 88, mu=0, delta=20,
#nu=0, eta=10, chi=2, phi=0)
def test_tau4(self):
self.check_angle('tau', 92, mu=0, delta=20, nu=0, eta=10, chi=-2,
phi=0)
#self.check_angle('tau_from_dot_product', 92, mu=0, delta=20,
#nu=0, eta=10, chi=-2, phi=0)
def test_tau5(self):
self.check_angle('tau', 10, mu=0, delta=0, nu=20, eta=0, chi=0, phi=0)
#self.check_angle('tau_from_dot_product', 10, mu=0, delta=0,
#nu=20, eta=0, chi=0, phi=0)
#psi
def test_psi0(self):
pos = YouPosition(0, 0, 0, 0, 0, 0)
assert isnan(self.calc._anglesToVirtualAngles(pos, None)['psi'])
def test_psi1(self):
self.check_angle('psi', 90, mu=0, delta=11, nu=0, eta=0, chi=0, phi=0)
def test_psi2(self):
self.check_angle(
'psi', 100, mu=10, delta=.00000001, nu=0, eta=0, chi=0, phi=0)
def test_psi3(self):
self.check_angle(
'psi', 80, mu=-10, delta=.00000001, nu=0, eta=0, chi=0, phi=0)
def test_psi4(self):
self.check_angle(
'psi', 90, mu=0, delta=11, nu=0, eta=0, chi=0, phi=12.3)
def test_psi5(self):
#self.check_angle('psi', 0, mu=10, delta=.00000001,
#nu=0, eta=0, chi=90, phi=0)
pos = YouPosition(0, .00000001, 0, 0, 90, 0)
pos.changeToRadians()
assert isnan(self.calc._anglesToVirtualAngles(pos, None)['psi'])
def test_psi6(self):
self.check_angle(
'psi', 90, mu=0, delta=0.00000001, nu=0, eta=90, chi=0, phi=0)
def test_psi7(self):
self.check_angle(
'psi', 92, mu=0, delta=0.00000001, nu=0, eta=90, chi=2, phi=0)
def test_psi8(self):
self.check_angle(
'psi', 88, mu=0, delta=0.00000001, nu=0, eta=90, chi=-2, phi=0)
class Test_calc_theta():
def setup_method(self):
self.calc = YouHklCalculator(createMockUbcalc(I * 2 * pi),
createMockDiffractometerGeometry(),
createMockHardwareMonitor(),
Mock())
self.e = 12.398420 # 1 Angstrom
def test_100(self):
h_phi = matrix([[1], [0], [0]])
assert_almost_equal(self.calc._calc_theta(h_phi * 2 * pi, 1) * TODEG,
30)
@raises(DiffcalcException)
def test_too_short(self):
h_phi = matrix([[1], [0], [0]])
self.calc._calc_theta(h_phi * 0, 1)
@raises(DiffcalcException)
def test_too_long(self):
h_phi = matrix([[1], [0], [0]])
self.calc._calc_theta(h_phi * 2 * pi, 10)
class Test_calc_remaining_reference_angles_given_one():
# TODO: These are very incomplete due to either totally failing inutuition
# or code!
def setup_method(self):
self.calc = YouHklCalculator(createMockUbcalc(None),
createMockDiffractometerGeometry(),
createMockHardwareMonitor(),
Mock())
def check(self, name, value, theta, tau, psi_e, alpha_e, beta_e):
# all in deg
psi, alpha, beta = self.calc._calc_remaining_reference_angles(
name, value * TORAD, theta * TORAD, tau * TORAD)
print 'psi', psi * TODEG, ' alpha:', alpha * TODEG,\
' beta:', beta * TODEG
if psi_e is not None:
assert_almost_equal(psi * TODEG, psi_e)
if alpha_e is not None:
assert_almost_equal(alpha * TODEG, alpha_e)
if beta_e is not None:
assert_almost_equal(beta * TODEG, beta_e)
def test_psi_given0(self):
self.check('psi', 90, theta=10, tau=90, psi_e=90,
alpha_e=0, beta_e=0)
def test_psi_given1(self):
self.check('psi', 92, theta=0, tau=90, psi_e=92,
alpha_e=2, beta_e=-2)
def test_psi_given3(self):
self.check('psi', 88, theta=0, tau=90, psi_e=88,
alpha_e=-2, beta_e=2)
def test_psi_given4(self):
self.check('psi', 0, theta=0, tau=90, psi_e=0,
alpha_e=-90, beta_e=90)
def test_psi_given4a(self):
self.check('psi', 180, theta=0, tau=90, psi_e=180,
alpha_e=90, beta_e=-90)
def test_psi_given5(self):
raise SkipTest
# TODO: I don't understand why this one passes!
self.check('psi', 180, theta=0, tau=80,
psi_e=180, alpha_e=80, beta_e=-80)
self.check('psi', 180, theta=0, tau=80,
psi_e=180, alpha_e=90, beta_e=-90)
def test_a_eq_b0(self):
self.check('a_eq_b', 9999, theta=0, tau=90,
psi_e=90, alpha_e=0, beta_e=0)
def test_alpha_given(self):
self.check('alpha', 2, theta=0, tau=90,
psi_e=92, alpha_e=2, beta_e=-2)
def test_beta_given(self):
self.check('beta', 2, theta=0, tau=90,
psi_e=88, alpha_e=-2, beta_e=2)
# def test_a_eq_b1(self):
# self.check('a_eq_b', 9999, theta=20, tau=90,
# psi_e=90, alpha_e=10, beta_e=10)
# def test_psi_given0(self):
# self.check('psi', 90, theta=10, tau=45, psi_e=90,
# alpha_e=7.0530221302831952, beta_e=7.0530221302831952)
def test_merge_nearly_equal_detector_angle_pairs_different(self):
pairs = [(1,2), (1,2.1)]
assert_2darray_almost_equal(
merge_nearly_equal_pairs(pairs), pairs)
def test_merge_nearly_equal_detector_angle_pairs_1(self):
pairs = [(1, 2), (1, 2)]
assert_2darray_almost_equal(
merge_nearly_equal_pairs(pairs), [(1, 2)])
def test_merge_nearly_equal_detector_angle_pairs_2(self):
pairs = [(1, 2), (1, 2), (1, 2)]
assert_2darray_almost_equal(
merge_nearly_equal_pairs(pairs), [(1, 2)])
def test_merge_nearly_equal_detector_angle_pairs_3(self):
pairs = [(1, 2.2), (1, 2), (1, 2), (1, 2)]
assert_2darray_almost_equal(
merge_nearly_equal_pairs(pairs), [(1, 2.2), (1, 2)])
def test_merge_nearly_equal_detector_angle_pairs_4(self):
pairs = [(1, 2.2), (1, 2), (1, 2), (1, 2.2)]
assert_2darray_almost_equal(
merge_nearly_equal_pairs(pairs), [(1, 2.2), (1, 2)])
class Test_calc_detector_angles_given_one():
def setup_method(self):
self.calc = YouHklCalculator(createMockUbcalc(None),
createMockDiffractometerGeometry(),
createMockHardwareMonitor(),
Mock())
def check(self, name, value, theta, delta_e, nu_e, qaz_e):
# all in deg
delta, nu, qaz = self.calc._calc_remaining_detector_angles(
name, value * TORAD, theta * TORAD)
assert_almost_equal(delta * TODEG, delta_e)
assert_almost_equal(nu * TODEG, nu_e)
if qaz_e is not None:
assert_almost_equal(qaz * TODEG, qaz_e)
def test_nu_given0(self):
self.check(NUNAME, 0, theta=3, delta_e=6, nu_e=0, qaz_e=90)
def test_nu_given1(self):
self.check(NUNAME, 10, theta=7.0530221302831952,
delta_e=10, nu_e=10, qaz_e=None)
def test_nu_given2(self):
self.check(NUNAME, 6, theta=3, delta_e=0, nu_e=6, qaz_e=0)
def test_delta_given0(self):
self.check('delta', 0, theta=3, delta_e=0, nu_e=6, qaz_e=0)
def test_delta_given1(self):
self.check('delta', 10, theta=7.0530221302831952,
delta_e=10, nu_e=10, qaz_e=None)
def test_delta_given2(self):
self.check('delta', 6, theta=3, delta_e=6, nu_e=0, qaz_e=90)
def test_qaz_given0(self):
self.check('qaz', 90, theta=3, delta_e=6, nu_e=0, qaz_e=90)
def test_qaz_given2(self):
self.check('qaz', 0, theta=3, delta_e=0, nu_e=6, qaz_e=0)
class Test_calc_angle_between_naz_and_qaz():
def test1(self):
diff = _calc_angle_between_naz_and_qaz(
theta=0, alpha=0, tau=90 * TORAD)
assert_almost_equal(diff * TODEG, 90)
def test2(self):
diff = _calc_angle_between_naz_and_qaz(
theta=0 * TORAD, alpha=0, tau=80 * TORAD)
assert_almost_equal(diff * TODEG, 80)
class Test_calc_remaining_sample_angles_given_one():
#_calc_remaining_detector_angles_given_one
def setup_method(self):
self.calc = YouHklCalculator(createMockUbcalc(None),
createMockDiffractometerGeometry(),
createMockHardwareMonitor(),
Mock())
def check(self, name, value, Q_lab, n_lab, Q_phi, n_phi,
phi_e, chi_e, eta_e, mu_e):
phi, chi, eta, mu = self.calc._calc_remaining_sample_angles(
name, value * TORAD, Q_lab, n_lab, Q_phi, n_phi)
print 'phi', phi * TODEG, ' chi:', chi * TODEG, ' eta:', eta * TODEG,\
' mu:', mu * TODEG
if phi_e is not None:
assert_almost_equal(phi * TODEG, phi_e)
if chi_e is not None:
assert_almost_equal(chi * TODEG, chi_e)
if eta_e is not None:
assert_almost_equal(eta * TODEG, eta_e)
if mu_e is not None:
assert_almost_equal(mu * TODEG, mu_e)
@raises(ValueError)
def test_constrain_xx_degenerate(self):
self.check('mu', 0, Q_lab=x, n_lab=x, Q_phi=x, n_phi=x,
phi_e=0, chi_e=0, eta_e=0, mu_e=0)
def test_constrain_mu_0(self):
raise SkipTest()
self.check('mu', 0, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=0, chi_e=0, eta_e=0, mu_e=0)
def test_constrain_mu_10(self):
raise SkipTest()
self.check('mu', 10, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=-90, chi_e=10, eta_e=-90, mu_e=10)
def test_constrain_mu_n10(self):
raise SkipTest()
self.check('mu', -10, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=90, chi_e=10, eta_e=90, mu_e=-10)
def test_constrain_eta_10_wasfailing(self):
# Required the choice of a different equation
self.check('eta', 10, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=-10, chi_e=0, eta_e=10, mu_e=0)
def test_constrain_eta_n10(self):
self.check('eta', -10, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=10, chi_e=0, eta_e=-10, mu_e=0)
def test_constrain_eta_20_with_theta_20(self):
theta = 20 * TORAD
Q_lab = matrix([[cos(theta)], [-sin(theta)], [0]])
self.check('eta', 20, Q_lab=Q_lab, n_lab=z, Q_phi=x, n_phi=z,
phi_e=0, chi_e=0, eta_e=20, mu_e=0)
@raises(ValueError)
def test_constrain_chi_0_degenerate(self):
self.check('chi', 0, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=0, chi_e=0, eta_e=0, mu_e=0)
def test_constrain_chi_10(self):
self.check('chi', 10, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=-90, chi_e=10, eta_e=90, mu_e=-10)
def test_constrain_chi_90(self):
# mu is off by 180, but youcalc tries +-x and 180+-x anyway
raise SkipTest()
self.check('chi', 90, Q_lab=z * (-1), n_lab=x, Q_phi=x, n_phi=z,
phi_e=0, chi_e=90, eta_e=0, mu_e=0)
def test_constrain_phi_0(self):
self.check('phi', 0, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=0, chi_e=0, eta_e=0, mu_e=0)
def test_constrain_phi_10(self):
self.check('phi', 10, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=10, chi_e=0, eta_e=-10, mu_e=0)
def test_constrain_phi_n10(self):
self.check('phi', -10, Q_lab=x, n_lab=z, Q_phi=x, n_phi=z,
phi_e=-10, chi_e=0, eta_e=10, mu_e=0)
def test_constrain_phi_20_with_theta_20(self):
theta = 20 * TORAD
Q_lab = matrix([[cos(theta)], [-sin(theta)], [0]])
self.check('phi', 20, Q_lab=Q_lab, n_lab=z, Q_phi=x, n_phi=z,
phi_e=20, chi_e=0, eta_e=0, mu_e=0)
class TestSolutionGenerator():
def setup_method(self):
names = ['delta', NUNAME, 'mu', 'eta', 'chi', 'phi']
self.hardware = SimpleHardwareAdapter(names)
self.calc = YouHklCalculator(createMockUbcalc(None),
createMockDiffractometerGeometry(),
self.hardware,
Mock())
# constraint could have been 'delta', NUNAME, 'qaz' or 'naz'.
def test_generate_possible_det_soln_no_limits_constrained_qaz_or_naz(self):
# we will enfoce the order too, incase this later effects heuristically
# made choices
expected = (
(.1, .2),
(.1, -.2),
(.1, .2 - pi),
(.1, pi - .2),
(-.1, .2),
(-.1, -.2),
(-.1, .2 - pi),
(-.1, pi - .2),
(.1 - pi, .2), # pi + x cuts to x-pi
(.1 - pi, -.2),
(.1 - pi, .2 - pi),
(.1 - pi, pi - .2),
(pi - .1, .2),
(pi - .1, -.2),
(pi - .1, .2 - pi),
(pi - .1, pi - .2),
)
assert_2darray_almost_equal(expected,
self.calc._generate_possible_solutions(
(.1, .2), ('delta', NUNAME), ('naz',)))
assert_2darray_almost_equal(expected,
self.calc._generate_possible_solutions(
(.1, .2), ('delta', NUNAME), ('qaz',)))
def test_generate_poss_det_soln_no_lim_cons_qaz_or_naz_delta_and_nu_at_zro(self): # @IgnorePep8
# we will enfoce the order too, incase this later effects hearistically
# made choices
expected = (
(0., 0,),
(0., pi),
(pi, 0.),
(pi, pi)
)
assert_2darray_almost_equal(expected,
self.calc._generate_possible_solutions(
(-2e-9, 2e-9), ('delta', NUNAME), ('naz',)))
assert_2darray_almost_equal(expected,
self.calc._generate_possible_solutions(
(-2e-9, 2e-9), ('delta', NUNAME), ('qaz',)))
def test_generate_possible_det_solutions_no_limits_constrained_delta(self):
expected = (
(.1, .2),
(.1, -.2),
(.1, .2 - pi),
(.1, pi - .2),
)
assert_2darray_almost_equal(expected,
self.calc._generate_possible_solutions(
(.1, .2), ('delta', NUNAME), ('delta',)))
def test_generate_possible_det_solutions_no_limits_constrained_nu(self):
expected = (
(.1, .2),
(-.1, .2),
(.1 - pi, .2),
(pi - .1, .2),
)
assert_2darray_almost_equal(expected,
self.calc._generate_possible_solutions(
(.1, .2), ('delta', NUNAME), (NUNAME,)))
def test_generate_possible_det_soln_with_limits_constrained_delta(self):
self.hardware.set_lower_limit(NUNAME, 0)
expected = (
(.1, .2),
(.1, pi - .2),
)
assert_2darray_almost_equal(expected,
self.calc._generate_possible_solutions(
(.1, .2), ('delta', NUNAME), ('delta',)))
def test_generate_possible_det_solutions_with_limits_constrained_nu(self):
self.hardware.set_upper_limit('delta', 0)
expected = (
(-.1, .2),
(.1 - pi, .2), # cuts to .1-pi
)
assert_2darray_almost_equal(expected,
self.calc._generate_possible_solutions(
(.1, .2), ('delta', NUNAME), (NUNAME,)))
def test_generate_poss_det_soln_with_limits_overly_constrained_nu(self):
self.hardware.set_lower_limit('delta', .3)
self.hardware.set_upper_limit('delta', .31)
eq_(len(self.calc._generate_possible_solutions(
(.1, .2), ('delta', NUNAME), (NUNAME,))), 0)
def test_generate_possible_sample_solutions(self):
result = self.calc._generate_possible_solutions(
(.1, .2, .3, .4), ('mu', 'eta', 'chi', 'phi'), ('naz',))
generated = self._hardcoded_generate_possible_sample_solutions(
.1, .2, .3, .4, 'naz')
assert_2darray_almost_equal(generated, result)
eq_(4 ** 4, len(result))
def test_generate_possible_sample_solutions_fixed_chi(self):
result = self.calc._generate_possible_solutions(
(.1, .2, .3, .4), ('mu', 'eta', 'chi', 'phi'), ('chi',))
generated = self._hardcoded_generate_possible_sample_solutions(
.1, .2, .3, .4, 'chi')
assert_2darray_almost_equal(generated, result)
eq_(4 ** 3, len(result))
def test_generate_possible_sample_solutions_fixed_chi_positive_mu(self):
self.hardware.set_lower_limit('mu', 0)
result = self.calc._generate_possible_solutions(
(.1, .2, .3, .4), ('mu', 'eta', 'chi', 'phi'), ('chi',))
generated = self._hardcoded_generate_possible_sample_solutions(
.1, .2, .3, .4, 'chi')
assert_2darray_almost_equal(generated, result)
eq_(2 * (4 ** 2), len(result))
def _hardcoded_generate_possible_sample_solutions(self, mu, eta, chi, phi,
sample_constraint_name):
possible_solutions = []
_identity = lambda x: x
_transforms = (_identity,
lambda x: -x,
lambda x: pi + x,
lambda x: pi - x)
_transforms_for_zero = (lambda x: 0.,
lambda x: pi,)
SMALL = 1e-8
def cut_at_minus_pi(value):
if value < (-pi - SMALL):
return value + 2 * pi
if value >= pi + SMALL:
return value - 2 * pi
return value
def is_small(x):
return abs(x) < SMALL
name = sample_constraint_name
for transform in ((_identity,) if name == 'mu' else
_transforms if not is_small(mu) else
_transforms_for_zero):
transformed_mu = (transform(mu))
if not self.hardware.is_axis_value_within_limits('mu',
self.hardware.cut_angle('mu', transformed_mu * TODEG)):
continue
for transform in ((_identity,) if name == 'eta' else
_transforms if not is_small(eta) else
_transforms_for_zero):
transformed_eta = transform(eta)
if not self.hardware.is_axis_value_within_limits('eta',
self.hardware.cut_angle('eta', transformed_eta * TODEG)):
continue
for transform in ((_identity,) if name == 'chi' else
_transforms if not is_small(chi) else
_transforms_for_zero):
transformed_chi = transform(chi)
if not self.hardware.is_axis_value_within_limits('chi',
self.hardware.cut_angle('chi',
transformed_chi * TODEG)):
continue
for transform in ((_identity,) if name == 'phi' else
_transforms if not is_small(phi) else
_transforms_for_zero):
transformed_phi = transform(phi)
if not self.hardware.is_axis_value_within_limits('phi',
self.hardware.cut_angle('phi',
transformed_phi * TODEG)):
continue
possible_solutions.append((
cut_at_minus_pi(transformed_mu),
cut_at_minus_pi(transformed_eta),
cut_at_minus_pi(transformed_chi),
cut_at_minus_pi(transformed_phi)))
return possible_solutions

View File

@@ -0,0 +1,472 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
# TODO: class largely copied from test_calc
from math import pi
from mock import Mock
from nose.plugins.skip import SkipTest
try:
from numpy import matrix
except ImportError:
from numjy import matrix
from diffcalc.hkl.you.geometry import SixCircle
from diffcalc.hkl.willmott.calc import \
WillmottHorizontalPosition as WillPos
from diffcalc.hkl.you.geometry import YouPosition as YouPos
from diffcalc.hkl.you.calc import YouUbCalcStrategy
from test.tools import matrixeq_
from diffcalc.ub.calc import UBCalculation
from diffcalc.ub.crystal import CrystalUnderTest
from diffcalc.ub.persistence import UbCalculationNonPersister
from test.diffcalc.hkl.you.test_calc import _BaseTest
from diffcalc.hkl.you.constraints import NUNAME
TORAD = pi / 180
TODEG = 180 / pi
I = matrix('1 0 0; 0 1 0; 0 0 1')
class SkipTestSurfaceNormalVerticalCubic(_BaseTest):
def setup_method(self):
_BaseTest.setup_method(self)
self.constraints._constrained = {'a_eq_b': None, 'mu': -pi / 2,
'eta': 0}
self.wavelength = 1
self.UB = I * 2 * pi
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
if pos is not None:
self._check_angles_to_hkl('', 999, 999, hkl, pos, self.wavelength,
virtual_expected)
if fails:
self._check_hkl_to_angles_fails('', 999, 999, hkl, pos,
self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles('', 999, 999, hkl, pos, self.wavelength,
virtual_expected)
def testHkl001(self):
pos = YouPos(mu=-90, delta=60, nu=0, eta=0, chi=90 + 30, phi=-90)
self._check((0, 0, 1), pos, {'alpha': 30, 'beta': 30})
def testHkl011(self):
# raise SkipTest()
# skipped because we can't calculate values to check against by hand
pos = YouPos(mu=-90, delta=90, nu=0, eta=0, chi=90 + 90, phi=-90)
self._check((0, 1, 1), pos, {'alpha': 45, 'beta': 45})
def testHkl010fails(self):
self._check((0, 1, 0),
None,
{'alpha': 30, 'beta': 30}, fails=True)
def testHkl100fails(self):
self._check((1, 0, 0),
None,
{'alpha': 30, 'beta': 30}, fails=True)
def testHkl111(self):
raise SkipTest()
# skipped because we can't calculate values to check against by hand
pos = YouPos(mu=-90, delta=90, nu=0, eta=0, chi=90 + 90, phi=-90)
self._check((1, 1, 1), pos, {'alpha': 45, 'beta': 45})
# Primary and secondary reflections found with the help of DDIF on Diamond's
# i07 on Jan 27 2010
HKL0 = 2, 19, 32
REF0 = WillPos(delta=21.975, gamma=4.419, omegah=2, phi=326.2)
HKL1 = 0, 7, 22
REF1 = WillPos(delta=11.292, gamma=2.844, omegah=2, phi=124.1)
WAVELENGTH = 0.6358
ENERGY = 12.39842 / WAVELENGTH
# This is the version that Diffcalc comes up with ( see following test)
U_DIFFCALC = matrix([[-0.7178876, 0.6643924, -0.2078944],
[-0.6559596, -0.5455572, 0.5216170],
[0.2331402, 0.5108327, 0.8274634]])
#class WillmottHorizontalGeometry(VliegGeometry):
#
# def __init__(self):
# VliegGeometry.__init__(self,
# name='willmott_horizontal',
# supported_mode_groups=[],
# fixed_parameters={},
# gamma_location='base'
# )
#
# def physical_angles_to_internal_position(self, physicalAngles):
# assert (len(physicalAngles) == 4), "Wrong length of input list"
# return WillPos(*physicalAngles)
#
# def internal_position_to_physical_angles(self, internalPosition):
# return internalPosition.totuple()
def willmott_to_you_fixed_mu_eta(pos):
pos = YouPos(mu=-90,
delta=pos.delta,
nu=pos.gamma,
eta=0,
chi=90 + pos.omegah,
phi=-90 - pos.phi)
if pos.phi > 180:
pos.phi -= 360
elif pos.phi < -180:
pos.phi += 360
return pos
class TestUBCalculationWithWillmotStrategy_Si_5_5_12_FixedMuEta():
def setup_method(self):
hardware = Mock()
hardware.get_axes_names.return_value = ('m', 'd', 'n', 'e', 'c',
'p')
self.ubcalc = UBCalculation(hardware, SixCircle(),
UbCalculationNonPersister(),
YouUbCalcStrategy())
def testAgainstResultsFromJan_27_2010(self):
self.ubcalc.start_new('test')
self.ubcalc.set_lattice('Si_5_5_12', 7.68, 53.48, 75.63, 90, 90, 90)
self.ubcalc.add_reflection(
HKL0[0], HKL0[1], HKL0[2], willmott_to_you_fixed_mu_eta(REF0),
ENERGY, 'ref0', None)
self.ubcalc.add_reflection(
HKL1[0], HKL1[1], HKL1[2], willmott_to_you_fixed_mu_eta(REF1),
ENERGY, 'ref1', None)
self.ubcalc.calculate_UB()
print "U: ", self.ubcalc.U
print "UB: ", self.ubcalc.UB
matrixeq_(self.ubcalc.U, U_DIFFCALC)
class TestFixedMuEta(_BaseTest):
def setup_method(self):
_BaseTest.setup_method(self)
self._configure_constraints()
self.wavelength = 0.6358
B = CrystalUnderTest('xtal', 7.68, 53.48,
75.63, 90, 90, 90).B
self.UB = U_DIFFCALC * B
self._configure_limits()
def _configure_constraints(self):
self.constraints._constrained = {'alpha': 2 * TORAD, 'mu': -pi / 2,
'eta': 0}
def _configure_limits(self):
self.mock_hardware.set_lower_limit(NUNAME, None)
self.mock_hardware.set_upper_limit('delta', 90)
self.mock_hardware.set_lower_limit('mu', None)
self.mock_hardware.set_lower_limit('eta', None)
self.mock_hardware.set_lower_limit('chi', None)
def _convert_willmott_pos(self, willmott_pos):
return willmott_to_you_fixed_mu_eta(willmott_pos)
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
self._check_angles_to_hkl('', 999, 999, hkl, pos, self.wavelength)
# virtual_expected)
if fails:
self._check_hkl_to_angles_fails('', 999, 999, hkl, pos,
self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles('', 999, 999, hkl, pos, self.wavelength,
virtual_expected)
def testHkl_2_19_32_found_orientation_setting(self):
'''Check that the or0 reflection maps back to the assumed hkl'''
self.places = 2
self._check_angles_to_hkl('', 999, 999, HKL0,
self._convert_willmott_pos(REF0),
self.wavelength, {'alpha': 2})
def testHkl_0_7_22_found_orientation_setting(self):
'''Check that the or1 reflection maps back to the assumed hkl'''
self.places = 0
self._check_angles_to_hkl('', 999, 999, HKL1,
self._convert_willmott_pos(REF1),
self.wavelength, {'alpha': 2})
def testHkl_2_19_32_calculated_from_DDIF(self):
raise SkipTest() # diffcalc finds a different soln (with -ve gamma)
self.places = 3
willpos = WillPos(delta=21.974, gamma=4.419, omegah=2, phi=-33.803)
self._check((2, 19, 32),
self._convert_willmott_pos(willpos),
{'alpha': 2})
def testHkl_0_7_22_calculated_from_DDIF(self):
raise SkipTest() # diffcalc finds a different soln (with -ve gamma)
self.places = 3
willpos = WillPos(delta=11.241801854649, gamma=-3.038407637123,
omegah=2, phi=-3.436557497330)
self._check((0, 7, 22),
self._convert_willmott_pos(willpos),
{'alpha': 2})
def testHkl_2_m5_12_calculated_from_DDIF(self):
raise SkipTest() # diffcalc finds a different soln (with -ve gamma)
self.places = 3
willpos = WillPos(delta=5.224, gamma=10.415, omegah=2, phi=-1.972)
self._check((2, -5, 12),
self._convert_willmott_pos(willpos),
{'alpha': 2})
def testHkl_2_19_32_calculated_predicted_with_diffcalc_and_found(self):
willpos = WillPos(delta=21.974032376045, gamma=-4.418955754003,
omegah=2, phi=64.027358409574)
self._check((2, 19, 32),
self._convert_willmott_pos(willpos),
{'alpha': 2})
def testHkl_0_7_22_calculated_predicted_with_diffcalc_and_found(self):
willpos = WillPos(delta=11.241801854649, gamma=-3.038407637123,
omegah=2, phi=-86.563442502670)
self._check((0, 7, 22),
self._convert_willmott_pos(willpos),
{'alpha': 2})
def testHkl_2_m5_12_calculated_predicted_with_diffcalc_and_found(self):
willpos = WillPos(delta=5.223972025344, gamma=-10.415435905622,
omegah=2, phi=-90 - 102.995854571805)
self._check((2, -5, 12),
self._convert_willmott_pos(willpos),
{'alpha': 2})
###############################################################################
def willmott_to_you_fixed_mu_chi(pos):
pos = YouPos(mu=-0,
delta=pos.delta,
nu=pos.gamma,
eta=pos.omegah,
chi=90,
phi=-pos.phi)
if pos.phi > 180:
pos.phi -= 360
elif pos.phi < -180:
pos.phi += 360
return pos
class TestUBCalculationWithWillmotStrategy_Si_5_5_12_FixedMuChi():
def setup_method(self):
hardware = Mock()
names = 'm', 'd', 'n', 'e', 'c', 'p'
hardware.get_axes_names.return_value = names
self.ubcalc = UBCalculation(hardware, SixCircle(),
UbCalculationNonPersister(),
YouUbCalcStrategy())
def testAgainstResultsFromJan_27_2010(self):
self.ubcalc.start_new('test')
self.ubcalc.set_lattice('Si_5_5_12', 7.68, 53.48, 75.63, 90, 90, 90)
self.ubcalc.add_reflection(
HKL0[0], HKL0[1], HKL0[2], willmott_to_you_fixed_mu_chi(REF0),
ENERGY, 'ref0', None)
self.ubcalc.add_reflection(
HKL1[0], HKL1[1], HKL1[2], willmott_to_you_fixed_mu_chi(REF1),
ENERGY, 'ref1', None)
self.ubcalc.calculate_UB()
print "U: ", self.ubcalc.U
print "UB: ", self.ubcalc.UB
matrixeq_(self.ubcalc.U, U_DIFFCALC)
class Test_Fixed_Mu_Chi(TestFixedMuEta):
def _configure_constraints(self):
self.constraints._constrained = {'alpha': 2 * TORAD, 'mu': 0,
'chi': pi / 2}
def _convert_willmott_pos(self, willmott_pos):
return willmott_to_you_fixed_mu_chi(willmott_pos)
# Primary and secondary reflections found with the help of DDIF on Diamond's
# i07 on Jan 28/29 2010
Pt531_HKL0 = -1.000, 1.000, 6.0000
Pt531_REF0 = WillPos(delta=9.3971025, gamma=-16.1812303, omegah=2,
phi=108.5510712)
Pt531_HKL1 = -2.000, -1.000, 7.0000
Pt531_REF1 = WillPos(delta=11.0126958, gamma=-11.8636128, omegah=2,
phi=40.3803393)
Pt531_HKL2 = 1, 1, 9
Pt531_REF2 = WillPos(delta=14.1881617, gamma=-7.7585939, omegah=2,
phi=176.5348540)
Pt531_WAVELENGTH = 0.6358
# This is U matrix displayed by DDIF
U_FROM_DDIF = matrix([[-0.00312594, -0.00063417, 0.99999491],
[0.99999229, -0.00237817, 0.00312443],
[0.00237618, 0.99999697, 0.00064159]])
# This is the version that Diffcalc comes up with ( see following test)
Pt531_U_DIFFCALC = matrix([[-0.0023763, -0.9999970, -0.0006416],
[0.9999923, -0.0023783, 0.0031244],
[-0.0031259, -0.0006342, 0.9999949]])
class TestUBCalculationWithYouStrategy_Pt531_FixedMuChi():
def setup_method(self):
hardware = Mock()
names = 'm', 'd', 'n', 'e', 'c', 'p'
hardware.get_axes_names.return_value = names
self.ubcalc = UBCalculation(hardware, SixCircle(),
UbCalculationNonPersister(),
YouUbCalcStrategy())
def testAgainstResultsFromJan_28_2010(self):
self.ubcalc.start_new('test')
self.ubcalc.set_lattice('Pt531', 6.204, 4.806, 23.215, 90, 90, 49.8)
self.ubcalc.add_reflection(Pt531_HKL0[0], Pt531_HKL0[1], Pt531_HKL0[2],
willmott_to_you_fixed_mu_chi(Pt531_REF0),
12.39842 / Pt531_WAVELENGTH,
'ref0', None)
self.ubcalc.add_reflection(Pt531_HKL1[0], Pt531_HKL1[1], Pt531_HKL1[2],
willmott_to_you_fixed_mu_chi(Pt531_REF1),
12.39842 / Pt531_WAVELENGTH,
'ref1', None)
self.ubcalc.calculate_UB()
print "U: ", self.ubcalc.U
print "UB: ", self.ubcalc.UB
matrixeq_(self.ubcalc.U, Pt531_U_DIFFCALC)
class Test_Pt531_FixedMuChi(_BaseTest):
def setup_method(self):
_BaseTest.setup_method(self)
self._configure_constraints()
self.wavelength = Pt531_WAVELENGTH
CUT = CrystalUnderTest('Pt531', 6.204, 4.806, 23.215, 90, 90, 49.8)
B = CUT.B
self.UB = Pt531_U_DIFFCALC * B
self._configure_limits()
def _configure_constraints(self):
self.constraints._constrained = {'alpha': 2 * TORAD, 'mu': 0,
'chi': pi / 2}
def _configure_limits(self):
self.mock_hardware.set_lower_limit(NUNAME, None)
#self.mock_hardware.set_lower_limit('delta', None)
self.mock_hardware.set_upper_limit('delta', 90)
self.mock_hardware.set_lower_limit('mu', None)
self.mock_hardware.set_lower_limit('eta', None)
self.mock_hardware.set_lower_limit('chi', None)
def _convert_willmott_pos(self, willmott_pos):
return willmott_to_you_fixed_mu_chi(willmott_pos)
def _configure_ub(self):
self.mock_ubcalc.UB = self.UB
def _check(self, hkl, pos, virtual_expected={}, fails=False):
# self._check_angles_to_hkl('', 999, 999, hkl, pos, self.wavelength,
# virtual_expected)
if fails:
self._check_hkl_to_angles_fails('', 999, 999, hkl, pos,
self.wavelength, virtual_expected)
else:
self._check_hkl_to_angles('', 999, 999, hkl, pos, self.wavelength,
virtual_expected)
def testHkl_0_found_orientation_setting(self):
'''Check that the or0 reflection maps back to the assumed hkl'''
self.places = 1
self._check_angles_to_hkl('', 999, 999, Pt531_HKL0,
self._convert_willmott_pos(Pt531_REF0),
self.wavelength, {'alpha': 2})
def testHkl_1_found_orientation_setting(self):
'''Check that the or1 reflection maps back to the assumed hkl'''
self.places = 0
self._check_angles_to_hkl('', 999, 999, Pt531_HKL1,
self._convert_willmott_pos(Pt531_REF1),
self.wavelength, {'alpha': 2})
def testHkl_0_calculated_from_DDIF(self):
self.places = 7
pos_expected = self._convert_willmott_pos(Pt531_REF0)
self._check(Pt531_HKL0,
pos_expected,
{'alpha': 2})
def testHkl_1_calculated_from_DDIF(self):
self.places = 7
self._check(Pt531_HKL1,
self._convert_willmott_pos(Pt531_REF1),
{'alpha': 2})
def testHkl_2_calculated_from_DDIF(self):
self.places = 7
self._check(Pt531_HKL2,
self._convert_willmott_pos(Pt531_REF2),
{'alpha': 2})
def testHkl_2_m1_0_16(self):
self.places = 7
pos = WillPos(delta=25.7990976, gamma=-6.2413545, omegah=2,
phi=47.4624380)
# pos.phi -= 360
self._check((-1, 0, 16),
self._convert_willmott_pos(pos),
{'alpha': 2})
class Test_Pt531_Fixed_Mu_eta_(Test_Pt531_FixedMuChi):
def _configure_constraints(self):
self.constraints._constrained = {'alpha': 2 * TORAD, 'mu': -pi / 2,
'eta': 0}
def _convert_willmott_pos(self, willmott_pos):
return willmott_to_you_fixed_mu_eta(willmott_pos)

View File

@@ -0,0 +1,575 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
from nose.tools import eq_ # @UnresolvedImport
from mock import Mock
from diffcalc.hkl.you.constraints import YouConstraintManager
from diffcalc.util import DiffcalcException
from nose.tools import raises
from nose.tools import assert_raises # @UnresolvedImport
from diffcalc.hkl.you.constraints import NUNAME
import diffcalc.util
def joined(d1, d2):
d1.update(d2)
return d1
class TestConstraintManager:
def setup_method(self):
diffcalc.util.COLOURISE_TERMINAL_OUTPUT = False
self.hardware_monitor = Mock()
self.hardware_monitor.get_position.return_value = (1.,) * 6
self.hardware_monitor.get_axes_names.return_value = [
'mu', 'delta', NUNAME, 'eta', 'chi', 'phi']
self.cm = YouConstraintManager(self.hardware_monitor)
def test_init(self):
eq_(self.cm.all, {})
eq_(self.cm.detector, {})
eq_(self.cm.reference, {})
eq_(self.cm.sample, {})
eq_(self.cm.naz, {})
def test_build_display_table(self):
self.cm.constrain('qaz')
self.cm.constrain('alpha')
self.cm.constrain('eta')
self.cm.set_constraint('qaz', 1.234)
self.cm.set_constraint('eta', 99.)
print '\n'.join(self.cm.build_display_table_lines())
eq_(self.cm.build_display_table_lines(),
[' DET REF SAMP',
' ------ ------ ------',
' delta a_eq_b mu',
' %s o-> alpha --> eta' % NUNAME.ljust(6),
'--> qaz beta chi',
' naz psi phi',
' mu_is_%s' % NUNAME])
#"""
# DET REF SAMP Available:
# ====== ====== ======
# delta a_eq_b mu 3x samp: 80 of 80
# nu o-> alpha --> eta 2x samp and ref: chi & phi
#--> qaz beta chi mu & eta
# naz psi phi chi=90 & mu=0
# mu_is_nu 2x samp and det: 0 of 6
# 3x samp: 0 of 4
#"""[1:-1]
def test_unconstrain_okay(self):
eq_(self.cm.all, {})
self.cm.constrain('delta')
self.cm.constrain('mu')
eq_(self.cm.all, {'delta': None, 'mu': None})
eq_(self.cm.unconstrain('delta'), None)
eq_(self.cm.all, {'mu': None})
def test_clear_constraints(self):
self.cm.constrain('delta')
self.cm.constrain('mu')
self.cm.clear_constraints()
eq_(self.cm.all, {})
def test_unconstrain_bad(self):
eq_(self.cm.all, {})
eq_(self.cm.unconstrain('delta'), "Delta was not already constrained.")
def test_constrain_det(self, pre={}):
eq_(self.cm.all, pre)
eq_(self.cm.constrain('delta'), None)
eq_(self.cm.all, joined({'delta': None}, pre))
eq_(self.cm.constrain('delta'), 'Delta is already constrained.')
eq_(self.cm.all, joined({'delta': None}, pre))
eq_(self.cm.constrain('naz'), 'Delta constraint replaced.')
eq_(self.cm.all, joined({'naz': None}, pre))
eq_(self.cm.constrain('delta'), 'Naz constraint replaced.')
eq_(self.cm.all, joined({'delta': None}, pre))
def test_constrain_det_one_preexisting_ref(self):
self.cm.constrain('alpha')
self.test_constrain_det({'alpha': None})
def test_constrain_det_one_preexisting_samp(self):
self.cm.constrain('phi')
self.test_constrain_det({'phi': None})
def test_constrain_det_one_preexisting_samp_and_ref(self):
self.cm.constrain('alpha')
self.cm.constrain('phi')
self.test_constrain_det({'alpha': None, 'phi': None})
def test_constrain_det_two_preexisting_samp(self):
self.cm.constrain('chi')
self.cm.constrain('phi')
self.test_constrain_det({'chi': None, 'phi': None})
def test_constrain_det_three_preexisting_other(self):
self.cm.constrain('alpha')
self.cm.constrain('phi')
self.cm.constrain('chi')
try:
self.cm.constrain('delta')
assert False
except DiffcalcException, e:
eq_(e.args[0], (
"Delta could not be constrained. First un-constrain one of the"
"\nangles alpha, chi or phi (with 'uncon')"))
def test_constrain_det_three_preexisting_samp(self):
self.cm.constrain('phi')
self.cm.constrain('chi')
self.cm.constrain('eta')
try:
self.cm.constrain('delta')
assert False
except DiffcalcException, e:
eq_(e.args[0],
"Delta could not be constrained. First un-constrain one of the"
"\nangles eta, chi or phi (with 'uncon')")
def test_constrain_ref(self, pre={}):
eq_(self.cm.all, pre)
eq_(self.cm.constrain('alpha'), None)
eq_(self.cm.all, joined({'alpha': None}, pre))
eq_(self.cm.constrain('alpha'), 'Alpha is already constrained.')
eq_(self.cm.all, joined({'alpha': None}, pre))
eq_(self.cm.constrain('beta'), 'Alpha constraint replaced.')
eq_(self.cm.all, joined({'beta': None}, pre))
def test_constrain_ref_one_preexisting_det(self):
self.cm.constrain('delta')
self.test_constrain_ref({'delta': None})
def test_constrain_ref_one_preexisting_samp(self):
self.cm.constrain('phi')
self.test_constrain_ref({'phi': None})
def test_constrain_ref_one_preexisting_samp_and_det(self):
self.cm.constrain('delta')
self.cm.constrain('phi')
self.test_constrain_ref({'delta': None, 'phi': None})
def test_constrain_ref_two_preexisting_samp(self):
self.cm.constrain('chi')
self.cm.constrain('phi')
self.test_constrain_ref({'chi': None, 'phi': None})
def test_constrain_ref_three_preexisting_other(self):
self.cm.constrain('delta')
self.cm.constrain('phi')
self.cm.constrain('chi')
try:
self.cm.constrain('alpha'),
assert False
except DiffcalcException, e:
eq_(e.args[0],
"Alpha could not be constrained. First un-constrain one of the"
"\nangles delta, chi or phi (with 'uncon')")
def test_constrain_ref_three_preexisting_samp(self):
self.cm.constrain('phi')
self.cm.constrain('chi')
self.cm.constrain('eta')
try:
self.cm.constrain('delta')
assert False
except DiffcalcException, e:
eq_(e.args[0],
"Delta could not be constrained. First un-constrain one of the"
"\nangles eta, chi or phi (with 'uncon')")
def test_constrain_samp_when_one_free(self, pre={}):
eq_(self.cm.all, pre)
eq_(self.cm.constrain('phi'), None)
eq_(self.cm.all, joined({'phi': None}, pre))
eq_(self.cm.constrain('phi'), 'Phi is already constrained.')
eq_(self.cm.all, joined({'phi': None}, pre))
def test_constrain_samp_one_preexisting_samp(self):
self.cm.constrain('chi')
self.test_constrain_samp_when_one_free({'chi': None})
def test_constrain_samp_two_preexisting_samp(self):
self.cm.constrain('chi')
self.cm.constrain('eta')
self.test_constrain_samp_when_one_free({'chi': None, 'eta': None})
def test_constrain_samp_two_preexisting_other(self):
self.cm.constrain('delta')
self.cm.constrain('alpha')
self.test_constrain_samp_when_one_free({'delta': None, 'alpha': None})
def test_constrain_samp_two_preexisting_one_det(self):
self.cm.constrain('delta')
self.cm.constrain('eta')
self.test_constrain_samp_when_one_free({'delta': None, 'eta': None})
def test_constrain_samp_two_preexisting_one_ref(self):
self.cm.constrain('alpha')
self.cm.constrain('eta')
self.test_constrain_samp_when_one_free({'alpha': None, 'eta': None})
def test_constrain_samp_three_preexisting_only_one_samp(self):
self.cm.constrain('delta')
self.cm.constrain('alpha')
self.cm.constrain('eta')
eq_(self.cm.constrain('phi'), 'Eta constraint replaced.')
eq_(self.cm.all, {'delta': None, 'alpha': None, 'phi': None})
eq_(self.cm.constrain('phi'), 'Phi is already constrained.')
eq_(self.cm.all, {'delta': None, 'alpha': None, 'phi': None})
def test_constrain_samp_three_preexisting_two_samp_one_det(self):
self.cm.constrain('delta')
self.cm.constrain('eta')
self.cm.constrain('chi')
try:
self.cm.constrain('phi')
assert False
except DiffcalcException, e:
eq_(e.args[0],
"Phi could not be constrained. First un-constrain one of the"
"\nangles delta, eta or chi (with 'uncon')")
def test_constrain_samp_three_preexisting_two_samp_one_ref(self):
self.cm.constrain('alpha')
self.cm.constrain('eta')
self.cm.constrain('chi')
try:
self.cm.constrain('phi')
assert False
except DiffcalcException, e:
eq_(e.args[0],
"Phi could not be constrained. First un-constrain one of the"
"\nangles alpha, eta or chi (with 'uncon')")
def test_constrain_samp_three_preexisting_samp(self):
self.cm.constrain('mu')
self.cm.constrain('eta')
self.cm.constrain('chi')
try:
self.cm.constrain('phi')
assert False
except DiffcalcException, e:
eq_(e.args[0],
"Phi could not be constrained. First un-constrain one of the"
"\nangles mu, eta or chi (with 'uncon')")
def test_report_constraints_none(self):
eq_(self.cm.report_constraints_lines(),
['! 3 more constraints required'])
def test_report_constraints_one_with_value(self):
self.cm.constrain(NUNAME)
self.cm.set_constraint(NUNAME, 9.12343)
eq_(self.cm.report_constraints_lines(),
['! 2 more constraints required',
' %s : 9.1234' % NUNAME])
def test_report_constraints_one_with_novalue(self):
self.cm.constrain(NUNAME)
print '! 2 more constraints required\n! %s: ---' % NUNAME
eq_(self.cm.report_constraints_lines(),
['! 2 more constraints required',
'! %s : ---' % NUNAME])
def test_report_constraints_one_with_valueless(self):
self.cm.constrain('a_eq_b')
eq_(self.cm.report_constraints_lines(),
['! 2 more constraints required',
' a_eq_b'])
def test_report_constraints_one_with_two(self):
self.cm.constrain('naz')
self.cm.set_constraint('naz', 9.12343)
self.cm.constrain('a_eq_b')
eq_(self.cm.report_constraints_lines(),
['! 1 more constraint required',
' naz : 9.1234',
' a_eq_b'])
def test_report_constraints_one_with_three(self):
self.cm.constrain('naz')
self.cm.set_constraint('naz', 9.12343)
self.cm.constrain('a_eq_b')
self.cm.constrain('mu')
self.cm.set_constraint('mu', 9.12343)
eq_(self.cm.report_constraints_lines(),
[' naz : 9.1234',
' a_eq_b',
' mu : 9.1234'])
def _constrain(self, *args):
for con in args:
self.cm.constrain(con)
@raises(ValueError)
def test_is_implemented_invalid(self):
self._constrain('naz')
self.cm.is_current_mode_implemented()
# 1 samp
def test_is_implemented_1_samp_naz(self):
self._constrain('naz', 'alpha', 'mu')
eq_(self.cm.is_current_mode_implemented(), True)
def test_is_implemented_1_samp_det(self):
self._constrain('qaz', 'alpha', 'mu')
eq_(self.cm.is_current_mode_implemented(), True)
# 2 samp + ref
def test_is_implemented_2_samp_ref_mu_chi(self):
self._constrain('beta', 'mu', 'chi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_ref_mu90_chi0(self):
self._constrain('beta', 'mu', 'chi')
self.cm.set_constraint('mu', 0)
self.cm.set_constraint('chi', 90)
eq_(self.cm.is_current_mode_implemented(), True)
def test_is_implemented_2_samp_ref_mu_eta(self):
self._constrain('beta', 'mu', 'eta')
eq_(self.cm.is_current_mode_implemented(), True)
def test_is_implemented_2_samp_ref_mu_phi(self):
self._constrain('beta', 'mu', 'phi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_ref_eta_chi(self):
self._constrain('beta', 'eta', 'chi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_ref_eta_phi(self):
self._constrain('beta', 'eta', 'phi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_ref_chi_phi(self):
self._constrain('beta', 'chi', 'phi')
eq_(self.cm.is_current_mode_implemented(), True)
# 2 samp + det
def test_is_implemented_2_samp_det_mu_chi(self):
self._constrain('qaz', 'mu', 'chi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_det_mu_eta(self):
self._constrain('qaz', 'mu', 'eta')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_det_mu_phi(self):
self._constrain('qaz', 'mu', 'phi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_det_eta_chi(self):
self._constrain('qaz', 'eta', 'chi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_det_eta_phi(self):
self._constrain('qaz', 'eta', 'phi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_2_samp_det_chi_phi(self):
self._constrain('qaz', 'chi', 'phi')
eq_(self.cm.is_current_mode_implemented(), False)
# 3 samp
def test_is_implemented_3_samp_no_mu(self):
self._constrain('eta', 'chi', 'phi')
eq_(self.cm.is_current_mode_implemented(), True)
def test_is_implemented_3_samp_no_eta(self):
self._constrain('mu', 'chi', 'phi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_3_samp_no_chi(self):
self._constrain('mu', 'eta', 'phi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_is_implemented_3_samp_no_phi(self):
self._constrain('mu', 'eta', 'chi')
eq_(self.cm.is_current_mode_implemented(), False)
def test_set_fails(self):
try:
self.cm.set_constraint('not_a_constraint', object())
assert False
except DiffcalcException, e:
eq_(e.args[0], "Could not set not_a_constraint. This is not an "
"available constraint.")
try:
self.cm.set_constraint('delta', object())
assert False
except DiffcalcException, e:
eq_(e.args[0],
"Could not set delta. This is not currently constrained.")
self.cm.constrain('a_eq_b')
try:
self.cm.set_constraint('a_eq_b', object())
assert False
except DiffcalcException, e:
eq_(e.args[0],
"Could not set a_eq_b. This constraint takes no value.")
# self.cm.constrain('delta')
# self.cm.track('delta')
# try:
# self.cm.set('delta', object())
# assert False
# except DiffcalcException, e:
# eq_(e.args[0], ("Could not set delta as this constraint is "
# "configured to track its associated\n"
# "physical angle. First remove this tracking "
# "(use 'untrack delta')."))
def test_set(self):
#"%s: %s --> %f %s"
self.cm.constrain('alpha')
eq_(self.cm.set_constraint('alpha', 1.), 'alpha : --- --> 1.0')
eq_(self.cm.set_constraint('alpha', 2.), 'alpha : 1.0 --> 2.0')
# def test_track_fails(self):
# try:
# self.cm.track('not_a_constraint')
# assert False
# except DiffcalcException, e:
# eq_(e.args[0], "Could not track not_a_constraint as this is not "
# "an available constraint.")
#
# try:
# self.cm.track('delta')
# assert False
# except DiffcalcException, e:
# eq_(e.args[0],
# "Could not track delta as this is not currently constrained.")
#
# self.cm.constrain('a_eq_b')
# try:
# self.cm.track('a_eq_b')
# assert False
# except DiffcalcException, e:
# eq_(e.args[0],
# "Could not track a_eq_b as this constraint takes no value.")
#
# self.cm.constrain('alpha')
# try:
# self.cm.track('alpha')
# assert False
# except DiffcalcException, e:
# eq_(e.args[0], ("Could not configure alpha to track as this "
# "constraint is not associated with a\n"
# "physical angle."))
#
# def test_track(self):
# #"%s: %s --> %f %s"
# self.cm.constrain('delta')
# eq_(self.cm.track('delta'), 'delta : --- ~~> 1.0 (tracking)')
# eq_(self.cm.track('delta'), 'Delta was already configured to track.')
# self.cm.untrack('delta')
# self.cm.set_constraint('delta', 2.)
# eq_(self.cm.track('delta'), 'delta : 2.0 ~~> 1.0 (tracking)')
class TestConstraintManagerWithFourCircles:
def setup_method(self):
self.cm = YouConstraintManager(None, {NUNAME: 0, 'mu': 0})
def test_init(self):
eq_(self.cm.all, {NUNAME: 0, 'mu': 0})
eq_(self.cm.detector, {NUNAME: 0})
eq_(self.cm.reference, {})
eq_(self.cm.sample, {'mu': 0})
eq_(self.cm.naz, {})
def test_build_initial_display_table_with_fixed_detector(self):
self.cm = YouConstraintManager(None, {NUNAME: 0})
print self.cm.build_display_table_lines()
eq_(self.cm.build_display_table_lines(),
[' REF SAMP',
' ------ ------',
' a_eq_b mu',
' alpha eta',
' beta chi',
' psi phi'])
def test_build_initial_display_table_with_fixed_sample(self):
self.cm = YouConstraintManager(None, {'mu': 0})
print self.cm.build_display_table_lines()
eq_(self.cm.build_display_table_lines(),
[' DET REF SAMP',
' ------ ------ ------',
' delta a_eq_b eta',
' %s alpha chi' % NUNAME.ljust(6),
' qaz beta phi',
' naz psi'])
def test_build_initial_display_table_for_four_circle(self):
self.cm = YouConstraintManager(None, {'mu': 0, NUNAME: 0})
print self.cm.build_display_table_lines()
eq_(self.cm.build_display_table_lines(),
[' REF SAMP',
' ------ ------',
' a_eq_b eta',
' alpha chi',
' beta phi',
' psi'])
def test_constrain_fixed_detector_angle(self):
assert_raises(DiffcalcException, self.cm.constrain, 'delta')
assert_raises(DiffcalcException, self.cm.constrain, NUNAME)
assert_raises(DiffcalcException, self.cm.constrain, 'naz')
assert_raises(DiffcalcException, self.cm.constrain, 'qaz')
def test_unconstrain_fixed_detector_angle(self):
assert_raises(DiffcalcException, self.cm.unconstrain, 'delta')
assert_raises(DiffcalcException, self.cm.unconstrain, NUNAME)
assert_raises(DiffcalcException, self.cm.unconstrain, 'naz')
assert_raises(DiffcalcException, self.cm.unconstrain, 'qaz')
def test_set_constrain_fixed_detector_angle(self):
assert_raises(DiffcalcException, self.cm.set_constraint, 'delta', 0)
assert_raises(DiffcalcException, self.cm.set_constraint, NUNAME, 0)
assert_raises(DiffcalcException, self.cm.set_constraint, 'naz', 0)
assert_raises(DiffcalcException, self.cm.set_constraint, 'qaz', 0)
@raises(DiffcalcException)
def test_constrain_fixed_sample_angle(self):
self.cm.constrain('mu')
@raises(DiffcalcException)
def test_unconstrain_fixed_sample_angle(self):
self.cm.unconstrain('mu')
@raises(DiffcalcException)
def test_set_constrain_fixed_sample_angle(self):
self.cm.set_constraint('mu', 0)

View File

@@ -0,0 +1,95 @@
###
# Copyright 2008-2011 Diamond Light Source Ltd.
# This file is part of Diffcalc.
#
# Diffcalc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diffcalc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diffcalc. If not, see <http://www.gnu.org/licenses/>.
###
from mock import Mock, call
from diffcalc import settings
import diffcalc
diffcalc.util.DEBUG = True
hkl = None
def setup_module():
global hkl
settings.hardware=Mock()
settings.geometry=Mock()
settings.angles_to_hkl_function=Mock()
settings.ubcalc_strategy=Mock()
settings.geometry.fixed_constraints = {}
from diffcalc.hkl.you import hkl
reload(hkl)
hkl.hklcalc = Mock()
hkl.hklcalc.constraints.report_constraints_lines.return_value = ['report1', 'report2']
def test_con_with_1_constraint():
hkl.con('cona')
hkl.hklcalc.constraints.constrain.assert_called_with('cona')
def test_con_with_1_constraint_with_value():
hkl.con('cona', 123)
hkl.hklcalc.constraints.constrain.assert_called_with('cona')
hkl.hklcalc.constraints.set_constraint.assert_called_with('cona', 123)
def test_con_with_3_constraints():
hkl.con('cona', 'conb', 'conc')
hkl.hklcalc.constraints.clear_constraints.assert_called()
calls = [call('cona'), call('conb'), call('conc')]
hkl.hklcalc.constraints.constrain.assert_has_calls(calls)
def test_con_with_3_constraints_first_val():
hkl.con('cona', 1, 'conb', 'conc')
hkl.hklcalc.constraints.clear_constraints.assert_called()
calls = [call('cona'), call('conb'), call('conc')]
hkl.hklcalc.constraints.constrain.assert_has_calls(calls)
hkl.hklcalc.constraints.set_constraint.assert_called_with('cona', 1)
def test_con_with_3_constraints_second_val():
hkl.con('cona', 'conb', 2, 'conc')
hkl.hklcalc.constraints.clear_constraints.assert_called()
calls = [call('cona'), call('conb'), call('conc')]
hkl.hklcalc.constraints.constrain.assert_has_calls(calls)
hkl.hklcalc.constraints.set_constraint.assert_called_with('conb', 2)
def test_con_with_3_constraints_third_val():
hkl.con('cona', 'conb', 'conc', 3)
hkl.hklcalc.constraints.clear_constraints.assert_called()
calls = [call('cona'), call('conb'), call('conc')]
hkl.hklcalc.constraints.constrain.assert_has_calls(calls)
hkl.hklcalc.constraints.set_constraint.assert_called_with('conc', 3)
def test_con_with_3_constraints_all_vals():
hkl.con('cona', 1, 'conb', 2, 'conc', 3)
hkl.hklcalc.constraints.clear_constraints.assert_called()
calls = [call('cona'), call('conb'), call('conc')]
hkl.hklcalc.constraints.constrain.assert_has_calls(calls)
calls = [call('cona', 1), call('conb', 2), call('conc', 3)]
hkl.hklcalc.constraints.set_constraint.assert_has_calls(calls)
def test_con_messages_and_help_visually():
hkl.con()
print "**"
print hkl.con.__doc__
def test_con_message_display_whenn_selecting_an_unimplmented_mode():
hkl.hklcalc.constraints.is_fully_constrained.return_value = True
hkl.hklcalc.constraints.is_current_mode_implemented.return_value = False
hkl.con('phi', 'chi', 'eta')