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

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

Correct implementation of fast SESANS fitting

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