source: sasview/src/sas/sascalc/fit/qsmearing.py @ 0e0c645

ticket-1243
Last change on this file since 0e0c645 was 2469df7, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

lint: update 'if x==True/False?' to 'if x/not x:'

  • Property mode set to 100644
File size: 8.6 KB
RevLine 
[240a2d2]1"""
2    Handle Q smearing
3"""
4#####################################################################
5#This software was developed by the University of Tennessee as part of the
6#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
[50fcb09]7#project funded by the US National Science Foundation.
[240a2d2]8#See the license text in license.txt
9#copyright 2008, University of Tennessee
10######################################################################
11import math
12import logging
13import sys
[775e0b7]14
[a9f579c]15import numpy as np  # type: ignore
16from numpy import pi, exp # type:ignore
[775e0b7]17
[f8aa738]18from sasmodels.resolution import Slit1D, Pinhole1D
[157b716]19from sasmodels.sesans import SesansTransform
[f8aa738]20from sasmodels.resolution2d import Pinhole2D
[50fcb09]21
22from sas.sascalc.data_util.nxsunit import Converter
[f8aa738]23
24def smear_selection(data, model = None):
[240a2d2]25    """
[f8aa738]26    Creates the right type of smearer according
[240a2d2]27    to the data.
28    The canSAS format has a rule that either
29    slit smearing data OR resolution smearing data
[f8aa738]30    is available.
31
[240a2d2]32    For the present purpose, we choose the one that
33    has none-zero data. If both slit and resolution
[f8aa738]34    smearing arrays are filled with good data
[240a2d2]35    (which should not happen), then we choose the
[f8aa738]36    resolution smearing data.
37
38    :param data: Data1D object
[240a2d2]39    :param model: sas.model instance
40    """
41    # Sanity check. If we are not dealing with a SAS Data1D
42    # object, just return None
[a9f579c]43    # This checks for 2D data (does not throw exception because fail is common)
[f8aa738]44    if  data.__class__.__name__ not in ['Data1D', 'Theory1D']:
[235f514]45        if data is None:
[240a2d2]46            return None
[235f514]47        elif data.dqx_data is None or data.dqy_data is None:
[240a2d2]48            return None
[2ffe241]49        return PySmear2D(data)
[a9f579c]50    # This checks for 1D data with smearing info in the data itself (again, fail is likely; no exceptions)
[f8aa738]51    if  not hasattr(data, "dx") and not hasattr(data, "dxl")\
52         and not hasattr(data, "dxw"):
[240a2d2]53        return None
[f8aa738]54
[240a2d2]55    # Look for resolution smearing data
[a9f579c]56    # This is the code that checks for SESANS data; it looks for the file loader
57    # TODO: change other sanity checks to check for file loader instead of data structure?
58    _found_sesans = False
59    #if data.dx is not None and data.meta_data['loader']=='SESANS':
60    if data.dx is not None and data.isSesans:
61        #if data.dx[0] > 0.0:
[9a5097c]62        if np.size(data.dx[data.dx <= 0]) == 0:
[a9f579c]63            _found_sesans = True
64        # if data.dx[0] <= 0.0:
[9a5097c]65        if np.size(data.dx[data.dx <= 0]) > 0:
[a9f579c]66            raise ValueError('one or more of your dx values are negative, please check the data file!')
67
[e962d85]68    if _found_sesans:
69        # Pre-compute the Hankel matrix (H)
[157b716]70        SElength = Converter(data._xunit)(data.x, "A")
[0ac6e11]71
72        theta_max = Converter("radians")(data.sample.zacceptance)[0]
73        q_max = 2 * np.pi / np.max(data.source.wavelength) * np.sin(theta_max)
74        zaccept = Converter("1/A")(q_max, "1/" + data.source.wavelength_unit),
75
[157b716]76        Rmax = 10000000
[e962d85]77        hankel = SesansTransform(data.x, SElength,
78                                 data.source.wavelength,
79                                 zaccept, Rmax)
[a9f579c]80        # Then return the actual transform, as if it were a smearing function
[157b716]81        return PySmear(hankel, model, offset=0)
[a9f579c]82
[240a2d2]83    _found_resolution = False
[f8aa738]84    if data.dx is not None and len(data.dx) == len(data.x):
85
[240a2d2]86        # Check that we have non-zero data
[f8aa738]87        if data.dx[0] > 0.0:
[240a2d2]88            _found_resolution = True
89            #print "_found_resolution",_found_resolution
90            #print "data1D.dx[0]",data1D.dx[0],data1D.dxl[0]
91    # If we found resolution smearing data, return a QSmearer
[2469df7]92    if _found_resolution:
[f8aa738]93         return pinhole_smear(data, model)
[240a2d2]94
95    # Look for slit smearing data
96    _found_slit = False
[f8aa738]97    if data.dxl is not None and len(data.dxl) == len(data.x) \
98        and data.dxw is not None and len(data.dxw) == len(data.x):
99
[240a2d2]100        # Check that we have non-zero data
[f8aa738]101        if data.dxl[0] > 0.0 or data.dxw[0] > 0.0:
[240a2d2]102            _found_slit = True
[f8aa738]103
[240a2d2]104        # Sanity check: all data should be the same as a function of Q
[f8aa738]105        for item in data.dxl:
106            if data.dxl[0] != item:
[240a2d2]107                _found_resolution = False
108                break
[f8aa738]109
110        for item in data.dxw:
111            if data.dxw[0] != item:
[240a2d2]112                _found_resolution = False
113                break
114    # If we found slit smearing data, return a slit smearer
[2469df7]115    if _found_slit:
[f8aa738]116        return slit_smear(data, model)
[240a2d2]117    return None
118
119
120class PySmear(object):
121    """
122    Wrapper for pure python sasmodels resolution functions.
123    """
[157b716]124    def __init__(self, resolution, model, offset=None):
[240a2d2]125        self.model = model
126        self.resolution = resolution
[157b716]127        if offset is None:
[9a5097c]128            offset = np.searchsorted(self.resolution.q_calc, self.resolution.q[0])
[157b716]129        self.offset = offset
[240a2d2]130
131    def apply(self, iq_in, first_bin=0, last_bin=None):
132        """
133        Apply the resolution function to the data.
134        Note that this is called with iq_in matching data.x, but with
135        iq_in[first_bin:last_bin] set to theory values for these bins,
136        and the remainder left undefined.  The first_bin, last_bin values
137        should be those returned from get_bin_range.
138        The returned value is of the same length as iq_in, with the range
139        first_bin:last_bin set to the resolution smeared values.
140        """
141        if last_bin is None: last_bin = len(iq_in)
142        start, end = first_bin + self.offset, last_bin + self.offset
143        q_calc = self.resolution.q_calc
[9a5097c]144        iq_calc = np.empty_like(q_calc)
[240a2d2]145        if start > 0:
146            iq_calc[:start] = self.model.evalDistribution(q_calc[:start])
147        if end+1 < len(q_calc):
148            iq_calc[end+1:] = self.model.evalDistribution(q_calc[end+1:])
149        iq_calc[start:end+1] = iq_in[first_bin:last_bin+1]
150        smeared = self.resolution.apply(iq_calc)
151        return smeared
152    __call__ = apply
153
154    def get_bin_range(self, q_min=None, q_max=None):
155        """
156        For a given q_min, q_max, find the corresponding indices in the data.
157        Returns first, last.
158        Note that these are indexes into q from the data, not the q_calc
159        needed by the resolution function.  Note also that these are the
160        indices, not the range limits.  That is, the complete range will be
161        q[first:last+1].
162        """
163        q = self.resolution.q
[9a5097c]164        first = np.searchsorted(q, q_min)
165        last = np.searchsorted(q, q_max)
[240a2d2]166        return first, min(last,len(q)-1)
167
168def slit_smear(data, model=None):
169    q = data.x
170    width = data.dxw if data.dxw is not None else 0
171    height = data.dxl if data.dxl is not None else 0
172    # TODO: width and height seem to be reversed
173    return PySmear(Slit1D(q, height, width), model)
174
175def pinhole_smear(data, model=None):
176    q = data.x
177    width = data.dx if data.dx is not None else 0
[d3911e3]178    return PySmear(Pinhole1D(q, width), model)
179
180
181class PySmear2D(object):
182    """
183    Q smearing class for SAS 2d pinhole data
184    """
185
186    def __init__(self, data=None, model=None):
187        self.data = data
188        self.model = model
189        self.accuracy = 'Low'
190        self.limit = 3.0
191        self.index = None
192        self.coords = 'polar'
193        self.smearer = True
194
195    def set_accuracy(self, accuracy='Low'):
196        """
197        Set accuracy.
198
199        :param accuracy:  string
200        """
201        self.accuracy = accuracy
202
203    def set_smearer(self, smearer=True):
204        """
205        Set whether or not smearer will be used
206
207        :param smearer: smear object
208
209        """
210        self.smearer = smearer
211
212    def set_data(self, data=None):
213        """
214        Set data.
215
216        :param data: DataLoader.Data_info type
217        """
218        self.data = data
219
220    def set_model(self, model=None):
221        """
222        Set model.
223
224        :param model: sas.models instance
225        """
226        self.model = model
227
228    def set_index(self, index=None):
229        """
230        Set index.
231
232        :param index: 1d arrays
233        """
234        self.index = index
235
236    def get_value(self):
237        """
238        Over sampling of r_nbins times phi_nbins, calculate Gaussian weights,
239        then find smeared intensity
240        """
241        if self.smearer:
242            res = Pinhole2D(data=self.data, index=self.index,
243                            nsigma=3.0, accuracy=self.accuracy,
244                            coords=self.coords)
245            val = self.model.evalDistribution(res.q_calc)
246            return res.apply(val)
247        else:
248            index = self.index if self.index is not None else slice(None)
249            qx_data = self.data.qx_data[index]
250            qy_data = self.data.qy_data[index]
251            q_calc = [qx_data, qy_data]
252            val = self.model.evalDistribution(q_calc)
253            return val
254
Note: See TracBrowser for help on using the repository browser.