source: sasview/src/sas/sascalc/data_util/qsmearing.py @ 46f798f

Last change on this file since 46f798f was 2ffe241, checked in by krzywon, 8 years ago

Fix issues with loading 2D data in the SESANS branch and always set isSesans to False when working with 2D.

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