source: sasview/src/sas/sascalc/data_util/qsmearing.py @ 55db501

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 55db501 was 55db501, checked in by jhbakker, 7 years ago

test branch for SESANS class in sesans.py

  • Property mode set to 100644
File size: 7.1 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 time
16from sasmodels import sesans
17import numpy as np  # type: ignore
18from numpy import pi, exp  # type: ignore
19#from scipy.special import j as besselj
20
21from sasmodels.resolution import Slit1D, Pinhole1D, SESANS1D
22from sasmodels.resolution2d import Pinhole2D
23from src.sas.sascalc.data_util.nxsunit import Converter
24
25
26def smear_selection(data, model = None):
27    """
28    Creates the right type of smearer according
29    to the data.
30    The canSAS format has a rule that either
31    slit smearing data OR resolution smearing data
32    is available.
33
34    For the present purpose, we choose the one that
35    has none-zero data. If both slit and resolution
36    smearing arrays are filled with good data
37    (which should not happen), then we choose the
38    resolution smearing data.
39
40    :param data: Data1D object
41    :param model: sas.model instance
42    """
43    # Sanity check. If we are not dealing with a SAS Data1D
44    # object, just return None
45
46    # This checks for 2D data (does not throw exception because fail is common)
47    if  data.__class__.__name__ not in ['Data1D', 'Theory1D']:
48        if data == None:
49            return None
50        elif data.dqx_data == None or data.dqy_data == None:
51            return None
52        return Pinhole2D(data)
53    # This checks for 1D data with smearing info in the data itself (again, fail is likely; no exceptions)
54    if  not hasattr(data, "dx") and not hasattr(data, "dxl")\
55         and not hasattr(data, "dxw"):
56        return None
57
58    # Look for resolution smearing data
59    # This is the code that checks for SESANS data; it looks for the file loader
60    # TODO: change other sanity checks to check for file loader instead of data structure?
61    _found_sesans = False
62    #if data.dx is not None and data.meta_data['loader']=='SESANS':
63    if data.dx is not None and data.isSesans:
64        if data.dx[0] > 0.0:
65            _found_sesans = True
66
67    if _found_sesans == True:
68        #Pre-compute the Hankel matrix (H)
69        qmax, qunits = data.sample.zacceptance
70        Hankelinst=sesans.SesansTransform()
71        sesans.SesansTransform.set_transform(Hankelinst,
72        SE = Converter(data._xunit)(data.x, "A"),
73        zaccept = Converter(qunits)(qmax, "1/A"),
74        Rmax = 1000000)
75        H=sesans.SesansTransform._H
76        H0=sesans.SesansTransform._H0
77        q=sesans.SesansTransform.q
78        # Then return the actual transform, as if it were a smearing function
79        # applying evalDistribution to a model, with a q-space as param, returns the I(q) values that go with the q-values
80
81        return PySmear(SESANS1D(data, H0, H, q), model)
82
83    _found_resolution = False
84    if data.dx is not None and len(data.dx) == len(data.x):
85
86        # Check that we have non-zero data
87        if data.dx[0] > 0.0:
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
92    if _found_resolution == True:
93         return pinhole_smear(data, model)
94
95    # Look for slit smearing data
96    _found_slit = False
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
100        # Check that we have non-zero data
101        if data.dxl[0] > 0.0 or data.dxw[0] > 0.0:
102            _found_slit = True
103
104        # Sanity check: all data should be the same as a function of Q
105        for item in data.dxl:
106            if data.dxl[0] != item:
107                _found_resolution = False
108                break
109
110        for item in data.dxw:
111            if data.dxw[0] != item:
112                _found_resolution = False
113                break
114    # If we found slit smearing data, return a slit smearer
115    if _found_slit == True:
116        return slit_smear(data, model)
117    return None
118
119
120class PySmear(object):
121    """
122    Wrapper for pure python sasmodels resolution functions.
123    """
124    def __init__(self, resolution, model):
125        self.model = model
126        self.resolution = resolution
127        if hasattr(self.resolution, 'data'):
128            if self.resolution.data.meta_data['loader'] == 'SESANS':
129                self.offset = 0
130            # This is default behaviour, for future resolution/transform functions this needs to be revisited.
131            else:
132                self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
133        else:
134            self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
135
136        #self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
137
138    def apply(self, iq_in, first_bin=0, last_bin=None):
139        """
140        Apply the resolution function to the data.
141        Note that this is called with iq_in matching data.x, but with
142        iq_in[first_bin:last_bin] set to theory values for these bins,
143        and the remainder left undefined.  The first_bin, last_bin values
144        should be those returned from get_bin_range.
145        The returned value is of the same length as iq_in, with the range
146        first_bin:last_bin set to the resolution smeared values.
147        """
148        if last_bin is None: last_bin = len(iq_in)
149        start, end = first_bin + self.offset, last_bin + self.offset
150        q_calc = self.resolution.q_calc
151        iq_calc = numpy.empty_like(q_calc)
152        if start > 0:
153            iq_calc[:start] = self.model.evalDistribution(q_calc[:start])
154        if end+1 < len(q_calc):
155            iq_calc[end+1:] = self.model.evalDistribution(q_calc[end+1:])
156        iq_calc[start:end+1] = iq_in[first_bin:last_bin+1]
157        smeared = self.resolution.apply(iq_calc)
158        return smeared
159    __call__ = apply
160
161    def get_bin_range(self, q_min=None, q_max=None):
162        """
163        For a given q_min, q_max, find the corresponding indices in the data.
164        Returns first, last.
165        Note that these are indexes into q from the data, not the q_calc
166        needed by the resolution function.  Note also that these are the
167        indices, not the range limits.  That is, the complete range will be
168        q[first:last+1].
169        """
170
171        q = self.resolution.q
172        first = numpy.searchsorted(q, q_min)
173        last = numpy.searchsorted(q, q_max)
174        return first, min(last,len(q)-1)
175
176def slit_smear(data, model=None):
177    q = data.x
178    width = data.dxw if data.dxw is not None else 0
179    height = data.dxl if data.dxl is not None else 0
180    # TODO: width and height seem to be reversed
181    return PySmear(Slit1D(q, height, width), model)
182
183def pinhole_smear(data, model=None):
184    q = data.x
185    width = data.dx if data.dx is not None else 0
186    return PySmear(Pinhole1D(q, width), model)
Note: See TracBrowser for help on using the repository browser.