source: sasview/src/sas/sascalc/data_util/qsmearing.py @ 2a2b43a

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 2a2b43a was 2a2b43a, checked in by jhbakker, 7 years ago

hankel simplified, set_transform is now init,sesans test data is in
sasview/test

  • Property mode set to 100644
File size: 9.0 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 numpy
12import math
13import logging
14import sys
15from sasmodels import sesans
16import numpy as np  # type: ignore
17from numpy import pi, exp # type:ignore
18from sasmodels.resolution import Slit1D, Pinhole1D
19from sasmodels.sesans import SESANS1D
20from sasmodels.resolution2d import Pinhole2D
21from src.sas.sascalc.data_util.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 == None:
45            return None
46        elif data.dqx_data == None or data.dqy_data == None:
47            return None
48        return Pinhole2D(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 numpy.size(data.dx[data.dx <= 0]) == 0:
62            _found_sesans = True
63        # if data.dx[0] <= 0.0:
64        if numpy.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 == True:
68        #Pre-compute the Hankel matrix (H)
69        qmax, qunits = data.sample.zacceptance
70        hankel = sesans.SesansTransform(SE=Converter(data._xunit)(data.x, "A"),
71                                        zaccept=Converter(qunits)(qmax, "1/A"),
72                                        Rmax=10000000)
73        # Then return the actual transform, as if it were a smearing function
74        return PySmear(SESANS1D(data, hankel.H0, hankel.H, hankel.q), model)
75
76    _found_resolution = False
77    if data.dx is not None and len(data.dx) == len(data.x):
78
79        # Check that we have non-zero data
80        if data.dx[0] > 0.0:
81            _found_resolution = True
82            #print "_found_resolution",_found_resolution
83            #print "data1D.dx[0]",data1D.dx[0],data1D.dxl[0]
84    # If we found resolution smearing data, return a QSmearer
85    if _found_resolution == True:
86         return pinhole_smear(data, model)
87
88    # Look for slit smearing data
89    _found_slit = False
90    if data.dxl is not None and len(data.dxl) == len(data.x) \
91        and data.dxw is not None and len(data.dxw) == len(data.x):
92
93        # Check that we have non-zero data
94        if data.dxl[0] > 0.0 or data.dxw[0] > 0.0:
95            _found_slit = True
96
97        # Sanity check: all data should be the same as a function of Q
98        for item in data.dxl:
99            if data.dxl[0] != item:
100                _found_resolution = False
101                break
102
103        for item in data.dxw:
104            if data.dxw[0] != item:
105                _found_resolution = False
106                break
107    # If we found slit smearing data, return a slit smearer
108    if _found_slit == True:
109        return slit_smear(data, model)
110    return None
111
112
113class PySmear(object):
114    """
115    Wrapper for pure python sasmodels resolution functions.
116    """
117    def __init__(self, resolution, model):
118        self.model = model
119        self.resolution = resolution
120
121        if hasattr(self.resolution, 'data'):
122            #if self.resolution.data.meta_data['loader'] == 'SESANS':  # Always True if file extension is '.ses'!
123            if self.resolution.data.isSesans:
124                self.offset = 0
125            # This is default behaviour, for future resolution/transform functions this needs to be revisited.
126            else:
127                self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
128        else:
129            self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
130
131        # self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
132
133    def apply(self, iq_in, first_bin=0, last_bin=None):
134        """
135        Apply the resolution function to the data.
136        Note that this is called with iq_in matching data.x, but with
137        iq_in[first_bin:last_bin] set to theory values for these bins,
138        and the remainder left undefined.  The first_bin, last_bin values
139        should be those returned from get_bin_range.
140        The returned value is of the same length as iq_in, with the range
141        first_bin:last_bin set to the resolution smeared values.
142        """
143        if last_bin is None: last_bin = len(iq_in)
144        start, end = first_bin + self.offset, last_bin + self.offset
145        q_calc = self.resolution.q_calc
146        iq_calc = numpy.empty_like(q_calc)
147        if start > 0:
148            iq_calc[:start] = self.model.evalDistribution(q_calc[:start])
149        if end+1 < len(q_calc):
150            iq_calc[end+1:] = self.model.evalDistribution(q_calc[end+1:])
151        iq_calc[start:end+1] = iq_in[first_bin:last_bin+1]
152        smeared = self.resolution.apply(iq_calc)
153        return smeared
154    __call__ = apply
155
156    def get_bin_range(self, q_min=None, q_max=None):
157        """
158        For a given q_min, q_max, find the corresponding indices in the data.
159        Returns first, last.
160        Note that these are indexes into q from the data, not the q_calc
161        needed by the resolution function.  Note also that these are the
162        indices, not the range limits.  That is, the complete range will be
163        q[first:last+1].
164        """
165        q = self.resolution.q
166        first = numpy.searchsorted(q, q_min)
167        last = numpy.searchsorted(q, q_max)
168        return first, min(last,len(q)-1)
169
170def slit_smear(data, model=None):
171    q = data.x
172    width = data.dxw if data.dxw is not None else 0
173    height = data.dxl if data.dxl is not None else 0
174    # TODO: width and height seem to be reversed
175    return PySmear(Slit1D(q, height, width), model)
176
177def pinhole_smear(data, model=None):
178    q = data.x
179    width = data.dx if data.dx is not None else 0
180    return PySmear(Pinhole1D(q, width), model)
181
182
183class PySmear2D(object):
184    """
185    Q smearing class for SAS 2d pinhole data
186    """
187
188    def __init__(self, data=None, model=None):
189        self.data = data
190        self.model = model
191        self.accuracy = 'Low'
192        self.limit = 3.0
193        self.index = None
194        self.coords = 'polar'
195        self.smearer = True
196
197    def set_accuracy(self, accuracy='Low'):
198        """
199        Set accuracy.
200
201        :param accuracy:  string
202        """
203        self.accuracy = accuracy
204
205    def set_smearer(self, smearer=True):
206        """
207        Set whether or not smearer will be used
208
209        :param smearer: smear object
210
211        """
212        self.smearer = smearer
213
214    def set_data(self, data=None):
215        """
216        Set data.
217
218        :param data: DataLoader.Data_info type
219        """
220        self.data = data
221
222    def set_model(self, model=None):
223        """
224        Set model.
225
226        :param model: sas.models instance
227        """
228        self.model = model
229
230    def set_index(self, index=None):
231        """
232        Set index.
233
234        :param index: 1d arrays
235        """
236        self.index = index
237
238    def get_value(self):
239        """
240        Over sampling of r_nbins times phi_nbins, calculate Gaussian weights,
241        then find smeared intensity
242        """
243        if self.smearer:
244            res = Pinhole2D(data=self.data, index=self.index,
245                            nsigma=3.0, accuracy=self.accuracy,
246                            coords=self.coords)
247            val = self.model.evalDistribution(res.q_calc)
248            return res.apply(val)
249        else:
250            index = self.index if self.index is not None else slice(None)
251            qx_data = self.data.qx_data[index]
252            qy_data = self.data.qy_data[index]
253            q_calc = [qx_data, qy_data]
254            val = self.model.evalDistribution(q_calc)
255            return val
256
Note: See TracBrowser for help on using the repository browser.