source: sasview/src/sas/sascalc/data_util/qsmearing.py @ 7b15990

costrafo411
Last change on this file since 7b15990 was 7b15990, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

Merge branch 'master' into costrafo411

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