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

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

Hankel trafo optimized, sesans_reader code cleaned up, hankel matrix constructor
code moved from sasview/qsmearing to sasmodels/sesans

  • 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
17
18import numpy as np  # type: ignore
19from numpy import pi, exp  # type: ignore
20#from scipy.special import j 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-compute the Hankel matrix (H)
69        H0,H, q_calc = sesans.Hankelconstructor(data)
70        # Then return the actual transform, as if it were a smearing function
71        return PySmear(SESANS1D(data, H0, H, q_calc), model)
72
73    _found_resolution = False
74    if data.dx is not None and len(data.dx) == len(data.x):
75
76        # Check that we have non-zero data
77        if data.dx[0] > 0.0:
78            _found_resolution = True
79            #print "_found_resolution",_found_resolution
80            #print "data1D.dx[0]",data1D.dx[0],data1D.dxl[0]
81    # If we found resolution smearing data, return a QSmearer
82    if _found_resolution == True:
83         return pinhole_smear(data, model)
84
85    # Look for slit smearing data
86    _found_slit = False
87    if data.dxl is not None and len(data.dxl) == len(data.x) \
88        and data.dxw is not None and len(data.dxw) == len(data.x):
89
90        # Check that we have non-zero data
91        if data.dxl[0] > 0.0 or data.dxw[0] > 0.0:
92            _found_slit = True
93
94        # Sanity check: all data should be the same as a function of Q
95        for item in data.dxl:
96            if data.dxl[0] != item:
97                _found_resolution = False
98                break
99
100        for item in data.dxw:
101            if data.dxw[0] != item:
102                _found_resolution = False
103                break
104    # If we found slit smearing data, return a slit smearer
105    if _found_slit == True:
106        return slit_smear(data, model)
107    return None
108
109
110class PySmear(object):
111    """
112    Wrapper for pure python sasmodels resolution functions.
113    """
114    def __init__(self, resolution, model):
115        self.model = model
116        self.resolution = resolution
117        if hasattr(self.resolution, 'data'):
118            if self.resolution.data.meta_data['loader'] == 'SESANS':
119                self.offset = 0
120            # This is default behaviour, for future resolution/transform functions this needs to be revisited.
121            else:
122                self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
123        else:
124            self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
125
126        #self.offset = numpy.searchsorted(self.resolution.q_calc, self.resolution.q[0])
127
128    def apply(self, iq_in, first_bin=0, last_bin=None):
129        """
130        Apply the resolution function to the data.
131        Note that this is called with iq_in matching data.x, but with
132        iq_in[first_bin:last_bin] set to theory values for these bins,
133        and the remainder left undefined.  The first_bin, last_bin values
134        should be those returned from get_bin_range.
135        The returned value is of the same length as iq_in, with the range
136        first_bin:last_bin set to the resolution smeared values.
137        """
138        if last_bin is None: last_bin = len(iq_in)
139        start, end = first_bin + self.offset, last_bin + self.offset
140        q_calc = self.resolution.q_calc
141        iq_calc = numpy.empty_like(q_calc)
142        if start > 0:
143            iq_calc[:start] = self.model.evalDistribution(q_calc[:start])
144        if end+1 < len(q_calc):
145            iq_calc[end+1:] = self.model.evalDistribution(q_calc[end+1:])
146        iq_calc[start:end+1] = iq_in[first_bin:last_bin+1]
147        smeared = self.resolution.apply(iq_calc)
148        return smeared
149    __call__ = apply
150
151    def get_bin_range(self, q_min=None, q_max=None):
152        """
153        For a given q_min, q_max, find the corresponding indices in the data.
154        Returns first, last.
155        Note that these are indexes into q from the data, not the q_calc
156        needed by the resolution function.  Note also that these are the
157        indices, not the range limits.  That is, the complete range will be
158        q[first:last+1].
159        """
160
161        q = self.resolution.q
162        first = numpy.searchsorted(q, q_min)
163        last = numpy.searchsorted(q, q_max)
164        return first, min(last,len(q)-1)
165
166def slit_smear(data, model=None):
167    q = data.x
168    width = data.dxw if data.dxw is not None else 0
169    height = data.dxl if data.dxl is not None else 0
170    # TODO: width and height seem to be reversed
171    return PySmear(Slit1D(q, height, width), model)
172
173def pinhole_smear(data, model=None):
174    q = data.x
175    width = data.dx if data.dx is not None else 0
176    return PySmear(Pinhole1D(q, width), model)
177
178def sesans_smear(data, model=None):
179    #This should be calculated characteristic length scale
180    #Probably not a data prameter either
181    #Need function to calculate this based on model
182    #Here assume a number
183    Rmax = 1000000
184    q_calc = sesans.make_q(data.sample.zacceptance, Rmax)
185    SElength=Converter(data._xunit)(data.x, "A")
186    #return sesans.HankelTransform(q_calc, SElength)
187    #Old return statement, running through the smearer
188    #return PySmear(SESANS1D(data,q_calc),model)
Note: See TracBrowser for help on using the repository browser.