source: sasview/src/sas/sascalc/data_util/qsmearing.py @ 945f45d

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 945f45d was 775e0b7, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

use relative import for local files

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