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

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

Limit Sesanstransform q-space array size to prevent Memerror on 32-bit OS

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