def fit_crystal(uc, refl_list): try: uc_system, uc_params = uc.get_lattice_params() start = uc_params lower = [ 0, ] * len(uc_params) upper, sigma = _get_uc_upper_limits(uc_system) except AttributeError: raise DiffcalcException( "UB matrix not initialised. Cannot run UB matrix fitting procedure." ) try: from org.apache.commons.math3.optim.nonlinear.scalar.noderiv import CMAESOptimizer from org.apache.commons.math3.optim.nonlinear.scalar import GoalType from org.apache.commons.math3.optim import MaxEval, InitialGuess, SimpleBounds from org.apache.commons.math3.random import MersenneTwister optimizer = CMAESOptimizer(30000, 0, True, 10, 0, MersenneTwister(), True, None) opt = optimizer.optimize( (MaxEval(5000), get_crystal_target(refl_list, uc_system), GoalType.MINIMIZE, CMAESOptimizer.PopulationSize(15), CMAESOptimizer.Sigma(sigma), InitialGuess(start), SimpleBounds(lower, upper))) vals = opt.getPoint() #res = opt.getValue() except ImportError: from scipy.optimize import minimize ref_data = _get_refl_hkl(refl_list) bounds = zip(lower, upper) res = minimize(_func_crystal, start, args=(uc_system, ref_data), method='SLSQP', tol=1e-10, options={ 'disp': False, 'maxiter': 10000, 'eps': 1e-6, 'ftol': 1e-10 }, bounds=bounds) vals = res.x res_cr = CrystalUnderTest('trial', uc_system, 1, 1, 1, 90, 90, 90) res_cr._set_cell_for_system(uc_system, *vals) return res_cr
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
def _func_crystal(vals, uc_system, ref_data): trial_cr = CrystalUnderTest('trial', uc_system, 1, 1, 1, 90, 90, 90) try: trial_cr._set_cell_for_system(uc_system, *vals) except Exception: return 1e6 res = 0 I = matrix('1 0 0; 0 1 0; 0 0 1') for (hkl_vals, pos_vals, en) in ref_data: wl = 12.3984 / en [_, DELTA, NU, _, _, _] = create_you_matrices(*pos_vals.totuple()) q_pos = (NU * DELTA - I) * matrix([[0], [2 * pi / wl], [0]]) q_hkl = trial_cr.B * hkl_vals res += (norm(q_pos) - norm(q_hkl))**2 return res
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 decode_ubcalcstate(state, geometry, diffractometer_axes_names, multiplier): # Backwards compatibility code orientlist_=OrientationList(geometry, diffractometer_axes_names, []) try: orientlist_=decode_orientlist(state['orientlist'], geometry, diffractometer_axes_names) except KeyError: pass try: surface_=decode_reference(state['surface'], settings.surface_vector, False) except KeyError: surface_ = YouReference(None) surface_._set_n_phi_configured(settings.surface_vector) return UBCalcState( name=state['name'], crystal=state['crystal'] and CrystalUnderTest(*eval(state['crystal'])), reflist=decode_reflist(state['reflist'], geometry, diffractometer_axes_names, multiplier), orientlist=orientlist_, tau=state['tau'], sigma=state['sigma'], manual_U=state['u'] and decode_matrix(state['u']), manual_UB=state['ub'] and decode_matrix(state['ub']), or0=state['or0'], or1=state['or1'], reference=decode_reference(state.get('reference', None), settings.reference_vector, True), surface=surface_ )
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 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 _set_lattice(self, name, a, b, c, alpha, beta, gamma): """set lattice parameters in degrees""" if self._state.name is None: raise DiffcalcException( "Cannot set lattice until a UBCalcaluation has been started " "with newubcalc") self._state.crystal = CrystalUnderTest(name, a, b, c, alpha, beta, gamma) # Clear U and UB if these exist if self._U is not None: # (UB will also exist) print "Warning: the old UB calculation has been cleared." print " Use 'calcub' to recalculate with old reflections."
def testGetBMatrix(self): # Check the calculated B Matrix for sess in scenarios.sessions(): if sess.bmatrix is None: continue cut = CrystalUnderTest('tc', *sess.lattice) desired = matrix(sess.bmatrix) print desired.tolist() answer = cut.B print answer.tolist() note = "Incorrect B matrix calculation for scenario " + sess.name mneq_(answer, desired, 4, note=note)
def decode_ubcalcstate(state, geometry, diffractometer_axes_names): return UBCalcState( name=state['name'], crystal=state['crystal'] and CrystalUnderTest(*eval(state['crystal'])), reflist=decode_reflist(state['reflist'], geometry, diffractometer_axes_names), tau=state['tau'], sigma=state['sigma'], manual_U=state['u'] and decode_matrix(state['u']), manual_UB=state['ub'] and decode_matrix(state['ub']), or0=state['or0'], or1=state['or1'], reference=decode_reference(state.get('reference', None)) )
def set_lattice(self, name, *shortform): """ Converts a list shortform crystal parameter specification to a six-long tuple. See setlat() for a description of the shortforms supported. """ if not shortform: raise TypeError("Please specify unit cell parameters.") elif allnum(shortform): sf = shortform if len(sf) == 1: system = "Cubic" elif len(sf) == 2: system = "Tetragonal" elif len(sf) == 3: system = "Orthorhombic" elif len(sf) == 4: if abs(sf[0] - sf[1]) < SMALL and sf[3] == 120: system = "Hexagonal" else: system = "Monoclinic" elif len(sf) == 6: system = "Triclinic" else: raise TypeError( "Invalid number of input parameters to set unit lattice.") fullform = (system, ) + shortform else: if not isinstance(shortform[0], basestring): raise TypeError("Invalid unit cell parameters specified.") fullform = shortform if self._state.name is None: raise DiffcalcException( "Cannot set lattice until a UBCalcaluation has been started " "with newubcalc") self._state.crystal = CrystalUnderTest(name, *fullform) # Clear U and UB if these exist if self._U is not None: # (UB will also exist) print( "Warning: Setting new unit cell parameters.\n" " The old UB calculation has been cleared.") self.save()
def decode_ubcalcstate(state, geometry, diffractometer_axes_names): # Backwards compatibility code orientlist_ = OrientationList([]) try: orientlist_ = decode_orientlist(state['orientlist']) except KeyError: pass return UBCalcState(name=state['name'], crystal=state['crystal'] and CrystalUnderTest(*eval(state['crystal'])), reflist=decode_reflist(state['reflist'], geometry, diffractometer_axes_names), orientlist=orientlist_, tau=state['tau'], sigma=state['sigma'], manual_U=state['u'] and decode_matrix(state['u']), manual_UB=state['ub'] and decode_matrix(state['ub']), or0=state['or0'], or1=state['or1'], reference=decode_reference(state.get('reference', None)))
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 setCrystal(self, name, a, b, c, alpha, beta, gamma): self.cut = CrystalUnderTest(name, a, b, c, alpha, beta, gamma) self.calcUB()
class SimulatedCrystalCounter(PseudoDevice): def __init__(self, name, diffractometerScannable, geometryPlugin, wavelengthScannable, equation=Gaussian(.01), engine='you'): self.setName(name) self.setInputNames([name + '_count']) self.setOutputFormat(['%7.5f']) self.exposureTime = 1 self.pause = True self.diffractometerScannable = diffractometerScannable self.geometry = geometryPlugin self.wavelengthScannable = wavelengthScannable self.equation = equation self.engine = engine self.cut = None self.UB = None self.chiMissmount = 0. self.phiMissmount = 0. self.setCrystal('cubic', 1, 1, 1, 90, 90, 90) def setCrystal(self, name, a, b, c, alpha, beta, gamma): self.cut = CrystalUnderTest(name, a, b, c, alpha, beta, gamma) self.calcUB() def setChiMissmount(self, chi): self.chiMissmount = chi self.calcUB() def setPhiMissmount(self, phi): self.phiMissmount = phi self.calcUB() def calcUB(self): CHI = calcCHI(self.chiMissmount * TORAD) PHI = calcPHI(self.phiMissmount * TORAD) self.UB = CHI * PHI * self.cut.B def asynchronousMoveTo(self, exposureTime): self.exposureTime = exposureTime if self.pause: time.sleep(exposureTime) # Should not technically block! def getPosition(self): h, k, l = self.getHkl() dh, dk, dl = h - round(h), k - round(k), l - round(l) count = self.equation(dh, dk, dl) #return self.exposureTime, count*self.exposureTime return count * self.exposureTime def getHkl(self): pos = self.geometry.physical_angles_to_internal_position( self.diffractometerScannable.getPosition()) pos.changeToRadians() wavelength = self.wavelengthScannable.getPosition() if self.engine.lower() == 'vlieg': return vliegAnglesToHkl(pos, wavelength, self.UB) elif self.engine.lower() == 'you': return youAnglesToHkl(pos, wavelength, self.UB) else: raise ValueError(self.engine) def isBusy(self): return False def __str__(self): return self.__repr__() def __repr__(self): s = 'simulated crystal detector: %s\n' % self.getName() h, k, l = self.getHkl() s += ' h : %f\n' % h s += ' k : %f\n' % k s += ' l : %f\n' % l s += self.cut.__str__() + '\n' s += "chi orientation: %s\n" % self.chiMissmount s += "phi orientation: %s\n" % self.phiMissmount ub = self.UB.tolist() s += "UB:\n" s += " % 18.13f% 18.13f% 18.12f\n" % (ub[0][0], ub[0][1], ub[0][2]) s += " % 18.13f% 18.13f% 18.12f\n" % (ub[1][0], ub[1][1], ub[1][2]) s += " % 18.13f% 18.13f% 18.12f\n" % (ub[2][0], ub[2][1], ub[2][2]) return s
def test__str__(self): cut = CrystalUnderTest("HCl", 1, 2, 3, 4, 5, 6) print cut.__str__()