def __trig_param_array(som, param, trig_func): """ This private function applies a trigonometric function to a given parameter obtained from the supplied object. @param som: The object containing the requested information. @type som: C{SOM.SOM} @param param: The name of the parameter to seek. @type param: C{string} @param trig_func: The name of the trigonometric function to apply. @type trig_func: C{string} @return: An array of trigonometry applied values from parameters from the incoming object. @rtype: C{list} """ import math len_som = hlr_utils.get_length(som) plist = [] inst = som.attr_list.instrument tfunc = math.__getattribute__(trig_func) for i in xrange(len_som): plist.append(tfunc(hlr_utils.get_parameter(param, som[i], inst)[0])) return plist
def calc_BSS_solid_angle(map_so, inst): """ This function calculates the solid angle for a given BSS detector pixel @param map_so: The object containing the pixel ID @type map_so: C{SOM.SO} @param inst: The object containing the instrument geometry @type inst: C{SOM.Instrument} or C{SOM.CompositeInstrument} @return: The solid angle for the given pixel @rtype: C{float} """ # Get polar angle from instrument information angle_tuple = hlr_utils.get_parameter("polar", map_so, inst) angle = angle_tuple[0] # Get the detector pixel height dh_tuple = hlr_utils.get_parameter("dh", map_so, inst) dh = dh_tuple[0] # Get the detector pixel angular width dtd_tuple = hlr_utils.get_parameter("dtd", map_so, inst) dtd = dtd_tuple[0] # Get partial derivatives dazi_dh_tuple = hlr_utils.get_parameter("dazi_dh", map_so, inst) dazi_dh = dazi_dh_tuple[0] dpol_dh_tuple = hlr_utils.get_parameter("dpol_dh", map_so, inst) dpol_dh = dpol_dh_tuple[0] dpol_dtd_tuple = hlr_utils.get_parameter("dpol_dtd", map_so, inst) dpol_dtd = dpol_dtd_tuple[0] dazi_dtd_tuple = hlr_utils.get_parameter("dazi_dtd", map_so, inst) dazi_dtd = dazi_dtd_tuple[0] import math sin_pol = math.sin(angle) return math.fabs(sin_pol * dtd * dh * (dpol_dtd * dazi_dh - dpol_dh * dazi_dtd))
def param_array(som, param): """ This function takes a parameter and interrogates the object for that information. @param som: The object containing the requested information. @type som: C{SOM.SOM} @param param: The name of the parameter to seek. @type param: C{string} @return: An array of the parameters from the incoming object. @rtype: C{list} """ len_som = hlr_utils.get_length(som) plist = [] inst = som.attr_list.instrument for i in xrange(len_som): plist.append(hlr_utils.get_parameter(param, som[i], inst)[0]) return plist
def calc_solid_angle(inst, pix, **kwargs): """ This function calculates the solid angle of a given pixel by taking the area of the pixel and the cosine of the polar angle and dividing it by the square of the pathlength. @param inst: The object containing the geometry information. @type inst: C{Instrument} or C{CompositeInstrument} @param pix: The pixel to calculate the solid angle for. @type pix: C{SOM.SO} @param kwargs: A list of keyword arguments that the function accepts: @keyword pathtype: The pathlength type from which to calculate the solid angle. The possible values are I{total}, I{primary} and I{secondary}. The default is I{secondary}. @type pathtype: C{string} """ import hlr_utils # Check for keywords try: pathtype = kwargs["pathtype"] except KeyError: pathtype = "secondary" # Get pixel pathlength and square it (this is in meters) pl = hlr_utils.get_parameter(pathtype, pix, inst) pl2 = pl[0] * pl[0] # Make object for neighboring pixel import SOM npix = SOM.SO() import math # Get x pixel size x1 = hlr_utils.get_parameter("x-offset", pix, inst) # Make the neighboring pixel ID in the x direction try: npix.id = (pix.id[0], (pix.id[1][0]+1, pix.id[1][1])) x2 = hlr_utils.get_parameter("x-offset", npix, inst) except IndexError: npix.id = (pix.id[0], (pix.id[1][0]-1, pix.id[1][1])) x2 = hlr_utils.get_parameter("x-offset", npix, inst) # Pixel offsets are in meters xdiff = math.fabs(x2 - x1) # Get y pixel size y1 = hlr_utils.get_parameter("y-offset", pix, inst) # Make the neighboring pixel ID in the y direction try: npix.id = (pix.id[0], (pix.id[1][0], pix.id[1][1]+1)) y2 = hlr_utils.get_parameter("y-offset", npix, inst) except IndexError: npix.id = (pix.id[0], (pix.id[1][0], pix.id[1][1]-1)) y2 = hlr_utils.get_parameter("y-offset", npix, inst) # Pixel offsets are in meters ydiff = math.fabs(y2 - y1) # Make pixel area pix_area = xdiff * ydiff # Get the polar angle polar = hlr_utils.get_parameter("polar", pix, inst) solid_angle = (pix_area * math.cos(polar[0])) / pl2 return solid_angle
def tof_to_wavelength_lin_time_zero(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to wavelength incorporating a linear time zero which is a described as a linear function of the wavelength. The time-of-flight axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(tof, tof_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(wavelength, wavelength_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword pathlength: The pathlength and its associated error^2 @type pathlength: C{tuple} or C{list} of C{tuple}s @keyword time_zero_slope: The time zero slope and its associated error^2 @type time_zero_slope: C{tuple} @keyword time_zero_offset: The time zero offset and its associated error^2 @type time_zero_offset: C{tuple} @keyword inst_param: The type of parameter requested from an associated instrument. For this function the acceptable parameters are I{primary}, I{secondary} and I{total}. Default is I{primary}. @type inst_param: C{string} @keyword lojac: A flag that allows one to turn off the calculation of the linear-order Jacobian. The default action is I{True} for histogram data. @type lojac: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds}. @type units: C{string} @keyword cut_val: Specify a wavelength to cut the spectra at. @type cut_val: C{float} @keyword cut_less: A flag that specifies cutting the spectra less than C{cut_val}. The default is C{True}. @type cut_less: C{boolean} @return: Object with a primary axis in time-of-flight converted to wavelength @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} @raise RuntimeError: A C{SOM} does not contain an instrument and no pathlength was provided @raise RuntimeError: No C{SOM} is provided and no pathlength given """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: inst_param = kwargs["inst_param"] except KeyError: inst_param = "primary" try: pathlength = kwargs["pathlength"] except KeyError: pathlength = None try: time_zero_slope = kwargs["time_zero_slope"] except KeyError: time_zero_slope = None # Current constants for Time Zero Slope TIME_ZERO_SLOPE = (float(0.0), float(0.0)) try: time_zero_offset = kwargs["time_zero_offset"] except KeyError: time_zero_offset = None # Current constants for Time Zero Offset TIME_ZERO_OFFSET = (float(0.0), float(0.0)) try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) try: units = kwargs["units"] except KeyError: units = "microseconds" try: cut_val = kwargs["cut_val"] except KeyError: cut_val = None try: cut_less = kwargs["cut_less"] except KeyError: cut_less = True # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "Angstroms", axis) result.setAxisLabel(axis, "wavelength") result.setYUnits("Counts/A") result.setYLabel("Intensity") else: pass if pathlength is not None: p_descr = hlr_utils.get_descr(pathlength) else: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided") else: raise RuntimeError("If no SOM is provided, then pathlength "\ +"information must be provided") if time_zero_slope is not None: t_0_slope_descr = hlr_utils.get_descr(time_zero_slope) else: if o_descr == "SOM": try: t_0_slope = obj.attr_list["Time_zero_slope"][0] t_0_slope_err2 = obj.attr_list["Time_zero_slope"][1] except KeyError: t_0_slope = TIME_ZERO_SLOPE[0] t_0_slope_err2 = TIME_ZERO_SLOPE[1] else: t_0_slope = TIME_ZERO_SLOPE[0] t_0_slope_err2 = TIME_ZERO_SLOPE[1] if time_zero_offset is not None: t_0_offset_descr = hlr_utils.get_descr(time_zero_offset) else: if o_descr == "SOM": try: t_0_offset = obj.attr_list["Time_zero_offset"][0] t_0_offset_err2 = obj.attr_list["Time_zero_offset"][1] except KeyError: t_0_offset = TIME_ZERO_OFFSET[0] t_0_offset_err2 = TIME_ZERO_OFFSET[1] else: t_0_offset = TIME_ZERO_OFFSET[0] t_0_offset_err2 = TIME_ZERO_OFFSET[1] # iterate through the values import axis_manip if lojac or cut_val is not None: import utils for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if pathlength is None: (pl, pl_err2) = hlr_utils.get_parameter(inst_param, map_so, inst) else: pl = hlr_utils.get_value(pathlength, i, p_descr) pl_err2 = hlr_utils.get_err2(pathlength, i, p_descr) if time_zero_slope is not None: t_0_slope = hlr_utils.get_value(time_zero_slope, i, t_0_slope_descr) t_0_slope_err2 = hlr_utils.get_err2(time_zero_slope, i, t_0_slope_descr) else: pass if time_zero_offset is not None: t_0_offset = hlr_utils.get_value(time_zero_offset, i, t_0_offset_descr) t_0_offset_err2 = hlr_utils.get_err2(time_zero_offset, i, t_0_offset_descr) else: pass value = axis_manip.tof_to_wavelength_lin_time_zero( val, err2, pl, pl_err2, t_0_slope, t_0_slope_err2, t_0_offset, t_0_offset_err2) if cut_val is not None: index = utils.bisect_helper(value[0], cut_val) if cut_less: # Need to cut at this index, so increment by one index += 1 value[0].__delslice__(0, index) value[1].__delslice__(0, index) map_so.y.__delslice__(0, index) map_so.var_y.__delslice__(0, index) if lojac: val.__delslice__(0, index) err2.__delslice__(0, index) else: len_data = len(value[0]) # All axis arrays need starting index adjusted by one since # they always carry one more bin than the data value[0].__delslice__(index + 1, len_data) value[1].__delslice__(index + 1, len_data) map_so.y.__delslice__(index, len_data) map_so.var_y.__delslice__(index, len_data) if lojac: val.__delslice__(index + 1, len_data) err2.__delslice__(index + 1, len_data) if lojac: counts = utils.linear_order_jacobian(val, value[0], map_so.y, map_so.var_y) hlr_utils.result_insert(result, res_descr, counts, map_so, "all", axis, [value[0]]) else: hlr_utils.result_insert(result, res_descr, value, map_so, "x", axis) return result
def calc_BSS_coeffs(map_so, inst, *args): """ This function calculates the x_i coefficients for the BSS instrument @param map_so: The spectrum object to calculate the coefficients for @type map_so: C{SOM.SO} @param inst: The instrument object associated with the data @type inst: C{SOM.Instrument} or C{SOM.CompositeInstrument} @param args: A list of parameters (C{tuple}s with value and err^2) used to calculate the x_i coefficients The following is a list of the arguments needed in there expected order 1. Initial Energy 2. Momentum Transfer 3. Initial Wavevector 4. Initial Time-of-Flight 5. Detector Pixel Height 6. Polar Angle 7. Final Energy 8. Final Wavevector 9. Final Wavelength 10. Source to Sample Distance 11. Sample to Detector Distance 12. Time-zero Slope 13. Vector of Zeros @type args: C{list} @return: The calculated coefficients (x_1, x_2, x_3, x_4) @rtype: C{tuple} of 4 C{nessi_list.NessiList}s """ import math # Settle out the arguments to sensible names E_i = args[0][0] E_i_err2 = args[0][1] Q = args[1][0] Q_err2 = args[1][1] k_i = args[2][0] k_i_err2 = args[2][1] T_i = args[3][0] T_i_err2 = args[3][1] dh = args[4] polar_angle = args[5] E_f = args[6] k_f = args[7] l_f = args[8] L_s = args[9] L_d = args[10] T_0_s = args[11] zero_vec = args[12] # Constant h/m_n (meters / microsecond) H_OVER_MNEUT = 0.003956034e-10 # Get the differential geometry parameters dlf_dh_tuple = hlr_utils.get_parameter("dlf_dh", map_so, inst) dlf_dh = dlf_dh_tuple[0] # dlf_dh should be unitless (Angstrom/Angstrom) dlf_dh *= 1e-10 dpol_dh_tuple = hlr_utils.get_parameter("dpol_dh", map_so, inst) dpol_dh = dpol_dh_tuple[0] # Convert to radian/Angstrom dpol_dh *= 1e-10 dpol_dtd_tuple = hlr_utils.get_parameter("dpol_dtd", map_so, inst) dpol_dtd = dpol_dtd_tuple[0] # Get the detector pixel angular width dtd_tuple = hlr_utils.get_parameter("dtd", map_so, inst) dtd = dtd_tuple[0] # Calculate bin centric values E_i_bc_tuple = utils.calc_bin_centers(E_i, E_i_err2) E_i_bc = E_i_bc_tuple[0] k_i_bc_tuple = utils.calc_bin_centers(k_i, k_i_err2) k_i_bc = k_i_bc_tuple[0] Q_bc_tuple = utils.calc_bin_centers(Q, Q_err2) Q_bc = Q_bc_tuple[0] T_i_bc_tuple = utils.calc_bin_centers(T_i, T_i_err2) T_i_bc = T_i_bc_tuple[0] # Get numeric values sin_polar = math.sin(polar_angle) cos_polar = math.cos(polar_angle) length_ratio = L_d / L_s lambda_const = ((2.0 * math.pi) / (l_f * l_f)) * dlf_dh kf_cos_pol = k_f * cos_polar kf_sin_pol = k_f * sin_polar t0_slope_corr = (1.0 / (1.0 + H_OVER_MNEUT * (T_0_s / L_s))) dtd_over_dh = dtd / dh # Calculate coefficients x_1_tuple = __calc_x1(k_i_bc, Q_bc, length_ratio, k_f, kf_cos_pol, kf_sin_pol, lambda_const, dpol_dh, dpol_dtd, dtd_over_dh, cos_polar, t0_slope_corr, zero_vec) x_1 = x_1_tuple[0] x_2_tuple = __calc_x2(k_i_bc, Q_bc, T_i_bc, kf_cos_pol, t0_slope_corr, zero_vec) x_2 = x_2_tuple[0] x_3_tuple = __calc_x3(k_i_bc, E_i_bc, length_ratio, E_f, k_f, lambda_const, t0_slope_corr, zero_vec) x_3 = x_3_tuple[0] x_4_tuple = __calc_x4(E_i_bc, T_i_bc, t0_slope_corr, zero_vec) x_4 = x_4_tuple[0] return (x_1, x_2, x_3, x_4)
def initial_wavelength_igs_lin_time_zero_to_tof(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from initial_wavelength_igs_lin_time_zero to time-of-flight. The initial_wavelength_igs_lin_time_zero axis for a C{SOM} must be in units of I{Angstroms}. The primary axis of a C{SO} is assumed to be in units of I{Angstroms}. A C{tuple} of C{(initial_wavelength_igs_lin_time_zero, initial_wavelength_igs_lin_time_zero_err2)} (assumed to be in units of I{Angstroms}) can be converted to C{(tof, tof_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword lambda_f:The final wavelength and its associated error^2 @type lambda_f: C{tuple} @keyword time_zero_slope: The time zero slope and its associated error^2 @type time_zero_slope: C{tuple} @keyword time_zero_offset: The time zero offset and its associated error^2 @type time_zero_offset: C{tuple} @keyword dist_source_sample: The source to sample distance information and its associated error^2 @type dist_source_sample: C{tuple} or C{list} of C{tuple}s @keyword dist_sample_detector: The sample to detector distance information and its associated error^2 @type dist_sample_detector: C{tuple} or C{list} of C{tuple}s @keyword lojac: A flag that allows one to turn off the calculation of the linear-order Jacobian. The default action is True for histogram data. @type lojac: C{boolean} @keyword units: The expected units for this function. The default for this function is I{Angstroms} @type units: C{string} @return: Object with a primary axis in initial_wavelength_igs converted to time-of-flight @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{Angstroms} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: lambda_f = kwargs["lambda_f"] except KeyError: lambda_f = None try: time_zero_slope = kwargs["time_zero_slope"] except KeyError: time_zero_slope = None # Current constants for Time Zero Slope TIME_ZERO_SLOPE = (float(0.0), float(0.0)) try: time_zero_offset = kwargs["time_zero_offset"] except KeyError: time_zero_offset = None # Current constants for Time Zero Offset TIME_ZERO_OFFSET = (float(0.0), float(0.0)) try: dist_source_sample = kwargs["dist_source_sample"] except KeyError: dist_source_sample = None try: dist_sample_detector = kwargs["dist_sample_detector"] except KeyError: dist_sample_detector = None try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) try: units = kwargs["units"] except KeyError: units = "Angstroms" # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "Microseconds", axis) result.setAxisLabel(axis, "time-of-flight") result.setYUnits("Counts/uS") result.setYLabel("Intensity") else: pass # Where to get instrument information if dist_source_sample is None or dist_sample_detector is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: if dist_source_sample is None and dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample and sample-detector "\ +"distances must be provided.") elif dist_source_sample is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample distance must be provided.") elif dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"sample-detector distance must be "\ +"provided.") else: raise RuntimeError("If you get here, see Steve Miller for "\ +"your mug.") else: pass if lambda_f is not None: l_descr = hlr_utils.get_descr(lambda_f) else: if o_descr == "SOM": try: som_l_f = obj.attr_list["Wavelength_final"] except KeyError: raise RuntimeError("Please provide a final wavelength "\ +"parameter either via the function call "\ +"or the SOM") else: raise RuntimeError("You need to provide a final wavelength") if time_zero_slope is not None: t_0_slope_descr = hlr_utils.get_descr(time_zero_slope) else: if o_descr == "SOM": try: t_0_slope = obj.attr_list["Time_zero_slope"][0] t_0_slope_err2 = obj.attr_list["Time_zero_slope"][1] except KeyError: t_0_slope = TIME_ZERO_SLOPE[0] t_0_slope_err2 = TIME_ZERO_SLOPE[1] else: t_0_slope = TIME_ZERO_SLOPE[0] t_0_slope_err2 = TIME_ZERO_SLOPE[1] if time_zero_offset is not None: t_0_offset_descr = hlr_utils.get_descr(time_zero_offset) else: if o_descr == "SOM": try: t_0_offset = obj.attr_list["Time_zero_offset"][0] t_0_offset_err2 = obj.attr_list["Time_zero_offset"][1] except KeyError: t_0_offset = TIME_ZERO_OFFSET[0] t_0_offset_err2 = TIME_ZERO_OFFSET[1] else: t_0_offset = TIME_ZERO_OFFSET[0] t_0_offset_err2 = TIME_ZERO_OFFSET[1] if dist_source_sample is not None: ls_descr = hlr_utils.get_descr(dist_source_sample) # Do nothing, go on else: pass if dist_sample_detector is not None: ld_descr = hlr_utils.get_descr(dist_sample_detector) # Do nothing, go on else: pass # iterate through the values len_obj = hlr_utils.get_length(obj) MNEUT_OVER_H = 1.0 / 0.003956034 MNEUT_OVER_H2 = MNEUT_OVER_H * MNEUT_OVER_H for i in xrange(len_obj): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if dist_source_sample is None: (L_s, L_s_err2) = hlr_utils.get_parameter("primary", map_so, inst) else: L_s = hlr_utils.get_value(dist_source_sample, i, ls_descr) L_s_err2 = hlr_utils.get_err2(dist_source_sample, i, ls_descr) if dist_sample_detector is None: (L_d, L_d_err2) = hlr_utils.get_parameter("secondary", map_so, inst) else: L_d = hlr_utils.get_value(dist_sample_detector, i, ld_descr) L_d_err2 = hlr_utils.get_err2(dist_sample_detector, i, ld_descr) if lambda_f is not None: l_f = hlr_utils.get_value(lambda_f, i, l_descr) l_f_err2 = hlr_utils.get_err2(lambda_f, i, l_descr) else: l_f_tuple = hlr_utils.get_special(som_l_f, map_so) l_f = l_f_tuple[0] l_f_err2 = l_f_tuple[1] if time_zero_slope is not None: t_0_slope = hlr_utils.get_value(time_zero_slope, i, t_0_slope_descr) t_0_slope_err2 = hlr_utils.get_err2(time_zero_slope, i, t_0_slope_descr) else: pass if time_zero_offset is not None: t_0_offset = hlr_utils.get_value(time_zero_offset, i, t_0_offset_descr) t_0_offset_err2 = hlr_utils.get_err2(time_zero_offset, i, t_0_offset_descr) else: pass # Going to violate rules since the current usage is with a single # number. When an SCL equivalent function arises, this code can be # fixed. front_const = MNEUT_OVER_H * L_s + t_0_slope term2 = MNEUT_OVER_H * l_f * L_d tof = (front_const * val) + term2 + t_0_offset front_const2 = front_const * front_const eterm1 = l_f * l_f * L_d_err2 eterm2 = L_d * L_d * l_f_err2 eterm3 = MNEUT_OVER_H2 * L_s_err2 tof_err2 = (front_const2 * err2) + (val * val) * \ (eterm3 + t_0_slope_err2) + (MNEUT_OVER_H2 * \ (eterm1 + eterm2)) + \ t_0_offset_err2 hlr_utils.result_insert(result, res_descr, (tof, tof_err2), None, "all") return result
def d_spacing_to_tof_focused_det(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from d-spacing to a focused time-of-flight. The focusing is done using the geometry information from a single detector pixel. The d-spacing axis for a C{SOM} must be in units of I{Angstroms}. The primary axis of a C{SO} is assumed to be in units of I{Angstroms}. @param obj: Object to be converted @type obj: C{SOM.SOM} or C{SOM.SO} @param kwargs: A list of keyword arguments that the function accepts: @keyword polar: The polar angle and its associated error^2 @type polar: C{tuple} or C{list} of C{tuple}s @keyword pathlength: The total pathlength and its associated error^2 @type pathlength: C{tuple} or C{list} of C{tuple}s @keyword pixel_id: The pixel ID from which the geometry information will be retrieved from the instrument @type pixel_id: C{tuple}=(\"bankN\", (x, y)) @keyword verbose: This determines if the pixel geometry information is printed. The default is False @type verbose: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds}. @type units: C{string} @return: Object with a primary axis in d-spacing converted to time-of-flight @rtype: C{SOM.SOM} or C{SOM.SO} @raise RuntimeError: A C{SOM} or C{SO} is not provided to the function @raise RuntimeError: No C{SOM.Instrument} is provided in a C{SOM} @raise RuntimeError: No C{SOM} is given and both the pathlength and polar angle are not provided @raise RuntimeError: No C{SOM} is given and the pathlength is not provided @raise RuntimeError: No C{SOM} is given and the polar angle is not provided """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) if o_descr == "number" or o_descr == "list": raise RuntimeError("Must provide a SOM of a SO to the function.") # Go on else: pass # Setup keyword arguments try: polar = kwargs["polar"] except KeyError: polar = None try: pathlength = kwargs["pathlength"] except KeyError: pathlength = None try: pixel_id = kwargs["pixel_id"] except KeyError: pixel_id = None try: verbose = kwargs["verbose"] except KeyError: verbose = False try: units = kwargs["units"] except KeyError: units = "Angstroms" # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "microseconds", axis) result.setAxisLabel(axis, "time-of-flight") result.setYUnits("Counts/usec") result.setYLabel("Intensity") else: pass if pathlength is None or polar is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("An instrument was not provided") else: if pathlength is None and polar is None: raise RuntimeError("If no SOM is provided, then pathlength "\ +"and polar angle information must be provided") elif pathlength is None: raise RuntimeError("If no SOM is provided, then pathlength "\ +"information must be provided") elif polar is None: raise RuntimeError("If no SOM is provided, then polar angle "\ +"information must be provided") else: raise RuntimeError("If you get here, see Steve Miller for "\ +"your mug.") else: pass if pathlength is not None: p_descr = hlr_utils.get_descr(pathlength) if polar is not None: a_descr = hlr_utils.get_descr(polar) # iterate through the values if pixel_id is not None: tmp_so = SOM.SO() tmp_so.id = pixel_id (pl, pl_err2) = hlr_utils.get_parameter("total", tmp_so, inst) (angle, angle_err2) = hlr_utils.get_parameter("polar", tmp_so, inst) if verbose: format_str = "Pixel ID %s has polar angle: (%f,%f) and " format_str += "pathlength: (%f,%f)" print format_str % (str(pixel_id), angle, angle_err2, pl, pl_err2) else: pass else: pl = hlr_utils.get_value(pathlength, 0, p_descr) pl_err2 = hlr_utils.get_err2(pathlength, 0, p_descr) angle = hlr_utils.get_value(polar, 0, a_descr) angle_err2 = hlr_utils.get_err2(polar, 0, a_descr) # iterate through the values import axis_manip for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) value = axis_manip.d_spacing_to_tof_focused_det(val, err2, pl, pl_err2, angle, angle_err2) hlr_utils.result_insert(result, res_descr, value, map_so, "x", axis) return result
def calc_substrate_trans(obj, subtrans_coeff, substrate_diam, **kwargs): """ This function calculates substrate transmission via the following formula: T = exp[-(A + B * wavelength) * d] where A is a constant with units of cm^-1, B is a constant with units of cm^-2 and d is the substrate diameter in units of cm. @param obj: The data object that contains the TOF axes to calculate the transmission from. @type obj: C{SOM.SOM} or C{SOM.SO} @param subtrans_coeff: The two coefficients for substrate transmission calculation. @type subtrans_coeff: C{tuple} of two C{float}s @param substrate_diam: The diameter of the substrate. @type substrate_diam: C{float} @param kwargs: A list of keyword arguments that the function accepts: @keyword pathlength: The pathlength and its associated error^2 @type pathlength: C{tuple} or C{list} of C{tuple}s @keyword units: The expected units for this function. The default for this function is I{microsecond}. @type units: C{string} @return: The calculate transmission for the given substrate parameters @rtype: C{SOM.SOM} or C{SOM.SO} @raise TypeError: The object used for calculation is not a C{SOM} or a C{SO} @raise RuntimeError: The C{SOM} x-axis units are not I{microsecond} @raise RuntimeError: A C{SOM} does not contain an instrument and no pathlength was provided @raise RuntimeError: No C{SOM} is provided and no pathlength given """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) if o_descr == "number" or o_descr == "list": raise TypeError("Do not know how to handle given type: %s" % o_descr) else: pass # Setup keyword arguments try: pathlength = kwargs["pathlength"] except KeyError: pathlength = None try: units = kwargs["units"] except KeyError: units = "microsecond" # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 if pathlength is not None: p_descr = hlr_utils.get_descr(pathlength) else: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided") else: raise RuntimeError("If no SOM is provided, then pathlength "\ +"information must be provided") result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result.setYLabel("Transmission") # iterate through the values import array_manip import axis_manip import nessi_list import utils import math len_obj = hlr_utils.get_length(obj) for i in xrange(len_obj): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if pathlength is None: (pl, pl_err2) = hlr_utils.get_parameter("total", map_so, inst) else: pl = hlr_utils.get_value(pathlength, i, p_descr) pl_err2 = hlr_utils.get_err2(pathlength, i, p_descr) value = axis_manip.tof_to_wavelength(val, err2, pl, pl_err2) value1 = utils.calc_bin_centers(value[0]) del value # Convert Angstroms to centimeters value2 = array_manip.mult_ncerr(value1[0], value1[1], subtrans_coeff[1] * 1.0e-8, 0.0) del value1 # Calculate the exponential value3 = array_manip.add_ncerr(value2[0], value2[1], subtrans_coeff[0], 0.0) del value2 value4 = array_manip.mult_ncerr(value3[0], value3[1], -1.0 * substrate_diam, 0.0) del value3 # Calculate transmission trans = nessi_list.NessiList() len_trans = len(value4[0]) for j in xrange(len_trans): trans.append(math.exp(value4[0][j])) trans_err2 = nessi_list.NessiList(len(trans)) hlr_utils.result_insert(result, res_descr, (trans, trans_err2), map_so) return result
def tof_to_initial_wavelength_igs_lin_time_zero(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to initial_wavelength_igs_lin_time_zero. The time-of-flight axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(tof, tof_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(initial_wavelength_igs, initial_wavelength_igs_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword lambda_f:The final wavelength and its associated error^2 @type lambda_f: C{tuple} @keyword time_zero_slope: The time zero slope and its associated error^2 @type time_zero_slope: C{tuple} @keyword time_zero_offset: The time zero offset and its associated error^2 @type time_zero_offset: C{tuple} @keyword dist_source_sample: The source to sample distance information and its associated error^2 @type dist_source_sample: C{tuple} or C{list} of C{tuple}s @keyword dist_sample_detector: The sample to detector distance information and its associated error^2 @type dist_sample_detector: C{tuple} or C{list} of C{tuple}s @keyword run_filter: This determines if the filter on the negative wavelengths is run. The default setting is True. @type run_filter: C{boolean} @keyword lojac: A flag that allows one to turn off the calculation of the linear-order Jacobian. The default action is True for histogram data. @type lojac: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds} @type units: C{string} @return: Object with a primary axis in time-of-flight converted to initial_wavelength_igs @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: lambda_f = kwargs["lambda_f"] except KeyError: lambda_f = None try: time_zero_slope = kwargs["time_zero_slope"] except KeyError: time_zero_slope = None # Current constants for Time Zero Slope TIME_ZERO_SLOPE = (float(0.0), float(0.0)) try: time_zero_offset = kwargs["time_zero_offset"] except KeyError: time_zero_offset = None # Current constants for Time Zero Offset TIME_ZERO_OFFSET = (float(0.0), float(0.0)) try: dist_source_sample = kwargs["dist_source_sample"] except KeyError: dist_source_sample = None try: dist_sample_detector = kwargs["dist_sample_detector"] except KeyError: dist_sample_detector = None try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) try: units = kwargs["units"] except KeyError: units = "microseconds" try: run_filter = kwargs["run_filter"] except KeyError: run_filter = True try: iobj = kwargs["iobj"] except KeyError: iobj = None # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "Angstroms", axis) result.setAxisLabel(axis, "wavelength") result.setYUnits("Counts/A") result.setYLabel("Intensity") else: pass # Where to get instrument information if dist_source_sample is None or dist_sample_detector is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument mobj = obj except RuntimeError: raise RuntimeError("A detector was not provided!") else: if iobj is None: if dist_source_sample is None and dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample and sample-detector "\ +"distances must be provided.") elif dist_source_sample is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample distance must be "\ +"provided.") elif dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"sample-detector distance must be "\ +"provided.") else: raise RuntimeError("If you get here, see Steve Miller "\ +"for your mug.") else: inst = iobj.attr_list.instrument mobj = iobj else: mobj = obj if lambda_f is not None: l_descr = hlr_utils.get_descr(lambda_f) else: if o_descr == "SOM": try: som_l_f = obj.attr_list["Wavelength_final"] except KeyError: raise RuntimeError("Please provide a final wavelength "\ +"parameter either via the function call "\ +"or the SOM") else: if iobj is None: raise RuntimeError("You need to provide a final wavelength") else: som_l_f = iobj.attr_list["Wavelength_final"] if time_zero_slope is not None: t_0_slope_descr = hlr_utils.get_descr(time_zero_slope) else: if o_descr == "SOM": try: t_0_slope = obj.attr_list["Time_zero_slope"][0] t_0_slope_err2 = obj.attr_list["Time_zero_slope"][1] except KeyError: t_0_slope = TIME_ZERO_SLOPE[0] t_0_slope_err2 = TIME_ZERO_SLOPE[1] else: t_0_slope = TIME_ZERO_SLOPE[0] t_0_slope_err2 = TIME_ZERO_SLOPE[1] if time_zero_offset is not None: t_0_offset_descr = hlr_utils.get_descr(time_zero_offset) else: if o_descr == "SOM": try: t_0_offset = obj.attr_list["Time_zero_offset"][0] t_0_offset_err2 = obj.attr_list["Time_zero_offset"][1] except KeyError: t_0_offset = TIME_ZERO_OFFSET[0] t_0_offset_err2 = TIME_ZERO_OFFSET[1] else: t_0_offset = TIME_ZERO_OFFSET[0] t_0_offset_err2 = TIME_ZERO_OFFSET[1] if dist_source_sample is not None: ls_descr = hlr_utils.get_descr(dist_source_sample) # Do nothing, go on else: pass if dist_sample_detector is not None: ld_descr = hlr_utils.get_descr(dist_sample_detector) # Do nothing, go on else: pass # iterate through the values import axis_manip if lojac: import utils for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(mobj, None, i) if dist_source_sample is None: (L_s, L_s_err2) = hlr_utils.get_parameter("primary", map_so, inst) else: L_s = hlr_utils.get_value(dist_source_sample, i, ls_descr) L_s_err2 = hlr_utils.get_err2(dist_source_sample, i, ls_descr) if dist_sample_detector is None: (L_d, L_d_err2) = hlr_utils.get_parameter("secondary", map_so, inst) else: L_d = hlr_utils.get_value(dist_sample_detector, i, ld_descr) L_d_err2 = hlr_utils.get_err2(dist_sample_detector, i, ld_descr) if lambda_f is not None: l_f = hlr_utils.get_value(lambda_f, i, l_descr) l_f_err2 = hlr_utils.get_err2(lambda_f, i, l_descr) else: l_f_tuple = hlr_utils.get_special(som_l_f, map_so) l_f = l_f_tuple[0] l_f_err2 = l_f_tuple[1] if time_zero_slope is not None: t_0_slope = hlr_utils.get_value(time_zero_slope, i, t_0_slope_descr) t_0_slope_err2 = hlr_utils.get_err2(time_zero_slope, i, t_0_slope_descr) else: pass if time_zero_offset is not None: t_0_offset = hlr_utils.get_value(time_zero_offset, i, t_0_offset_descr) t_0_offset_err2 = hlr_utils.get_err2(time_zero_offset, i, t_0_offset_descr) else: pass value = axis_manip.tof_to_initial_wavelength_igs_lin_time_zero( val, err2, l_f, l_f_err2, t_0_slope, t_0_slope_err2, t_0_offset, t_0_offset_err2, L_s, L_s_err2, L_d, L_d_err2) # Remove all wavelengths < 0 if run_filter: index = 0 for valx in value[0]: if valx >= 0: break index += 1 value[0].__delslice__(0, index) value[1].__delslice__(0, index) map_so.y.__delslice__(0, index) map_so.var_y.__delslice__(0, index) if lojac: val.__delslice__(0, index) err2.__delslice__(0, index) else: pass if lojac: try: counts = utils.linear_order_jacobian(val, value[0], map_so.y, map_so.var_y) except Exception, e: # Lets us know offending pixel ID raise Exception(str(map_so.id) + " " + str(e)) hlr_utils.result_insert(result, res_descr, counts, map_so, "all", axis, [value[0]]) else: hlr_utils.result_insert(result, res_descr, value, map_so, "x", axis)
def wavelength_to_d_spacing(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from wavelength to d-spacing. The wavelength axis for a C{SOM} must be in units of I{Angstroms}. The primary axis of a C{SO} is assumed to be in units of I{Angstroms}. A C{tuple} of C{(wavelength, wavelength_err2)} (assumed to be in units of I{Angstroms}) can be converted to C{(d_spacing, d_spacing_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword polar:The polar angle and its associated error^2 @type polar: C{tuple} @keyword units: The expected units for this function. The default for this function is I{Angstroms} @type units: C{string} @return: Object with a primary axis in wavelength converted to d-spacing @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: A C{SOM} is not passed and no polar angle is provided @raise RuntimeError: The C{SOM} x-axis units are not I{Angstroms} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) if o_descr == "list": raise TypeError("Do not know how to handle given type: %s" % \ o_descr) else: pass # Setup keyword arguments try: polar = kwargs["polar"] except KeyError: polar = None try: units = kwargs["units"] except KeyError: units = "Angstroms" # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "Angstroms", axis) result.setAxisLabel(axis, "d-spacing") result.setYUnits("Counts/A") result.setYLabel("Intensity") else: pass if polar is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: raise RuntimeError("If no SOM is provided, then polar "\ +"information must be given.") else: p_descr = hlr_utils.get_descr(polar) # iterate through the values import axis_manip for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if polar is None: (angle, angle_err2) = hlr_utils.get_parameter("polar", map_so, inst) else: angle = hlr_utils.get_value(polar, i, p_descr) angle_err2 = hlr_utils.get_err2(polar, i, p_descr) value = axis_manip.wavelength_to_d_spacing(val, err2, angle, angle_err2) hlr_utils.result_insert(result, res_descr, value, map_so, "x", axis) return result
def convert_single_to_list(funcname, number, som, **kwargs): """ This function retrieves a function object from the L{common_lib} set of functions that provide axis transformations and converts the provided number based on that function. Instrument geometry information needs to be provided via the C{SOM}. The following is the list of functions supported by this one. - d_spacing_to_tof_focused_det - energy_to_wavelength - frequency_to_energy - initial_wavelength_igs_lin_time_zero_to_tof - init_scatt_wavevector_to_scalar_Q - tof_to_initial_wavelength_igs_lin_time_zero - tof_to_initial_wavelength_igs - tof_to_scalar_Q - tof_to_wavelength_lin_time_zero - tof_to_wavelength - wavelength_to_d_spacing - wavelength_to_energy - wavelength_to_scalar_k - wavelength_to_scalar_Q @param funcname: The name of the axis conversion function to use @type funcname: C{string} @param number: The value and error^2 to convert @type number: C{tuple} @param som: The object containing geometry and other special information @type som: C{SOM.SOM} @param kwargs: A list of keyword arguments that the function accepts: @keyword inst_param: The type of parameter requested from an associated instrument. For this function the acceptable parameters are I{primary}, I{secondary} and I{total}. Default is I{primary}. @type inst_param: C{string} @keyword pixel_id: The pixel ID from which the geometry information will be retrieved from the instrument @type pixel_id: C{tuple}=(\"bankN\", (x, y)) @return: A converted number for every unique spectrum @rtype: C{list} of C{tuple}s @raise AttributeError: The requested function is not in the approved list """ # Setup supported function list and check to see if funcname is available function_list = [] function_list.append("d_spacing_to_tof_focused_det") function_list.append("energy_to_wavelength") function_list.append("frequency_to_energy") function_list.append("initial_wavelength_igs_lin_time_zero_to_tof") function_list.append("init_scatt_wavevector_to_scalar_Q") function_list.append("tof_to_initial_wavelength_igs_lin_time_zero") function_list.append("tof_to_initial_wavelength_igs") function_list.append("tof_to_scalar_Q") function_list.append("tof_to_wavelength_lin_time_zero") function_list.append("tof_to_wavelength") function_list.append("wavelength_to_d_spacing") function_list.append("wavelength_to_energy") function_list.append("wavelength_to_scalar_k") function_list.append("wavelength_to_scalar_Q") if funcname not in function_list: raise AttributeError("Function %s is not supported by "\ +"convert_single_to_list" % funcname) import common_lib # Get the common_lib function object func = common_lib.__getattribute__(funcname) # Setup inclusive dictionary containing the requested keywords for all # common_lib axis conversion functions fkwds = {} fkwds["pathlength"] = () fkwds["polar"] = () fkwds["lambda_f"] = () try: lambda_final = som.attr_list["Wavelength_final"] except KeyError: lambda_final = None try: fkwds["time_zero_slope"] = som.attr_list["Time_zero_slope"] except KeyError: pass try: fkwds["time_zero_offset"] = som.attr_list["Time_zero_offset"] except KeyError: pass try: fkwds["time_zero"] = som.attr_list["Time_zero"] except KeyError: pass fkwds["dist_source_sample"] = () fkwds["dist_sample_detector"] = () try: fkwds["inst_param"] = kwargs["inst_param"] except KeyError: fkwds["inst_param"] = "primary" try: fkwds["pixel_id"] = kwargs["pixel_id"] except KeyError: fkwds["pixel_id"] = None fkwds["run_filter"] = False # Set up for working through data # This time highest object in the hierarchy is NOT what we need result = [] res_descr = "list" inst = som.attr_list.instrument import hlr_utils # iterate through the values for i in xrange(hlr_utils.get_length(som)): map_so = hlr_utils.get_map_so(som, None, i) fkwds["pathlength"] = hlr_utils.get_parameter(fkwds["inst_param"], map_so, inst) fkwds["dist_source_sample"] = hlr_utils.get_parameter( "primary", map_so, inst) fkwds["dist_sample_detector"] = hlr_utils.get_parameter( "secondary", map_so, inst) fkwds["polar"] = hlr_utils.get_parameter("polar", map_so, inst) fkwds["lambda_f"] = hlr_utils.get_special(lambda_final, map_so) value = tuple(func(number, **fkwds)) hlr_utils.result_insert(result, res_descr, value, None, "all") return result
def tof_to_final_velocity_dgs(obj, velocity_i, time_zero_offset, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to final_velocity_dgs. The time-of-flight axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(tof, tof_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(final_velocity_dgs, final_velocity_dgs_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param velocity_i: The initial velocity and its associated error^2 @type velocity_i: C{tuple} @param time_zero_offset: The time zero offset and its associated error^2 @type time_zero_offset: C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword dist_source_sample: The source to sample distance information and its associated error^2 @type dist_source_sample: C{tuple} or C{list} of C{tuple}s @keyword dist_sample_detector: The sample to detector distance information and its associated error^2 @type dist_sample_detector: C{tuple} or C{list} of C{tuple}s @keyword run_filter: This determines if the filter on the negative velocities is run. The default setting is True. @type run_filter: C{boolean} @keyword lojac: A flag that allows one to turn off the calculation of the linear-order Jacobian. The default action is True for histogram data. @type lojac: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds} @type units: C{string} @return: Object with a primary axis in time-of-flight converted to final_velocity_dgs @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} """ import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: dist_source_sample = kwargs["dist_source_sample"] except KeyError: dist_source_sample = None try: dist_sample_detector = kwargs["dist_sample_detector"] except KeyError: dist_sample_detector = None try: units = kwargs["units"] except KeyError: units = "microseconds" try: run_filter = kwargs["run_filter"] except KeyError: run_filter = True try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "meters/microseconds", axis) result.setAxisLabel(axis, "velocity") result.setYUnits("Counts/meters/microseconds") result.setYLabel("Intensity") else: pass # Where to get instrument information if dist_source_sample is None or dist_sample_detector is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: if dist_source_sample is None and dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample and sample-detector "\ +"distances must be provided.") elif dist_source_sample is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample distance must be provided.") elif dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"sample-detector distance must be "\ +"provided.") else: raise RuntimeError("If you get here, see Steve Miller for "\ +"your mug.") else: pass if dist_source_sample is not None: ls_descr = hlr_utils.get_descr(dist_source_sample) # Do nothing, go on else: pass if dist_sample_detector is not None: ld_descr = hlr_utils.get_descr(dist_sample_detector) # Do nothing, go on else: pass # iterate through the values import axis_manip if lojac: import utils len_obj = hlr_utils.get_length(obj) for i in xrange(len_obj): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if dist_source_sample is None: (L_s, L_s_err2) = hlr_utils.get_parameter("primary", map_so, inst) else: L_s = hlr_utils.get_value(dist_source_sample, i, ls_descr) L_s_err2 = hlr_utils.get_err2(dist_source_sample, i, ls_descr) if dist_sample_detector is None: (L_d, L_d_err2) = hlr_utils.get_parameter("secondary", map_so, inst) else: L_d = hlr_utils.get_value(dist_sample_detector, i, ld_descr) L_d_err2 = hlr_utils.get_err2(dist_sample_detector, i, ld_descr) value = axis_manip.tof_to_final_velocity_dgs(val, err2, velocity_i[0], velocity_i[1], time_zero_offset[0], time_zero_offset[1], L_s, L_s_err2, L_d, L_d_err2) # Remove all velocities < 0 if run_filter: index = 0 for valx in value[0]: if valx >= 0: break index += 1 value[0].__delslice__(0, index) value[1].__delslice__(0, index) map_so.y.__delslice__(0, index) map_so.var_y.__delslice__(0, index) if lojac: val.__delslice__(0, index) err2.__delslice__(0, index) else: pass if lojac: (map_so.y, map_so.var_y) = utils.linear_order_jacobian( val, value[0], map_so.y, map_so.var_y) # Need to reverse arrays due to conversion if o_descr != "number": valx = axis_manip.reverse_array_cp(value[0]) valxe = axis_manip.reverse_array_cp(value[1]) rev_value = (valx, valxe) else: rev_value = value if map_so is not None: map_so.y = axis_manip.reverse_array_cp(map_so.y) map_so.var_y = axis_manip.reverse_array_cp(map_so.var_y) hlr_utils.result_insert(result, res_descr, rev_value, map_so, "x", axis) return result
def tof_to_final_velocity_dgs(obj, velocity_i, time_zero_offset, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to final_velocity_dgs. The time-of-flight axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(tof, tof_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(final_velocity_dgs, final_velocity_dgs_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param velocity_i: The initial velocity and its associated error^2 @type velocity_i: C{tuple} @param time_zero_offset: The time zero offset and its associated error^2 @type time_zero_offset: C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword dist_source_sample: The source to sample distance information and its associated error^2 @type dist_source_sample: C{tuple} or C{list} of C{tuple}s @keyword dist_sample_detector: The sample to detector distance information and its associated error^2 @type dist_sample_detector: C{tuple} or C{list} of C{tuple}s @keyword run_filter: This determines if the filter on the negative velocities is run. The default setting is True. @type run_filter: C{boolean} @keyword lojac: A flag that allows one to turn off the calculation of the linear-order Jacobian. The default action is True for histogram data. @type lojac: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds} @type units: C{string} @return: Object with a primary axis in time-of-flight converted to final_velocity_dgs @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} """ import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: dist_source_sample = kwargs["dist_source_sample"] except KeyError: dist_source_sample = None try: dist_sample_detector = kwargs["dist_sample_detector"] except KeyError: dist_sample_detector = None try: units = kwargs["units"] except KeyError: units = "microseconds" try: run_filter = kwargs["run_filter"] except KeyError: run_filter = True try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "meters/microseconds", axis) result.setAxisLabel(axis, "velocity") result.setYUnits("Counts/meters/microseconds") result.setYLabel("Intensity") else: pass # Where to get instrument information if dist_source_sample is None or dist_sample_detector is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: if dist_source_sample is None and dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample and sample-detector "\ +"distances must be provided.") elif dist_source_sample is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample distance must be provided.") elif dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"sample-detector distance must be "\ +"provided.") else: raise RuntimeError("If you get here, see Steve Miller for "\ +"your mug.") else: pass if dist_source_sample is not None: ls_descr = hlr_utils.get_descr(dist_source_sample) # Do nothing, go on else: pass if dist_sample_detector is not None: ld_descr = hlr_utils.get_descr(dist_sample_detector) # Do nothing, go on else: pass # iterate through the values import axis_manip if lojac: import utils len_obj = hlr_utils.get_length(obj) for i in xrange(len_obj): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if dist_source_sample is None: (L_s, L_s_err2) = hlr_utils.get_parameter("primary", map_so, inst) else: L_s = hlr_utils.get_value(dist_source_sample, i, ls_descr) L_s_err2 = hlr_utils.get_err2(dist_source_sample, i, ls_descr) if dist_sample_detector is None: (L_d, L_d_err2) = hlr_utils.get_parameter("secondary", map_so, inst) else: L_d = hlr_utils.get_value(dist_sample_detector, i, ld_descr) L_d_err2 = hlr_utils.get_err2(dist_sample_detector, i, ld_descr) value = axis_manip.tof_to_final_velocity_dgs(val, err2, velocity_i[0], velocity_i[1], time_zero_offset[0], time_zero_offset[1], L_s, L_s_err2, L_d, L_d_err2) # Remove all velocities < 0 if run_filter: index = 0 for valx in value[0]: if valx >= 0: break index += 1 value[0].__delslice__(0, index) value[1].__delslice__(0, index) map_so.y.__delslice__(0, index) map_so.var_y.__delslice__(0, index) if lojac: val.__delslice__(0, index) err2.__delslice__(0, index) else: pass if lojac: (map_so.y, map_so.var_y) = utils.linear_order_jacobian(val, value[0], map_so.y, map_so.var_y) # Need to reverse arrays due to conversion if o_descr != "number": valx = axis_manip.reverse_array_cp(value[0]) valxe = axis_manip.reverse_array_cp(value[1]) rev_value = (valx, valxe) else: rev_value = value if map_so is not None: map_so.y = axis_manip.reverse_array_cp(map_so.y) map_so.var_y = axis_manip.reverse_array_cp(map_so.var_y) hlr_utils.result_insert(result, res_descr, rev_value, map_so, "x", axis) return result
def tof_to_initial_wavelength_igs(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to initial_wavelength_igs. The time-of-flight axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(tof, tof_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(initial_wavelength_igs, initial_wavelength_igs_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword lambda_f:The final wavelength and its associated error^2 @type lambda_f: C{tuple} @keyword time_zero: The time zero offset and its associated error^2 @type time_zero: C{tuple} @keyword dist_source_sample: The source to sample distance information and its associated error^2 @type dist_source_sample: C{tuple} or C{list} of C{tuple}s @keyword dist_sample_detector: The sample to detector distance information and its associated error^2 @type dist_sample_detector: C{tuple} or C{list} of C{tuple}s @keyword run_filter: This determines if the filter on the negative wavelengths is run. The default setting is True. @type run_filter: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds} @type units: C{string} @return: Object with a primary axis in time-of-flight converted to initial_wavelength_igs @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: lambda_f = kwargs["lambda_f"] except KeyError: lambda_f = None try: time_zero = kwargs["time_zero"] except KeyError: time_zero = None try: dist_source_sample = kwargs["dist_source_sample"] except KeyError: dist_source_sample = None try: dist_sample_detector = kwargs["dist_sample_detector"] except KeyError: dist_sample_detector = None try: units = kwargs["units"] except KeyError: units = "microseconds" try: run_filter = kwargs["run_filter"] except KeyError: run_filter = True # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "Angstroms", axis) result.setAxisLabel(axis, "wavelength") result.setYUnits("Counts/A") result.setYLabel("Intensity") else: pass # Where to get instrument information if dist_source_sample is None or dist_sample_detector is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: if dist_source_sample is None and dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample and sample-detector "\ +"distances must be provided.") elif dist_source_sample is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample distance must be provided.") elif dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"sample-detector distance must be "\ +"provided.") else: raise RuntimeError("If you get here, see Steve Miller for "\ +"your mug.") else: pass if lambda_f is not None: l_descr = hlr_utils.get_descr(lambda_f) else: if o_descr == "SOM": try: som_l_f = obj.attr_list["Wavelength_final"] except KeyError: raise RuntimeError("Please provide a final wavelength "\ +"parameter either via the function call "\ +"or the SOM") else: raise RuntimeError("You need to provide a final wavelength") if time_zero is not None: t_descr = hlr_utils.get_descr(time_zero) else: if o_descr == "SOM": try: t_0 = obj.attr_list["Time_zero"][0] t_0_err2 = obj.attr_list["Time_zero"][1] except KeyError: raise RuntimeError("Please provide a time-zero "\ +"parameter either via the function call "\ +"or the SOM") else: t_0 = 0.0 t_0_err2 = 0.0 if dist_source_sample is not None: ls_descr = hlr_utils.get_descr(dist_source_sample) # Do nothing, go on else: pass if dist_sample_detector is not None: ld_descr = hlr_utils.get_descr(dist_sample_detector) # Do nothing, go on else: pass # iterate through the values import axis_manip for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if dist_source_sample is None: (L_s, L_s_err2) = hlr_utils.get_parameter("primary", map_so, inst) else: L_s = hlr_utils.get_value(dist_source_sample, i, ls_descr) L_s_err2 = hlr_utils.get_err2(dist_source_sample, i, ls_descr) if dist_sample_detector is None: (L_d, L_d_err2) = hlr_utils.get_parameter("secondary", map_so, inst) else: L_d = hlr_utils.get_value(dist_sample_detector, i, ld_descr) L_d_err2 = hlr_utils.get_err2(dist_sample_detector, i, ld_descr) if lambda_f is not None: l_f = hlr_utils.get_value(lambda_f, i, l_descr) l_f_err2 = hlr_utils.get_err2(lambda_f, i, l_descr) else: l_f_tuple = hlr_utils.get_special(som_l_f, map_so) l_f = l_f_tuple[0] l_f_err2 = l_f_tuple[1] if time_zero is not None: t_0 = hlr_utils.get_value(time_zero, i, t_descr) t_0_err2 = hlr_utils.get_err2(time_zero, i, t_descr) else: pass value = axis_manip.tof_to_initial_wavelength_igs( val, err2, l_f, l_f_err2, t_0, t_0_err2, L_s, L_s_err2, L_d, L_d_err2) # Remove all wavelengths < 0 if run_filter: index = 0 for val in value[0]: if val >= 0: break index += 1 value[0].__delslice__(0, index) value[1].__delslice__(0, index) map_so.y.__delslice__(0, index) map_so.var_y.__delslice__(0, index) else: pass hlr_utils.result_insert(result, res_descr, value, map_so, "x", axis) return result
def create_E_vs_Q_igs(som, *args, **kwargs): """ This function starts with the initial IGS wavelength axis and turns this into a 2D spectra with E and Q axes. @param som: The input object with initial IGS wavelength axis @type som: C{SOM.SOM} @param args: A mandatory list of axes for rebinning. There is a particular order to them. They should be present in the following order: Without errors 1. Energy transfer 2. Momentum transfer With errors 1. Energy transfer 2. Energy transfer error^2 3. Momentum transfer 4. Momentum transfer error ^2 @type args: C{nessi_list.NessiList}s @param kwargs: A list of keyword arguments that the function accepts: @keyword withXVar: Flag for whether the function should be expecting the associated axes to have errors. The default value will be I{False}. @type withXVar: C{boolean} @keyword data_type: Name of the data type which can be either I{histogram}, I{density} or I{coordinate}. The default value will be I{histogram} @type data_type: C{string} @keyword Q_filter: Flag to turn on or off Q filtering. The default behavior is I{True}. @type Q_filter: C{boolean} @keyword so_id: The identifier represents a number, string, tuple or other object that describes the resulting C{SO} @type so_id: C{int}, C{string}, C{tuple}, C{pixel ID} @keyword y_label: The y axis label @type y_label: C{string} @keyword y_units: The y axis units @type y_units: C{string} @keyword x_labels: This is a list of names that sets the individual x axis labels @type x_labels: C{list} of C{string}s @keyword x_units: This is a list of names that sets the individual x axis units @type x_units: C{list} of C{string}s @keyword split: This flag causes the counts and the fractional area to be written out into separate files. @type split: C{boolean} @keyword configure: This is the object containing the driver configuration. @type configure: C{Configure} @return: Object containing a 2D C{SO} with E and Q axes @rtype: C{SOM.SOM} @raise RuntimeError: Anything other than a C{SOM} is passed to the function @raise RuntimeError: An instrument is not contained in the C{SOM} """ import nessi_list # Setup some variables dim = 2 N_y = [] N_tot = 1 N_args = len(args) # Get T0 slope in order to calculate dT = dT_i + dT_0 try: t_0_slope = som.attr_list["Time_zero_slope"][0] t_0_slope_err2 = som.attr_list["Time_zero_slope"][1] except KeyError: t_0_slope = float(0.0) t_0_slope_err2 = float(0.0) # Check withXVar keyword argument and also check number of given args. # Set xvar to the appropriate value try: value = kwargs["withXVar"] if value.lower() == "true": if N_args != 4: raise RuntimeError("Since you have requested x errors, 4 x "\ +"axes must be provided.") else: xvar = True elif value.lower() == "false": if N_args != 2: raise RuntimeError("Since you did not requested x errors, 2 "\ +"x axes must be provided.") else: xvar = False else: raise RuntimeError("Do not understand given parameter %s" % \ value) except KeyError: if N_args != 2: raise RuntimeError("Since you did not requested x errors, 2 "\ +"x axes must be provided.") else: xvar = False # Check dataType keyword argument. An offset will be set to 1 for the # histogram type and 0 for either density or coordinate try: data_type = kwargs["data_type"] if data_type.lower() == "histogram": offset = 1 elif data_type.lower() == "density" or \ data_type.lower() == "coordinate": offset = 0 else: raise RuntimeError("Do not understand data type given: %s" % \ data_type) # Default is offset for histogram except KeyError: offset = 1 try: Q_filter = kwargs["Q_filter"] except KeyError: Q_filter = True # Check for split keyword try: split = kwargs["split"] except KeyError: split = False # Check for configure keyword try: configure = kwargs["configure"] except KeyError: configure = None so_dim = SOM.SO(dim) for i in range(dim): # Set the x-axis arguments from the *args list into the new SO if not xvar: # Axis positions are 1 (Q) and 0 (E) position = dim - i - 1 so_dim.axis[i].val = args[position] else: # Axis positions are 2 (Q), 3 (eQ), 0 (E), 1 (eE) position = dim - 2 * i so_dim.axis[i].val = args[position] so_dim.axis[i].var = args[position + 1] # Set individual value axis sizes (not x-axis size) N_y.append(len(args[position]) - offset) # Calculate total 2D array size N_tot = N_tot * N_y[-1] # Create y and var_y lists from total 2D size so_dim.y = nessi_list.NessiList(N_tot) so_dim.var_y = nessi_list.NessiList(N_tot) # Create area sum and errors for the area sum lists from total 2D size area_sum = nessi_list.NessiList(N_tot) area_sum_err2 = nessi_list.NessiList(N_tot) # Create area sum and errors for the area sum lists from total 2D size bin_count = nessi_list.NessiList(N_tot) bin_count_err2 = nessi_list.NessiList(N_tot) inst = som.attr_list.instrument lambda_final = som.attr_list["Wavelength_final"] inst_name = inst.get_name() import bisect import math import dr_lib import utils arr_len = 0 #: Vector of zeros for function calculations zero_vec = None for j in xrange(hlr_utils.get_length(som)): # Get counts counts = hlr_utils.get_value(som, j, "SOM", "y") counts_err2 = hlr_utils.get_err2(som, j, "SOM", "y") arr_len = len(counts) zero_vec = nessi_list.NessiList(arr_len) # Get mapping SO map_so = hlr_utils.get_map_so(som, None, j) # Get lambda_i l_i = hlr_utils.get_value(som, j, "SOM", "x") l_i_err2 = hlr_utils.get_err2(som, j, "SOM", "x") # Get lambda_f from instrument information l_f_tuple = hlr_utils.get_special(lambda_final, map_so) l_f = l_f_tuple[0] l_f_err2 = l_f_tuple[1] # Get source to sample distance (L_s, L_s_err2) = hlr_utils.get_parameter("primary", map_so, inst) # Get sample to detector distance L_d_tuple = hlr_utils.get_parameter("secondary", map_so, inst) L_d = L_d_tuple[0] # Get polar angle from instrument information (angle, angle_err2) = hlr_utils.get_parameter("polar", map_so, inst) # Get the detector pixel height dh_tuple = hlr_utils.get_parameter("dh", map_so, inst) dh = dh_tuple[0] # Need dh in units of Angstrom dh *= 1e10 # Calculate T_i (T_i, T_i_err2) = axis_manip.wavelength_to_tof(l_i, l_i_err2, L_s, L_s_err2) # Scale counts by lambda_f / lambda_i (l_i_bc, l_i_bc_err2) = utils.calc_bin_centers(l_i, l_i_err2) (ratio, ratio_err2) = array_manip.div_ncerr(l_f, l_f_err2, l_i_bc, l_i_bc_err2) (counts, counts_err2) = array_manip.mult_ncerr(counts, counts_err2, ratio, ratio_err2) # Calculate E_i (E_i, E_i_err2) = axis_manip.wavelength_to_energy(l_i, l_i_err2) # Calculate E_f (E_f, E_f_err2) = axis_manip.wavelength_to_energy(l_f, l_f_err2) # Calculate E_t (E_t, E_t_err2) = array_manip.sub_ncerr(E_i, E_i_err2, E_f, E_f_err2) if inst_name == "BSS": # Convert E_t from meV to ueV (E_t, E_t_err2) = array_manip.mult_ncerr(E_t, E_t_err2, 1000.0, 0.0) (counts, counts_err2) = array_manip.mult_ncerr(counts, counts_err2, 1.0/1000.0, 0.0) # Convert lambda_i to k_i (k_i, k_i_err2) = axis_manip.wavelength_to_scalar_k(l_i, l_i_err2) # Convert lambda_f to k_f (k_f, k_f_err2) = axis_manip.wavelength_to_scalar_k(l_f, l_f_err2) # Convert k_i and k_f to Q (Q, Q_err2) = axis_manip.init_scatt_wavevector_to_scalar_Q(k_i, k_i_err2, k_f, k_f_err2, angle, angle_err2) # Calculate dT = dT_0 + dT_i dT_i = utils.calc_bin_widths(T_i, T_i_err2) (l_i_bw, l_i_bw_err2) = utils.calc_bin_widths(l_i, l_i_err2) dT_0 = array_manip.mult_ncerr(l_i_bw, l_i_bw_err2, t_0_slope, t_0_slope_err2) dT_tuple = array_manip.add_ncerr(dT_i[0], dT_i[1], dT_0[0], dT_0[1]) dT = dT_tuple[0] # Calculate Jacobian if inst_name == "BSS": (x_1, x_2, x_3, x_4) = dr_lib.calc_BSS_coeffs(map_so, inst, (E_i, E_i_err2), (Q, Q_err2), (k_i, k_i_err2), (T_i, T_i_err2), dh, angle, E_f, k_f, l_f, L_s, L_d, t_0_slope, zero_vec) else: raise RuntimeError("Do not know how to calculate x_i "\ +"coefficients for instrument %s" % inst_name) (A, A_err2) = dr_lib.calc_EQ_Jacobian(x_1, x_2, x_3, x_4, dT, dh, zero_vec) # Apply Jacobian: C/dlam * dlam / A(EQ) = C/EQ (jac_ratio, jac_ratio_err2) = array_manip.div_ncerr(l_i_bw, l_i_bw_err2, A, A_err2) (counts, counts_err2) = array_manip.mult_ncerr(counts, counts_err2, jac_ratio, jac_ratio_err2) # Reverse counts, E_t, k_i and Q E_t = axis_manip.reverse_array_cp(E_t) E_t_err2 = axis_manip.reverse_array_cp(E_t_err2) Q = axis_manip.reverse_array_cp(Q) Q_err2 = axis_manip.reverse_array_cp(Q_err2) counts = axis_manip.reverse_array_cp(counts) counts_err2 = axis_manip.reverse_array_cp(counts_err2) k_i = axis_manip.reverse_array_cp(k_i) x_1 = axis_manip.reverse_array_cp(x_1) x_2 = axis_manip.reverse_array_cp(x_2) x_3 = axis_manip.reverse_array_cp(x_3) x_4 = axis_manip.reverse_array_cp(x_4) dT = axis_manip.reverse_array_cp(dT) # Filter for duplicate Q values if Q_filter: k_i_cutoff = k_f * math.cos(angle) k_i_cutbin = bisect.bisect(k_i, k_i_cutoff) counts.__delslice__(0, k_i_cutbin) counts_err2.__delslice__(0, k_i_cutbin) Q.__delslice__(0, k_i_cutbin) Q_err2.__delslice__(0, k_i_cutbin) E_t.__delslice__(0, k_i_cutbin) E_t_err2.__delslice__(0, k_i_cutbin) x_1.__delslice__(0, k_i_cutbin) x_2.__delslice__(0, k_i_cutbin) x_3.__delslice__(0, k_i_cutbin) x_4.__delslice__(0, k_i_cutbin) dT.__delslice__(0, k_i_cutbin) zero_vec.__delslice__(0, k_i_cutbin) try: if inst_name == "BSS": ((Q_1, E_t_1), (Q_2, E_t_2), (Q_3, E_t_3), (Q_4, E_t_4)) = dr_lib.calc_BSS_EQ_verticies((E_t, E_t_err2), (Q, Q_err2), x_1, x_2, x_3, x_4, dT, dh, zero_vec) else: raise RuntimeError("Do not know how to calculate (Q_i, "\ +"E_t_i) verticies for instrument %s" \ % inst_name) except IndexError: # All the data got Q filtered, move on continue try: (y_2d, y_2d_err2, area_new, bin_count_new) = axis_manip.rebin_2D_quad_to_rectlin(Q_1, E_t_1, Q_2, E_t_2, Q_3, E_t_3, Q_4, E_t_4, counts, counts_err2, so_dim.axis[0].val, so_dim.axis[1].val) except IndexError, e: # Get the offending index from the error message index = int(str(e).split()[1].split('index')[-1].strip('[]')) print "Id:", map_so.id print "Index:", index print "Verticies: %f, %f, %f, %f, %f, %f, %f, %f" % (Q_1[index], E_t_1[index], Q_2[index], E_t_2[index], Q_3[index], E_t_3[index], Q_4[index], E_t_4[index]) raise IndexError(str(e)) # Add in together with previous results (so_dim.y, so_dim.var_y) = array_manip.add_ncerr(so_dim.y, so_dim.var_y, y_2d, y_2d_err2) (area_sum, area_sum_err2) = array_manip.add_ncerr(area_sum, area_sum_err2, area_new, area_sum_err2) if configure.dump_pix_contrib or configure.scale_sqe: if inst_name == "BSS": dOmega = dr_lib.calc_BSS_solid_angle(map_so, inst) (bin_count_new, bin_count_err2) = array_manip.mult_ncerr(bin_count_new, bin_count_err2, dOmega, 0.0) (bin_count, bin_count_err2) = array_manip.add_ncerr(bin_count, bin_count_err2, bin_count_new, bin_count_err2) else: del bin_count_new
def tof_to_initial_wavelength_igs(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to initial_wavelength_igs. The time-of-flight axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(tof, tof_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(initial_wavelength_igs, initial_wavelength_igs_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword lambda_f:The final wavelength and its associated error^2 @type lambda_f: C{tuple} @keyword time_zero: The time zero offset and its associated error^2 @type time_zero: C{tuple} @keyword dist_source_sample: The source to sample distance information and its associated error^2 @type dist_source_sample: C{tuple} or C{list} of C{tuple}s @keyword dist_sample_detector: The sample to detector distance information and its associated error^2 @type dist_sample_detector: C{tuple} or C{list} of C{tuple}s @keyword run_filter: This determines if the filter on the negative wavelengths is run. The default setting is True. @type run_filter: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds} @type units: C{string} @return: Object with a primary axis in time-of-flight converted to initial_wavelength_igs @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: lambda_f = kwargs["lambda_f"] except KeyError: lambda_f = None try: time_zero = kwargs["time_zero"] except KeyError: time_zero = None try: dist_source_sample = kwargs["dist_source_sample"] except KeyError: dist_source_sample = None try: dist_sample_detector = kwargs["dist_sample_detector"] except KeyError: dist_sample_detector = None try: units = kwargs["units"] except KeyError: units = "microseconds" try: run_filter = kwargs["run_filter"] except KeyError: run_filter = True # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "Angstroms", axis) result.setAxisLabel(axis, "wavelength") result.setYUnits("Counts/A") result.setYLabel("Intensity") else: pass # Where to get instrument information if dist_source_sample is None or dist_sample_detector is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: if dist_source_sample is None and dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample and sample-detector "\ +"distances must be provided.") elif dist_source_sample is None: raise RuntimeError("If a SOM is not passed, the "\ +"source-sample distance must be provided.") elif dist_sample_detector is None: raise RuntimeError("If a SOM is not passed, the "\ +"sample-detector distance must be "\ +"provided.") else: raise RuntimeError("If you get here, see Steve Miller for "\ +"your mug.") else: pass if lambda_f is not None: l_descr = hlr_utils.get_descr(lambda_f) else: if o_descr == "SOM": try: som_l_f = obj.attr_list["Wavelength_final"] except KeyError: raise RuntimeError("Please provide a final wavelength "\ +"parameter either via the function call "\ +"or the SOM") else: raise RuntimeError("You need to provide a final wavelength") if time_zero is not None: t_descr = hlr_utils.get_descr(time_zero) else: if o_descr == "SOM": try: t_0 = obj.attr_list["Time_zero"][0] t_0_err2 = obj.attr_list["Time_zero"][1] except KeyError: raise RuntimeError("Please provide a time-zero "\ +"parameter either via the function call "\ +"or the SOM") else: t_0 = 0.0 t_0_err2 = 0.0 if dist_source_sample is not None: ls_descr = hlr_utils.get_descr(dist_source_sample) # Do nothing, go on else: pass if dist_sample_detector is not None: ld_descr = hlr_utils.get_descr(dist_sample_detector) # Do nothing, go on else: pass # iterate through the values import axis_manip for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if dist_source_sample is None: (L_s, L_s_err2) = hlr_utils.get_parameter("primary", map_so, inst) else: L_s = hlr_utils.get_value(dist_source_sample, i, ls_descr) L_s_err2 = hlr_utils.get_err2(dist_source_sample, i, ls_descr) if dist_sample_detector is None: (L_d, L_d_err2) = hlr_utils.get_parameter("secondary", map_so, inst) else: L_d = hlr_utils.get_value(dist_sample_detector, i, ld_descr) L_d_err2 = hlr_utils.get_err2(dist_sample_detector, i, ld_descr) if lambda_f is not None: l_f = hlr_utils.get_value(lambda_f, i, l_descr) l_f_err2 = hlr_utils.get_err2(lambda_f, i, l_descr) else: l_f_tuple = hlr_utils.get_special(som_l_f, map_so) l_f = l_f_tuple[0] l_f_err2 = l_f_tuple[1] if time_zero is not None: t_0 = hlr_utils.get_value(time_zero, i, t_descr) t_0_err2 = hlr_utils.get_err2(time_zero, i, t_descr) else: pass value = axis_manip.tof_to_initial_wavelength_igs(val, err2, l_f, l_f_err2, t_0, t_0_err2, L_s, L_s_err2, L_d, L_d_err2) # Remove all wavelengths < 0 if run_filter: index = 0 for val in value[0]: if val >= 0: break index += 1 value[0].__delslice__(0, index) value[1].__delslice__(0, index) map_so.y.__delslice__(0, index) map_so.var_y.__delslice__(0, index) else: pass hlr_utils.result_insert(result, res_descr, value, map_so, "x", axis) return result
def tof_to_wavelength_lin_time_zero(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to wavelength incorporating a linear time zero which is a described as a linear function of the wavelength. The time-of-flight axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(tof, tof_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(wavelength, wavelength_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword pathlength: The pathlength and its associated error^2 @type pathlength: C{tuple} or C{list} of C{tuple}s @keyword time_zero_slope: The time zero slope and its associated error^2 @type time_zero_slope: C{tuple} @keyword time_zero_offset: The time zero offset and its associated error^2 @type time_zero_offset: C{tuple} @keyword inst_param: The type of parameter requested from an associated instrument. For this function the acceptable parameters are I{primary}, I{secondary} and I{total}. Default is I{primary}. @type inst_param: C{string} @keyword lojac: A flag that allows one to turn off the calculation of the linear-order Jacobian. The default action is I{True} for histogram data. @type lojac: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds}. @type units: C{string} @keyword cut_val: Specify a wavelength to cut the spectra at. @type cut_val: C{float} @keyword cut_less: A flag that specifies cutting the spectra less than C{cut_val}. The default is C{True}. @type cut_less: C{boolean} @return: Object with a primary axis in time-of-flight converted to wavelength @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} @raise RuntimeError: A C{SOM} does not contain an instrument and no pathlength was provided @raise RuntimeError: No C{SOM} is provided and no pathlength given """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: inst_param = kwargs["inst_param"] except KeyError: inst_param = "primary" try: pathlength = kwargs["pathlength"] except KeyError: pathlength = None try: time_zero_slope = kwargs["time_zero_slope"] except KeyError: time_zero_slope = None # Current constants for Time Zero Slope TIME_ZERO_SLOPE = (float(0.0), float(0.0)) try: time_zero_offset = kwargs["time_zero_offset"] except KeyError: time_zero_offset = None # Current constants for Time Zero Offset TIME_ZERO_OFFSET = (float(0.0), float(0.0)) try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) try: units = kwargs["units"] except KeyError: units = "microseconds" try: cut_val = kwargs["cut_val"] except KeyError: cut_val = None try: cut_less = kwargs["cut_less"] except KeyError: cut_less = True # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "Angstroms", axis) result.setAxisLabel(axis, "wavelength") result.setYUnits("Counts/A") result.setYLabel("Intensity") else: pass if pathlength is not None: p_descr = hlr_utils.get_descr(pathlength) else: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided") else: raise RuntimeError("If no SOM is provided, then pathlength "\ +"information must be provided") if time_zero_slope is not None: t_0_slope_descr = hlr_utils.get_descr(time_zero_slope) else: if o_descr == "SOM": try: t_0_slope = obj.attr_list["Time_zero_slope"][0] t_0_slope_err2 = obj.attr_list["Time_zero_slope"][1] except KeyError: t_0_slope = TIME_ZERO_SLOPE[0] t_0_slope_err2 = TIME_ZERO_SLOPE[1] else: t_0_slope = TIME_ZERO_SLOPE[0] t_0_slope_err2 = TIME_ZERO_SLOPE[1] if time_zero_offset is not None: t_0_offset_descr = hlr_utils.get_descr(time_zero_offset) else: if o_descr == "SOM": try: t_0_offset = obj.attr_list["Time_zero_offset"][0] t_0_offset_err2 = obj.attr_list["Time_zero_offset"][1] except KeyError: t_0_offset = TIME_ZERO_OFFSET[0] t_0_offset_err2 = TIME_ZERO_OFFSET[1] else: t_0_offset = TIME_ZERO_OFFSET[0] t_0_offset_err2 = TIME_ZERO_OFFSET[1] # iterate through the values import axis_manip if lojac or cut_val is not None: import utils for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if pathlength is None: (pl, pl_err2) = hlr_utils.get_parameter(inst_param, map_so, inst) else: pl = hlr_utils.get_value(pathlength, i, p_descr) pl_err2 = hlr_utils.get_err2(pathlength, i, p_descr) if time_zero_slope is not None: t_0_slope = hlr_utils.get_value(time_zero_slope, i, t_0_slope_descr) t_0_slope_err2 = hlr_utils.get_err2(time_zero_slope, i, t_0_slope_descr) else: pass if time_zero_offset is not None: t_0_offset = hlr_utils.get_value(time_zero_offset, i, t_0_offset_descr) t_0_offset_err2 = hlr_utils.get_err2(time_zero_offset, i, t_0_offset_descr) else: pass value = axis_manip.tof_to_wavelength_lin_time_zero(val, err2, pl, pl_err2, t_0_slope, t_0_slope_err2, t_0_offset, t_0_offset_err2) if cut_val is not None: index = utils.bisect_helper(value[0], cut_val) if cut_less: # Need to cut at this index, so increment by one index += 1 value[0].__delslice__(0, index) value[1].__delslice__(0, index) map_so.y.__delslice__(0, index) map_so.var_y.__delslice__(0, index) if lojac: val.__delslice__(0, index) err2.__delslice__(0, index) else: len_data = len(value[0]) # All axis arrays need starting index adjusted by one since # they always carry one more bin than the data value[0].__delslice__(index + 1, len_data) value[1].__delslice__(index + 1, len_data) map_so.y.__delslice__(index, len_data) map_so.var_y.__delslice__(index, len_data) if lojac: val.__delslice__(index + 1, len_data) err2.__delslice__(index + 1, len_data) if lojac: counts = utils.linear_order_jacobian(val, value[0], map_so.y, map_so.var_y) hlr_utils.result_insert(result, res_descr, counts, map_so, "all", axis, [value[0]]) else: hlr_utils.result_insert(result, res_descr, value, map_so, "x", axis) return result
def calc_BSS_coeffs(map_so, inst, *args): """ This function calculates the x_i coefficients for the BSS instrument @param map_so: The spectrum object to calculate the coefficients for @type map_so: C{SOM.SO} @param inst: The instrument object associated with the data @type inst: C{SOM.Instrument} or C{SOM.CompositeInstrument} @param args: A list of parameters (C{tuple}s with value and err^2) used to calculate the x_i coefficients The following is a list of the arguments needed in there expected order 1. Initial Energy 2. Momentum Transfer 3. Initial Wavevector 4. Initial Time-of-Flight 5. Detector Pixel Height 6. Polar Angle 7. Final Energy 8. Final Wavevector 9. Final Wavelength 10. Source to Sample Distance 11. Sample to Detector Distance 12. Time-zero Slope 13. Vector of Zeros @type args: C{list} @return: The calculated coefficients (x_1, x_2, x_3, x_4) @rtype: C{tuple} of 4 C{nessi_list.NessiList}s """ import math # Settle out the arguments to sensible names E_i = args[0][0] E_i_err2 = args[0][1] Q = args[1][0] Q_err2 = args[1][1] k_i = args[2][0] k_i_err2 = args[2][1] T_i = args[3][0] T_i_err2 = args[3][1] dh = args[4] polar_angle = args[5] E_f = args[6] k_f = args[7] l_f = args[8] L_s = args[9] L_d = args[10] T_0_s = args[11] zero_vec = args[12] # Constant h/m_n (meters / microsecond) H_OVER_MNEUT = 0.003956034e-10 # Get the differential geometry parameters dlf_dh_tuple = hlr_utils.get_parameter("dlf_dh", map_so, inst) dlf_dh = dlf_dh_tuple[0] # dlf_dh should be unitless (Angstrom/Angstrom) dlf_dh *= 1e-10 dpol_dh_tuple = hlr_utils.get_parameter("dpol_dh", map_so, inst) dpol_dh = dpol_dh_tuple[0] # Convert to radian/Angstrom dpol_dh *= 1e-10 dpol_dtd_tuple = hlr_utils.get_parameter("dpol_dtd", map_so, inst) dpol_dtd = dpol_dtd_tuple[0] # Get the detector pixel angular width dtd_tuple = hlr_utils.get_parameter("dtd", map_so, inst) dtd = dtd_tuple[0] # Calculate bin centric values E_i_bc_tuple = utils.calc_bin_centers(E_i, E_i_err2) E_i_bc = E_i_bc_tuple[0] k_i_bc_tuple = utils.calc_bin_centers(k_i, k_i_err2) k_i_bc = k_i_bc_tuple[0] Q_bc_tuple = utils.calc_bin_centers(Q, Q_err2) Q_bc = Q_bc_tuple[0] T_i_bc_tuple = utils.calc_bin_centers(T_i, T_i_err2) T_i_bc = T_i_bc_tuple[0] # Get numeric values sin_polar = math.sin(polar_angle) cos_polar = math.cos(polar_angle) length_ratio = L_d / L_s lambda_const = ((2.0 * math.pi) / (l_f * l_f)) * dlf_dh kf_cos_pol = k_f * cos_polar kf_sin_pol = k_f * sin_polar t0_slope_corr = 1.0 / (1.0 + H_OVER_MNEUT * (T_0_s / L_s)) dtd_over_dh = dtd / dh # Calculate coefficients x_1_tuple = __calc_x1( k_i_bc, Q_bc, length_ratio, k_f, kf_cos_pol, kf_sin_pol, lambda_const, dpol_dh, dpol_dtd, dtd_over_dh, cos_polar, t0_slope_corr, zero_vec, ) x_1 = x_1_tuple[0] x_2_tuple = __calc_x2(k_i_bc, Q_bc, T_i_bc, kf_cos_pol, t0_slope_corr, zero_vec) x_2 = x_2_tuple[0] x_3_tuple = __calc_x3(k_i_bc, E_i_bc, length_ratio, E_f, k_f, lambda_const, t0_slope_corr, zero_vec) x_3 = x_3_tuple[0] x_4_tuple = __calc_x4(E_i_bc, T_i_bc, t0_slope_corr, zero_vec) x_4 = x_4_tuple[0] return (x_1, x_2, x_3, x_4)
def tof_to_wavelength(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to wavelength. The wavelength axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(tof, tof_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(wavelength, wavelength_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword pathlength: The pathlength and its associated error^2 @type pathlength: C{tuple} or C{list} of C{tuple}s @keyword inst_param: The type of parameter requested from an associated instrument. For this function the acceptable parameters are I{primary}, I{secondary} and I{total}. Default is I{primary}. @type inst_param: C{string} @keyword lojac: A flag that allows one to turn off the calculation of the linear-order Jacobian. The default action is I{True} for histogram data. @type lojac: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds}. @type units: C{string} @return: Object with a primary axis in time-of-flight converted to wavelength @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} @raise RuntimeError: A C{SOM} does not contain an instrument and no pathlength was provided @raise RuntimeError: No C{SOM} is provided and no pathlength given """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) # Setup keyword arguments try: inst_param = kwargs["inst_param"] except KeyError: inst_param = "primary" try: pathlength = kwargs["pathlength"] except KeyError: pathlength = None try: units = kwargs["units"] except KeyError: units = "microseconds" try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "Angstroms", axis) result.setAxisLabel(axis, "wavelength") result.setYUnits("Counts/A") result.setYLabel("Intensity") else: pass if pathlength is not None: p_descr = hlr_utils.get_descr(pathlength) else: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided") else: raise RuntimeError("If no SOM is provided, then pathlength "\ +"information must be provided") # iterate through the values import axis_manip if lojac: import utils for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if pathlength is None: (pl, pl_err2) = hlr_utils.get_parameter(inst_param, map_so, inst) else: pl = hlr_utils.get_value(pathlength, i, p_descr) pl_err2 = hlr_utils.get_err2(pathlength, i, p_descr) value = axis_manip.tof_to_wavelength(val, err2, pl, pl_err2) if lojac: y_val = hlr_utils.get_value(obj, i, o_descr, "y") y_err2 = hlr_utils.get_err2(obj, i, o_descr, "y") counts = utils.linear_order_jacobian(val, value[0], y_val, y_err2) hlr_utils.result_insert(result, res_descr, counts, map_so, "all", axis, [value[0]]) else: hlr_utils.result_insert(result, res_descr, value, map_so, "x", axis) return result
def wavelength_to_scalar_Q(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from wavelength to scalar Q. The wavelength axis for a C{SOM} must be in units of I{Angstroms}. The primary axis of a C{SO} is assumed to be in units of I{Angstroms}. A C{tuple} of C{(wavelength, wavelength_err2)} (assumed to be in units of I{Angstroms}) can be converted to C{(scalar_Q, scalar_Q_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword polar: The polar angle and its associated error^2 @type polar: C{tuple} or C{list} of C{tuple}s @keyword pathlength: The pathlength and its associated error^2 @type pathlength: C{tuple} or C{list} of C{tuple}s @keyword units: The expected units for this function. The default for this function is I{Angstroms}. @type units: C{string} @return: Object with a primary axis in wavelength converted to scalar Q @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: A C{SOM} is not passed and no polar angle is provided @raise RuntimeError: The C{SOM} x-axis units are not I{Angstroms} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) if o_descr == "list": raise TypeError("Do not know how to handle given type: %s" % \ o_descr) else: pass # Setup keyword arguments try: polar = kwargs["polar"] except KeyError: polar = None try: units = kwargs["units"] except KeyError: units = "Angstroms" try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "1/Angstroms", axis) result.setAxisLabel(axis, "scalar wavevector transfer") result.setYUnits("Counts/A-1") result.setYLabel("Intensity") else: pass if polar is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: raise RuntimeError("If no SOM is provided, then polar "\ +"information must be given.") else: p_descr = hlr_utils.get_descr(polar) # iterate through the values import axis_manip if lojac: import utils for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if polar is None: (angle, angle_err2) = hlr_utils.get_parameter("polar", map_so, inst) else: angle = hlr_utils.get_value(polar, i, p_descr) angle_err2 = hlr_utils.get_err2(polar, i, p_descr) value = axis_manip.wavelength_to_scalar_Q(val, err2, angle, angle_err2) if lojac: y_val = hlr_utils.get_value(obj, i, o_descr, "y") y_err2 = hlr_utils.get_err2(obj, i, o_descr, "y") counts = utils.linear_order_jacobian(val, value[0], y_val, y_err2) else: pass if o_descr != "number": value1 = axis_manip.reverse_array_cp(value[0]) value2 = axis_manip.reverse_array_cp(value[1]) rev_value = (value1, value2) else: rev_value = value if map_so is not None: if not lojac: map_so.y = axis_manip.reverse_array_cp(map_so.y) map_so.var_y = axis_manip.reverse_array_cp(map_so.var_y) else: map_so.y = axis_manip.reverse_array_cp(counts[0]) map_so.var_y = axis_manip.reverse_array_cp(counts[1]) else: pass hlr_utils.result_insert(result, res_descr, rev_value, map_so, "x", axis) return result
def convert_single_to_list(funcname, number, som, **kwargs): """ This function retrieves a function object from the L{common_lib} set of functions that provide axis transformations and converts the provided number based on that function. Instrument geometry information needs to be provided via the C{SOM}. The following is the list of functions supported by this one. - d_spacing_to_tof_focused_det - energy_to_wavelength - frequency_to_energy - initial_wavelength_igs_lin_time_zero_to_tof - init_scatt_wavevector_to_scalar_Q - tof_to_initial_wavelength_igs_lin_time_zero - tof_to_initial_wavelength_igs - tof_to_scalar_Q - tof_to_wavelength_lin_time_zero - tof_to_wavelength - wavelength_to_d_spacing - wavelength_to_energy - wavelength_to_scalar_k - wavelength_to_scalar_Q @param funcname: The name of the axis conversion function to use @type funcname: C{string} @param number: The value and error^2 to convert @type number: C{tuple} @param som: The object containing geometry and other special information @type som: C{SOM.SOM} @param kwargs: A list of keyword arguments that the function accepts: @keyword inst_param: The type of parameter requested from an associated instrument. For this function the acceptable parameters are I{primary}, I{secondary} and I{total}. Default is I{primary}. @type inst_param: C{string} @keyword pixel_id: The pixel ID from which the geometry information will be retrieved from the instrument @type pixel_id: C{tuple}=(\"bankN\", (x, y)) @return: A converted number for every unique spectrum @rtype: C{list} of C{tuple}s @raise AttributeError: The requested function is not in the approved list """ # Setup supported function list and check to see if funcname is available function_list = [] function_list.append("d_spacing_to_tof_focused_det") function_list.append("energy_to_wavelength") function_list.append("frequency_to_energy") function_list.append("initial_wavelength_igs_lin_time_zero_to_tof") function_list.append("init_scatt_wavevector_to_scalar_Q") function_list.append("tof_to_initial_wavelength_igs_lin_time_zero") function_list.append("tof_to_initial_wavelength_igs") function_list.append("tof_to_scalar_Q") function_list.append("tof_to_wavelength_lin_time_zero") function_list.append("tof_to_wavelength") function_list.append("wavelength_to_d_spacing") function_list.append("wavelength_to_energy") function_list.append("wavelength_to_scalar_k") function_list.append("wavelength_to_scalar_Q") if funcname not in function_list: raise AttributeError("Function %s is not supported by "\ +"convert_single_to_list" % funcname) import common_lib # Get the common_lib function object func = common_lib.__getattribute__(funcname) # Setup inclusive dictionary containing the requested keywords for all # common_lib axis conversion functions fkwds = {} fkwds["pathlength"] = () fkwds["polar"] = () fkwds["lambda_f"] = () try: lambda_final = som.attr_list["Wavelength_final"] except KeyError: lambda_final = None try: fkwds["time_zero_slope"] = som.attr_list["Time_zero_slope"] except KeyError: pass try: fkwds["time_zero_offset"] = som.attr_list["Time_zero_offset"] except KeyError: pass try: fkwds["time_zero"] = som.attr_list["Time_zero"] except KeyError: pass fkwds["dist_source_sample"] = () fkwds["dist_sample_detector"] = () try: fkwds["inst_param"] = kwargs["inst_param"] except KeyError: fkwds["inst_param"] = "primary" try: fkwds["pixel_id"] = kwargs["pixel_id"] except KeyError: fkwds["pixel_id"] = None fkwds["run_filter"] = False # Set up for working through data # This time highest object in the hierarchy is NOT what we need result = [] res_descr = "list" inst = som.attr_list.instrument import hlr_utils # iterate through the values for i in xrange(hlr_utils.get_length(som)): map_so = hlr_utils.get_map_so(som, None, i) fkwds["pathlength"] = hlr_utils.get_parameter(fkwds["inst_param"], map_so, inst) fkwds["dist_source_sample"] = hlr_utils.get_parameter("primary", map_so, inst) fkwds["dist_sample_detector"] = hlr_utils.get_parameter("secondary", map_so, inst) fkwds["polar"] = hlr_utils.get_parameter("polar", map_so, inst) fkwds["lambda_f"] = hlr_utils.get_special(lambda_final, map_so) value = tuple(func(number, **fkwds)) hlr_utils.result_insert(result, res_descr, value, None, "all") return result
def apply_sas_correct(obj): """ This function applies the following corrections to SAS TOF data: - Multiply counts by the following formula: (sin(polar) * cos(polar)) / (1 + tan^2(polar)) @param obj: The data to apply the corrections to @type obj: C{SOM.SOM} or C{SOM.SO} @return: The data after corrections have been applied @rtype: C{SOM.SOM} or C{SOM.SO} @raise TypeError: The object being rebinned is not a C{SOM} or a C{SO} """ # import the helper functions import hlr_utils # set up for working through data o_descr = hlr_utils.get_descr(obj) if o_descr == "number" or o_descr == "list": raise TypeError("Do not know how to handle given type: %s" % \ o_descr) else: pass if o_descr == "SOM": inst = obj.attr_list.instrument else: inst = None (result, res_descr) = hlr_utils.empty_result(obj) result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) # iterate through the values import array_manip import math len_obj = hlr_utils.get_length(obj) for i in xrange(len_obj): val = hlr_utils.get_value(obj, i, o_descr, "y") err2 = hlr_utils.get_err2(obj, i, o_descr, "y") map_so = hlr_utils.get_map_so(obj, None, i) polar = hlr_utils.get_parameter("polar", map_so, inst) sin_pol = math.sin(polar[0]) cos_pol = math.cos(polar[0]) tan_pol = math.tan(polar[0]) scale = (sin_pol * cos_pol) / (1.0 + (tan_pol * tan_pol)) value = array_manip.mult_ncerr(val, err2, scale, 0.0) hlr_utils.result_insert(result, res_descr, value, map_so, "y") return result
def create_E_vs_Q_igs(som, *args, **kwargs): """ This function starts with the initial IGS wavelength axis and turns this into a 2D spectra with E and Q axes. @param som: The input object with initial IGS wavelength axis @type som: C{SOM.SOM} @param args: A mandatory list of axes for rebinning. There is a particular order to them. They should be present in the following order: Without errors 1. Energy transfer 2. Momentum transfer With errors 1. Energy transfer 2. Energy transfer error^2 3. Momentum transfer 4. Momentum transfer error ^2 @type args: C{nessi_list.NessiList}s @param kwargs: A list of keyword arguments that the function accepts: @keyword withXVar: Flag for whether the function should be expecting the associated axes to have errors. The default value will be I{False}. @type withXVar: C{boolean} @keyword data_type: Name of the data type which can be either I{histogram}, I{density} or I{coordinate}. The default value will be I{histogram} @type data_type: C{string} @keyword Q_filter: Flag to turn on or off Q filtering. The default behavior is I{True}. @type Q_filter: C{boolean} @keyword so_id: The identifier represents a number, string, tuple or other object that describes the resulting C{SO} @type so_id: C{int}, C{string}, C{tuple}, C{pixel ID} @keyword y_label: The y axis label @type y_label: C{string} @keyword y_units: The y axis units @type y_units: C{string} @keyword x_labels: This is a list of names that sets the individual x axis labels @type x_labels: C{list} of C{string}s @keyword x_units: This is a list of names that sets the individual x axis units @type x_units: C{list} of C{string}s @keyword split: This flag causes the counts and the fractional area to be written out into separate files. @type split: C{boolean} @keyword configure: This is the object containing the driver configuration. @type configure: C{Configure} @return: Object containing a 2D C{SO} with E and Q axes @rtype: C{SOM.SOM} @raise RuntimeError: Anything other than a C{SOM} is passed to the function @raise RuntimeError: An instrument is not contained in the C{SOM} """ import nessi_list # Setup some variables dim = 2 N_y = [] N_tot = 1 N_args = len(args) # Get T0 slope in order to calculate dT = dT_i + dT_0 try: t_0_slope = som.attr_list["Time_zero_slope"][0] t_0_slope_err2 = som.attr_list["Time_zero_slope"][1] except KeyError: t_0_slope = float(0.0) t_0_slope_err2 = float(0.0) # Check withXVar keyword argument and also check number of given args. # Set xvar to the appropriate value try: value = kwargs["withXVar"] if value.lower() == "true": if N_args != 4: raise RuntimeError("Since you have requested x errors, 4 x "\ +"axes must be provided.") else: xvar = True elif value.lower() == "false": if N_args != 2: raise RuntimeError("Since you did not requested x errors, 2 "\ +"x axes must be provided.") else: xvar = False else: raise RuntimeError("Do not understand given parameter %s" % \ value) except KeyError: if N_args != 2: raise RuntimeError("Since you did not requested x errors, 2 "\ +"x axes must be provided.") else: xvar = False # Check dataType keyword argument. An offset will be set to 1 for the # histogram type and 0 for either density or coordinate try: data_type = kwargs["data_type"] if data_type.lower() == "histogram": offset = 1 elif data_type.lower() == "density" or \ data_type.lower() == "coordinate": offset = 0 else: raise RuntimeError("Do not understand data type given: %s" % \ data_type) # Default is offset for histogram except KeyError: offset = 1 try: Q_filter = kwargs["Q_filter"] except KeyError: Q_filter = True # Check for split keyword try: split = kwargs["split"] except KeyError: split = False # Check for configure keyword try: configure = kwargs["configure"] except KeyError: configure = None so_dim = SOM.SO(dim) for i in range(dim): # Set the x-axis arguments from the *args list into the new SO if not xvar: # Axis positions are 1 (Q) and 0 (E) position = dim - i - 1 so_dim.axis[i].val = args[position] else: # Axis positions are 2 (Q), 3 (eQ), 0 (E), 1 (eE) position = dim - 2 * i so_dim.axis[i].val = args[position] so_dim.axis[i].var = args[position + 1] # Set individual value axis sizes (not x-axis size) N_y.append(len(args[position]) - offset) # Calculate total 2D array size N_tot = N_tot * N_y[-1] # Create y and var_y lists from total 2D size so_dim.y = nessi_list.NessiList(N_tot) so_dim.var_y = nessi_list.NessiList(N_tot) # Create area sum and errors for the area sum lists from total 2D size area_sum = nessi_list.NessiList(N_tot) area_sum_err2 = nessi_list.NessiList(N_tot) # Create area sum and errors for the area sum lists from total 2D size bin_count = nessi_list.NessiList(N_tot) bin_count_err2 = nessi_list.NessiList(N_tot) inst = som.attr_list.instrument lambda_final = som.attr_list["Wavelength_final"] inst_name = inst.get_name() import bisect import math import dr_lib import utils arr_len = 0 #: Vector of zeros for function calculations zero_vec = None for j in xrange(hlr_utils.get_length(som)): # Get counts counts = hlr_utils.get_value(som, j, "SOM", "y") counts_err2 = hlr_utils.get_err2(som, j, "SOM", "y") arr_len = len(counts) zero_vec = nessi_list.NessiList(arr_len) # Get mapping SO map_so = hlr_utils.get_map_so(som, None, j) # Get lambda_i l_i = hlr_utils.get_value(som, j, "SOM", "x") l_i_err2 = hlr_utils.get_err2(som, j, "SOM", "x") # Get lambda_f from instrument information l_f_tuple = hlr_utils.get_special(lambda_final, map_so) l_f = l_f_tuple[0] l_f_err2 = l_f_tuple[1] # Get source to sample distance (L_s, L_s_err2) = hlr_utils.get_parameter("primary", map_so, inst) # Get sample to detector distance L_d_tuple = hlr_utils.get_parameter("secondary", map_so, inst) L_d = L_d_tuple[0] # Get polar angle from instrument information (angle, angle_err2) = hlr_utils.get_parameter("polar", map_so, inst) # Get the detector pixel height dh_tuple = hlr_utils.get_parameter("dh", map_so, inst) dh = dh_tuple[0] # Need dh in units of Angstrom dh *= 1e10 # Calculate T_i (T_i, T_i_err2) = axis_manip.wavelength_to_tof(l_i, l_i_err2, L_s, L_s_err2) # Scale counts by lambda_f / lambda_i (l_i_bc, l_i_bc_err2) = utils.calc_bin_centers(l_i, l_i_err2) (ratio, ratio_err2) = array_manip.div_ncerr(l_f, l_f_err2, l_i_bc, l_i_bc_err2) (counts, counts_err2) = array_manip.mult_ncerr(counts, counts_err2, ratio, ratio_err2) # Calculate E_i (E_i, E_i_err2) = axis_manip.wavelength_to_energy(l_i, l_i_err2) # Calculate E_f (E_f, E_f_err2) = axis_manip.wavelength_to_energy(l_f, l_f_err2) # Calculate E_t (E_t, E_t_err2) = array_manip.sub_ncerr(E_i, E_i_err2, E_f, E_f_err2) if inst_name == "BSS": # Convert E_t from meV to ueV (E_t, E_t_err2) = array_manip.mult_ncerr(E_t, E_t_err2, 1000.0, 0.0) (counts, counts_err2) = array_manip.mult_ncerr(counts, counts_err2, 1.0 / 1000.0, 0.0) # Convert lambda_i to k_i (k_i, k_i_err2) = axis_manip.wavelength_to_scalar_k(l_i, l_i_err2) # Convert lambda_f to k_f (k_f, k_f_err2) = axis_manip.wavelength_to_scalar_k(l_f, l_f_err2) # Convert k_i and k_f to Q (Q, Q_err2) = axis_manip.init_scatt_wavevector_to_scalar_Q( k_i, k_i_err2, k_f, k_f_err2, angle, angle_err2) # Calculate dT = dT_0 + dT_i dT_i = utils.calc_bin_widths(T_i, T_i_err2) (l_i_bw, l_i_bw_err2) = utils.calc_bin_widths(l_i, l_i_err2) dT_0 = array_manip.mult_ncerr(l_i_bw, l_i_bw_err2, t_0_slope, t_0_slope_err2) dT_tuple = array_manip.add_ncerr(dT_i[0], dT_i[1], dT_0[0], dT_0[1]) dT = dT_tuple[0] # Calculate Jacobian if inst_name == "BSS": (x_1, x_2, x_3, x_4) = dr_lib.calc_BSS_coeffs( map_so, inst, (E_i, E_i_err2), (Q, Q_err2), (k_i, k_i_err2), (T_i, T_i_err2), dh, angle, E_f, k_f, l_f, L_s, L_d, t_0_slope, zero_vec) else: raise RuntimeError("Do not know how to calculate x_i "\ +"coefficients for instrument %s" % inst_name) (A, A_err2) = dr_lib.calc_EQ_Jacobian(x_1, x_2, x_3, x_4, dT, dh, zero_vec) # Apply Jacobian: C/dlam * dlam / A(EQ) = C/EQ (jac_ratio, jac_ratio_err2) = array_manip.div_ncerr(l_i_bw, l_i_bw_err2, A, A_err2) (counts, counts_err2) = array_manip.mult_ncerr(counts, counts_err2, jac_ratio, jac_ratio_err2) # Reverse counts, E_t, k_i and Q E_t = axis_manip.reverse_array_cp(E_t) E_t_err2 = axis_manip.reverse_array_cp(E_t_err2) Q = axis_manip.reverse_array_cp(Q) Q_err2 = axis_manip.reverse_array_cp(Q_err2) counts = axis_manip.reverse_array_cp(counts) counts_err2 = axis_manip.reverse_array_cp(counts_err2) k_i = axis_manip.reverse_array_cp(k_i) x_1 = axis_manip.reverse_array_cp(x_1) x_2 = axis_manip.reverse_array_cp(x_2) x_3 = axis_manip.reverse_array_cp(x_3) x_4 = axis_manip.reverse_array_cp(x_4) dT = axis_manip.reverse_array_cp(dT) # Filter for duplicate Q values if Q_filter: k_i_cutoff = k_f * math.cos(angle) k_i_cutbin = bisect.bisect(k_i, k_i_cutoff) counts.__delslice__(0, k_i_cutbin) counts_err2.__delslice__(0, k_i_cutbin) Q.__delslice__(0, k_i_cutbin) Q_err2.__delslice__(0, k_i_cutbin) E_t.__delslice__(0, k_i_cutbin) E_t_err2.__delslice__(0, k_i_cutbin) x_1.__delslice__(0, k_i_cutbin) x_2.__delslice__(0, k_i_cutbin) x_3.__delslice__(0, k_i_cutbin) x_4.__delslice__(0, k_i_cutbin) dT.__delslice__(0, k_i_cutbin) zero_vec.__delslice__(0, k_i_cutbin) try: if inst_name == "BSS": ((Q_1, E_t_1), (Q_2, E_t_2), (Q_3, E_t_3), (Q_4, E_t_4)) = dr_lib.calc_BSS_EQ_verticies( (E_t, E_t_err2), (Q, Q_err2), x_1, x_2, x_3, x_4, dT, dh, zero_vec) else: raise RuntimeError("Do not know how to calculate (Q_i, "\ +"E_t_i) verticies for instrument %s" \ % inst_name) except IndexError: # All the data got Q filtered, move on continue try: (y_2d, y_2d_err2, area_new, bin_count_new) = axis_manip.rebin_2D_quad_to_rectlin( Q_1, E_t_1, Q_2, E_t_2, Q_3, E_t_3, Q_4, E_t_4, counts, counts_err2, so_dim.axis[0].val, so_dim.axis[1].val) except IndexError, e: # Get the offending index from the error message index = int(str(e).split()[1].split('index')[-1].strip('[]')) print "Id:", map_so.id print "Index:", index print "Verticies: %f, %f, %f, %f, %f, %f, %f, %f" % ( Q_1[index], E_t_1[index], Q_2[index], E_t_2[index], Q_3[index], E_t_3[index], Q_4[index], E_t_4[index]) raise IndexError(str(e)) # Add in together with previous results (so_dim.y, so_dim.var_y) = array_manip.add_ncerr(so_dim.y, so_dim.var_y, y_2d, y_2d_err2) (area_sum, area_sum_err2) = array_manip.add_ncerr(area_sum, area_sum_err2, area_new, area_sum_err2) if configure.dump_pix_contrib or configure.scale_sqe: if inst_name == "BSS": dOmega = dr_lib.calc_BSS_solid_angle(map_so, inst) (bin_count_new, bin_count_err2) = array_manip.mult_ncerr( bin_count_new, bin_count_err2, dOmega, 0.0) (bin_count, bin_count_err2) = array_manip.add_ncerr( bin_count, bin_count_err2, bin_count_new, bin_count_err2) else: del bin_count_new
def init_scatt_wavevector_to_scalar_Q(initk, scattk, **kwargs): """ This function takes an initial wavevector and a scattered wavevector as a C{tuple} and a C{SOM}, a C{tuple} and a C{SO} or two C{tuple}s and calculates the quantity scalar Q units of I{1/Angstroms}. The C{SOM} principle axis must be in units of I{1/Angstroms}. The C{SO}s and C{tuple}(s) is(are) assumed to be in units of I{1/Angstroms}. The polar angle must be provided if one of the initial arguments is not a C{SOM}. If a C{SOM} is passed, by providing the polar angle at the function call time, the polar angle carried in the C{SOM} instrument will be overridden. @param initk: Object holding the initial wavevector @type initk: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param scattk: Object holding the scattered wavevector @type scattk: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword polar: The polar angle and its associated error^2 @type polar: C{tuple} or C{list} of C{tuple}s @keyword units: The expected units for this function. The default for this function is I{1/Angstroms}. @type units: C{string} @return: Object converted to scalar Q @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The C{SOM}-C{SOM} operation is attempted @raise TypeError: The C{SOM}-C{SO} operation is attempted @raise TypeError: The C{SO}-C{SOM} operation is attempted @raise TypeError: The C{SO}-C{SO} operation is attempted @raise RuntimeError: The C{SOM} x-axis units are not I{1/Angstroms} @raise RuntimeError: A C{SOM} is not passed and no polar angle is provided @raise RuntimeError: No C{SOM.Instrument} is provided in a C{SOM} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(initk, scattk) (i_descr, s_descr) = hlr_utils.get_descr(initk, scattk) # error checking for types if i_descr == "SOM" and s_descr == "SOM": raise TypeError("SOM-SOM operation not supported") elif i_descr == "SOM" and s_descr == "SO": raise TypeError("SOM-SO operation not supported") elif i_descr == "SO" and s_descr == "SOM": raise TypeError("SO-SOM operation not supported") elif i_descr == "SO" and s_descr == "SO": raise TypeError("SO-SO operation not supported") else: pass # Setup keyword arguments try: polar = kwargs["polar"] except KeyError: polar = None try: units = kwargs["units"] except KeyError: units = "1/Angstroms" result = hlr_utils.copy_som_attr(result, res_descr, initk, i_descr, scattk, s_descr) if res_descr == "SOM": index = hlr_utils.one_d_units(result, units) result = hlr_utils.force_units(result, units, index) result.setAxisLabel(index, "scalar wavevector transfer") result.setYUnits("Counts/A-1") result.setYLabel("Intensity") else: pass if polar is None: if i_descr == "SOM": try: initk.attr_list.instrument.get_primary() inst = initk.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") elif s_descr == "SOM": try: scattk.attr_list.instrument.get_primary() inst = scattk.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: raise RuntimeError("If no SOM is provided, then polar "\ +"information must be given.") else: p_descr = hlr_utils.get_descr(polar) # iterate through the values import axis_manip for i in xrange(hlr_utils.get_length(initk, scattk)): val1 = hlr_utils.get_value(initk, i, i_descr, "x") err2_1 = hlr_utils.get_err2(initk, i, i_descr, "x") val2 = hlr_utils.get_value(scattk, i, s_descr, "x") err2_2 = hlr_utils.get_err2(scattk, i, s_descr, "x") map_so = hlr_utils.get_map_so(initk, scattk, i) if polar is None: (angle, angle_err2) = hlr_utils.get_parameter("polar", map_so, inst) else: angle = hlr_utils.get_value(polar, i, p_descr) angle_err2 = hlr_utils.get_err2(polar, i, p_descr) value = axis_manip.init_scatt_wavevector_to_scalar_Q( val1, err2_1, val2, err2_2, angle, angle_err2) hlr_utils.result_insert(result, res_descr, value, map_so, "x") return result
def init_scatt_wavevector_to_scalar_Q(initk, scattk, **kwargs): """ This function takes an initial wavevector and a scattered wavevector as a C{tuple} and a C{SOM}, a C{tuple} and a C{SO} or two C{tuple}s and calculates the quantity scalar Q units of I{1/Angstroms}. The C{SOM} principle axis must be in units of I{1/Angstroms}. The C{SO}s and C{tuple}(s) is(are) assumed to be in units of I{1/Angstroms}. The polar angle must be provided if one of the initial arguments is not a C{SOM}. If a C{SOM} is passed, by providing the polar angle at the function call time, the polar angle carried in the C{SOM} instrument will be overridden. @param initk: Object holding the initial wavevector @type initk: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param scattk: Object holding the scattered wavevector @type scattk: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword polar: The polar angle and its associated error^2 @type polar: C{tuple} or C{list} of C{tuple}s @keyword units: The expected units for this function. The default for this function is I{1/Angstroms}. @type units: C{string} @return: Object converted to scalar Q @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The C{SOM}-C{SOM} operation is attempted @raise TypeError: The C{SOM}-C{SO} operation is attempted @raise TypeError: The C{SO}-C{SOM} operation is attempted @raise TypeError: The C{SO}-C{SO} operation is attempted @raise RuntimeError: The C{SOM} x-axis units are not I{1/Angstroms} @raise RuntimeError: A C{SOM} is not passed and no polar angle is provided @raise RuntimeError: No C{SOM.Instrument} is provided in a C{SOM} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(initk, scattk) (i_descr, s_descr) = hlr_utils.get_descr(initk, scattk) # error checking for types if i_descr == "SOM" and s_descr == "SOM": raise TypeError("SOM-SOM operation not supported") elif i_descr == "SOM" and s_descr == "SO": raise TypeError("SOM-SO operation not supported") elif i_descr == "SO" and s_descr == "SOM": raise TypeError("SO-SOM operation not supported") elif i_descr == "SO" and s_descr == "SO": raise TypeError("SO-SO operation not supported") else: pass # Setup keyword arguments try: polar = kwargs["polar"] except KeyError: polar = None try: units = kwargs["units"] except KeyError: units = "1/Angstroms" result = hlr_utils.copy_som_attr(result, res_descr, initk, i_descr, scattk, s_descr) if res_descr == "SOM": index = hlr_utils.one_d_units(result, units) result = hlr_utils.force_units(result, units, index) result.setAxisLabel(index, "scalar wavevector transfer") result.setYUnits("Counts/A-1") result.setYLabel("Intensity") else: pass if polar is None: if i_descr == "SOM": try: initk.attr_list.instrument.get_primary() inst = initk.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") elif s_descr == "SOM": try: scattk.attr_list.instrument.get_primary() inst = scattk.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided!") else: raise RuntimeError("If no SOM is provided, then polar "\ +"information must be given.") else: p_descr = hlr_utils.get_descr(polar) # iterate through the values import axis_manip for i in xrange(hlr_utils.get_length(initk, scattk)): val1 = hlr_utils.get_value(initk, i, i_descr, "x") err2_1 = hlr_utils.get_err2(initk, i, i_descr, "x") val2 = hlr_utils.get_value(scattk, i, s_descr, "x") err2_2 = hlr_utils.get_err2(scattk, i, s_descr, "x") map_so = hlr_utils.get_map_so(initk, scattk, i) if polar is None: (angle, angle_err2) = hlr_utils.get_parameter("polar", map_so, inst) else: angle = hlr_utils.get_value(polar, i, p_descr) angle_err2 = hlr_utils.get_err2(polar, i, p_descr) value = axis_manip.init_scatt_wavevector_to_scalar_Q(val1, err2_1, val2, err2_2, angle, angle_err2) hlr_utils.result_insert(result, res_descr, value, map_so, "x") return result
def calc_substrate_trans(obj, subtrans_coeff, substrate_diam, **kwargs): """ This function calculates substrate transmission via the following formula: T = exp[-(A + B * wavelength) * d] where A is a constant with units of cm^-1, B is a constant with units of cm^-2 and d is the substrate diameter in units of cm. @param obj: The data object that contains the TOF axes to calculate the transmission from. @type obj: C{SOM.SOM} or C{SOM.SO} @param subtrans_coeff: The two coefficients for substrate transmission calculation. @type subtrans_coeff: C{tuple} of two C{float}s @param substrate_diam: The diameter of the substrate. @type substrate_diam: C{float} @param kwargs: A list of keyword arguments that the function accepts: @keyword pathlength: The pathlength and its associated error^2 @type pathlength: C{tuple} or C{list} of C{tuple}s @keyword units: The expected units for this function. The default for this function is I{microsecond}. @type units: C{string} @return: The calculate transmission for the given substrate parameters @rtype: C{SOM.SOM} or C{SOM.SO} @raise TypeError: The object used for calculation is not a C{SOM} or a C{SO} @raise RuntimeError: The C{SOM} x-axis units are not I{microsecond} @raise RuntimeError: A C{SOM} does not contain an instrument and no pathlength was provided @raise RuntimeError: No C{SOM} is provided and no pathlength given """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) if o_descr == "number" or o_descr == "list": raise TypeError("Do not know how to handle given type: %s" % o_descr) else: pass # Setup keyword arguments try: pathlength = kwargs["pathlength"] except KeyError: pathlength = None try: units = kwargs["units"] except KeyError: units = "microsecond" # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 if pathlength is not None: p_descr = hlr_utils.get_descr(pathlength) else: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided") else: raise RuntimeError("If no SOM is provided, then pathlength "\ +"information must be provided") result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result.setYLabel("Transmission") # iterate through the values import array_manip import axis_manip import nessi_list import utils import math len_obj = hlr_utils.get_length(obj) for i in xrange(len_obj): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if pathlength is None: (pl, pl_err2) = hlr_utils.get_parameter("total", map_so, inst) else: pl = hlr_utils.get_value(pathlength, i, p_descr) pl_err2 = hlr_utils.get_err2(pathlength, i, p_descr) value = axis_manip.tof_to_wavelength(val, err2, pl, pl_err2) value1 = utils.calc_bin_centers(value[0]) del value # Convert Angstroms to centimeters value2 = array_manip.mult_ncerr(value1[0], value1[1], subtrans_coeff[1]*1.0e-8, 0.0) del value1 # Calculate the exponential value3 = array_manip.add_ncerr(value2[0], value2[1], subtrans_coeff[0], 0.0) del value2 value4 = array_manip.mult_ncerr(value3[0], value3[1], -1.0*substrate_diam, 0.0) del value3 # Calculate transmission trans = nessi_list.NessiList() len_trans = len(value4[0]) for j in xrange(len_trans): trans.append(math.exp(value4[0][j])) trans_err2 = nessi_list.NessiList(len(trans)) hlr_utils.result_insert(result, res_descr, (trans, trans_err2), map_so) return result
def tof_to_scalar_Q(obj, **kwargs): """ This function converts a primary axis of a C{SOM} or C{SO} from time-of-flight to scalarQ. The time-of-flight axis for a C{SOM} must be in units of I{microseconds}. The primary axis of a C{SO} is assumed to be in units of I{microseconds}. A C{tuple} of C{(time-of-flight, time-of-flight_err2)} (assumed to be in units of I{microseconds}) can be converted to C{(scalar_Q, scalar_Q_err2)}. @param obj: Object to be converted @type obj: C{SOM.SOM}, C{SOM.SO} or C{tuple} @param kwargs: A list of keyword arguments that the function accepts: @keyword polar: The polar angle and its associated error^2 @type polar: C{tuple} or C{list} of C{tuple}s @keyword pathlength: The pathlength and its associated error^2 @type pathlength: C{tuple} or C{list} of C{tuple}s @keyword angle_offset: A constant offset for the polar angle and its associated error^2. The units of the offset should be in radians. @type angle_offset: C{tuple} @keyword lojac: A flag that allows one to turn off the calculation of the linear-order Jacobian. The default action is True for histogram data. @type lojac: C{boolean} @keyword units: The expected units for this function. The default for this function is I{microseconds}. @type units: C{string} @return: Object with a primary axis in time-of-flight converted to scalar Q @rtype: C{SOM.SOM}, C{SOM.SO} or C{tuple} @raise TypeError: The incoming object is not a type the function recognizes @raise RuntimeError: A C{SOM} is not passed and no polar angle is provided @raise RuntimeError: The C{SOM} x-axis units are not I{microseconds} """ # import the helper functions import hlr_utils # set up for working through data (result, res_descr) = hlr_utils.empty_result(obj) o_descr = hlr_utils.get_descr(obj) if o_descr == "list": raise TypeError("Do not know how to handle given type: %s" % \ o_descr) else: pass # Setup keyword arguments try: polar = kwargs["polar"] except KeyError: polar = None try: pathlength = kwargs["pathlength"] except KeyError: pathlength = None try: units = kwargs["units"] except KeyError: units = "microseconds" try: lojac = kwargs["lojac"] except KeyError: lojac = hlr_utils.check_lojac(obj) try: angle_offset = kwargs["angle_offset"] except KeyError: angle_offset = None # Primary axis for transformation. If a SO is passed, the function, will # assume the axis for transformation is at the 0 position if o_descr == "SOM": axis = hlr_utils.one_d_units(obj, units) else: axis = 0 result = hlr_utils.copy_som_attr(result, res_descr, obj, o_descr) if res_descr == "SOM": result = hlr_utils.force_units(result, "1/Angstroms", axis) result.setAxisLabel(axis, "scalar wavevector transfer") result.setYUnits("Counts/A-1") result.setYLabel("Intensity") else: pass if pathlength is None or polar is None: if o_descr == "SOM": try: obj.attr_list.instrument.get_primary() inst = obj.attr_list.instrument except RuntimeError: raise RuntimeError("A detector was not provided") else: if pathlength is None and polar is None: raise RuntimeError("If no SOM is provided, then pathlength "\ +"and polar angle information must be "\ +"provided") elif pathlength is None: raise RuntimeError("If no SOM is provided, then pathlength "\ +"information must be provided") elif polar is None: raise RuntimeError("If no SOM is provided, then polar angle "\ +"information must be provided") else: raise RuntimeError("If you get here, see Steve Miller for "\ +"your mug.") else: pass if pathlength is not None: p_descr = hlr_utils.get_descr(pathlength) else: pass if polar is not None: a_descr = hlr_utils.get_descr(polar) else: pass # iterate through the values import axis_manip if lojac: import utils for i in xrange(hlr_utils.get_length(obj)): val = hlr_utils.get_value(obj, i, o_descr, "x", axis) err2 = hlr_utils.get_err2(obj, i, o_descr, "x", axis) map_so = hlr_utils.get_map_so(obj, None, i) if pathlength is None: (pl, pl_err2) = hlr_utils.get_parameter("total", map_so, inst) else: pl = hlr_utils.get_value(pathlength, i, p_descr) pl_err2 = hlr_utils.get_err2(pathlength, i, p_descr) if polar is None: (angle, angle_err2) = hlr_utils.get_parameter("polar", map_so, inst) else: angle = hlr_utils.get_value(polar, i, a_descr) angle_err2 = hlr_utils.get_err2(polar, i, a_descr) if angle_offset is not None: angle += angle_offset[0] angle_err2 += angle_offset[1] value = axis_manip.tof_to_scalar_Q(val, err2, pl, pl_err2, angle, angle_err2) if lojac: y_val = hlr_utils.get_value(obj, i, o_descr, "y") y_err2 = hlr_utils.get_err2(obj, i, o_descr, "y") counts = utils.linear_order_jacobian(val, value[0], y_val, y_err2) else: pass if o_descr != "number": value1 = axis_manip.reverse_array_cp(value[0]) value2 = axis_manip.reverse_array_cp(value[1]) rev_value = (value1, value2) else: rev_value = value if map_so is not None: if not lojac: map_so.y = axis_manip.reverse_array_cp(map_so.y) map_so.var_y = axis_manip.reverse_array_cp(map_so.var_y) else: map_so.y = axis_manip.reverse_array_cp(counts[0]) map_so.var_y = axis_manip.reverse_array_cp(counts[1]) else: pass hlr_utils.result_insert(result, res_descr, rev_value, map_so, "x", axis) return result