source: sasview/src/sas/qtgui/Perspectives/Fitting/ModelThread.py @ 5181e9b

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 5181e9b was 5181e9b, checked in by Torin Cooper-Bennun <torin.cooper-bennun@…>, 6 years ago

ModelThread? supports sasmodels beta_approx version of calculate_Iq, which returns intermediate results

  • Property mode set to 100644
File size: 10.1 KB
Line 
1"""
2    Calculation thread for modeling
3"""
4
5import time
6import numpy
7import math
8from sas.sascalc.data_util.calcthread import CalcThread
9from sas.sascalc.fit.MultiplicationModel import MultiplicationModel
10import sas.qtgui.Utilities.LocalConfig as LocalConfig
11
12class Calc2D(CalcThread):
13    """
14    Compute 2D model
15    This calculation assumes a 2-fold symmetry of the model
16    where points are computed for one half of the detector
17    and I(qx, qy) = I(-qx, -qy) is assumed.
18    """
19    def __init__(self, data, model, smearer, qmin, qmax, page_id,
20                 state=None,
21                 weight=None,
22                 fid=None,
23                 toggle_mode_on=False,
24                 completefn=None,
25                 updatefn=None,
26                 update_chisqr=True,
27                 source='model',
28                 yieldtime=0.04,
29                 worktime=0.04,
30                 exception_handler=None,
31                 ):
32        CalcThread.__init__(self, completefn, updatefn, yieldtime, worktime,
33                            exception_handler=exception_handler)
34        self.qmin = qmin
35        self.qmax = qmax
36        self.weight = weight
37        self.fid = fid
38        #self.qstep = qstep
39        self.toggle_mode_on = toggle_mode_on
40        self.data = data
41        self.page_id = page_id
42        self.state = None
43        # the model on to calculate
44        self.model = model
45        self.smearer = smearer
46        self.starttime = 0
47        self.update_chisqr = update_chisqr
48        self.source = source
49
50    def compute(self):
51        """
52        Compute the data given a model function
53        """
54        self.starttime = time.time()
55        # Determine appropriate q range
56        if self.qmin is None:
57            self.qmin = 0
58        if self.qmax is None:
59            if self.data is not None:
60                newx = math.pow(max(math.fabs(self.data.xmax),
61                                   math.fabs(self.data.xmin)), 2)
62                newy = math.pow(max(math.fabs(self.data.ymax),
63                                   math.fabs(self.data.ymin)), 2)
64                self.qmax = math.sqrt(newx + newy)
65
66        if self.data is None:
67            msg = "Compute Calc2D receive data = %s.\n" % str(self.data)
68            raise ValueError(msg)
69
70        # Define matrix where data will be plotted
71        radius = numpy.sqrt((self.data.qx_data * self.data.qx_data) + \
72                    (self.data.qy_data * self.data.qy_data))
73
74        # For theory, qmax is based on 1d qmax
75        # so that must be mulitified by sqrt(2) to get actual max for 2d
76        index_model = (self.qmin <= radius) & (radius <= self.qmax)
77        index_model = index_model & self.data.mask
78        index_model = index_model & numpy.isfinite(self.data.data)
79
80        if self.smearer is not None:
81            # Set smearer w/ data, model and index.
82            fn = self.smearer
83            fn.set_model(self.model)
84            fn.set_index(index_model)
85            # Calculate smeared Intensity
86            #(by Gaussian averaging): DataLoader/smearing2d/Smearer2D()
87            value = fn.get_value()
88        else:
89            # calculation w/o smearing
90            value = self.model.evalDistribution([
91                self.data.qx_data[index_model],
92                self.data.qy_data[index_model]
93            ])
94        output = numpy.zeros(len(self.data.qx_data))
95        # output default is None
96        # This method is to distinguish between masked
97        #point(nan) and data point = 0.
98        output = output / output
99        # set value for self.mask==True, else still None to Plottools
100        output[index_model] = value
101        elapsed = time.time() - self.starttime
102
103        res = dict(image = output, data = self.data, page_id = self.page_id,
104            model = self.model, state = self.state,
105            toggle_mode_on = self.toggle_mode_on, elapsed = elapsed,
106            index = index_model, fid = self.fid,
107            qmin = self.qmin, qmax = self.qmax,
108            weight = self.weight, update_chisqr = self.update_chisqr,
109            source = self.source)
110
111        if LocalConfig.USING_TWISTED:
112            return res
113        else:
114            self.completefn(res)
115
116class Calc1D(CalcThread):
117    """
118    Compute 1D data
119    """
120    def __init__(self, model,
121                 page_id,
122                 data,
123                 fid=None,
124                 qmin=None,
125                 qmax=None,
126                 weight=None,
127                 smearer=None,
128                 toggle_mode_on=False,
129                 state=None,
130                 completefn=None,
131                 update_chisqr=True,
132                 source='model',
133                 updatefn=None,
134                 yieldtime=0.01,
135                 worktime=0.01,
136                 exception_handler=None,
137                 ):
138        """
139        """
140        CalcThread.__init__(self, completefn, updatefn, yieldtime, worktime,
141                            exception_handler=exception_handler)
142        self.fid = fid
143        self.data = data
144        self.qmin = qmin
145        self.qmax = qmax
146        self.model = model
147        self.weight = weight
148        self.toggle_mode_on = toggle_mode_on
149        self.state = state
150        self.page_id = page_id
151        self.smearer = smearer
152        self.starttime = 0
153        self.update_chisqr = update_chisqr
154        self.source = source
155        self.out = None
156        self.index = None
157
158    def compute(self):
159        """
160        Compute model 1d value given qmin , qmax , x value
161        """
162        self.starttime = time.time()
163        output = numpy.zeros((len(self.data.x)))
164        index = (self.qmin <= self.data.x) & (self.data.x <= self.qmax)
165
166        intermediate_results = None
167
168        # If we use a smearer, also return the unsmeared model
169        unsmeared_output = None
170        unsmeared_data = None
171        unsmeared_error = None
172        ##smearer the ouput of the plot
173        if self.smearer is not None:
174            first_bin, last_bin = self.smearer.get_bin_range(self.qmin,
175                                                             self.qmax)
176            mask = self.data.x[first_bin:last_bin+1]
177            unsmeared_output = numpy.zeros((len(self.data.x)))
178
179            return_data = self.model.calculate_Iq(mask)
180            if isinstance(return_data, tuple):
181                # see sasmodels beta_approx: SasviewModel.calculate_Iq
182                # TODO: implement intermediate results in smearers
183                return_data, _ = return_data
184            unsmeared_output[first_bin:last_bin+1] = return_data
185            output = self.smearer(unsmeared_output, first_bin, last_bin)
186
187            # Rescale data to unsmeared model
188            # Check that the arrays are compatible. If we only have a model but no data,
189            # the length of data.y will be zero.
190            if isinstance(self.data.y, numpy.ndarray) and output.shape == self.data.y.shape:
191                unsmeared_data = numpy.zeros((len(self.data.x)))
192                unsmeared_error = numpy.zeros((len(self.data.x)))
193                unsmeared_data[first_bin:last_bin+1] = self.data.y[first_bin:last_bin+1]\
194                                                        * unsmeared_output[first_bin:last_bin+1]\
195                                                        / output[first_bin:last_bin+1]
196                unsmeared_error[first_bin:last_bin+1] = self.data.dy[first_bin:last_bin+1]\
197                                                        * unsmeared_output[first_bin:last_bin+1]\
198                                                        / output[first_bin:last_bin+1]
199                unsmeared_output=unsmeared_output[index]
200                unsmeared_data=unsmeared_data[index]
201                unsmeared_error=unsmeared_error
202        else:
203            return_data = self.model.calculate_Iq(self.data.x[index])
204            if isinstance(return_data, tuple):
205                # see sasmodels beta_approx: SasviewModel.calculate_Iq
206                return_data, intermediate_results = return_data
207            output[index] = return_data
208
209        if intermediate_results:
210            # the model returns a callable which is then used to retrieve the data
211            intermediate_results = intermediate_results()
212        else:
213            # TODO: this conditional branch needs refactoring
214            sq_values = None
215            pq_values = None
216            s_model = None
217            p_model = None
218
219            if isinstance(self.model, MultiplicationModel):
220                s_model = self.model.s_model
221                p_model = self.model.p_model
222
223            elif hasattr(self.model, "calc_composition_models"):
224                results = self.model.calc_composition_models(self.data.x[index])
225                if results is not None:
226                    pq_values, sq_values = results
227
228            if pq_values is None or sq_values is None:
229                if p_model is not None and s_model is not None:
230                    sq_values = numpy.zeros((len(self.data.x)))
231                    pq_values = numpy.zeros((len(self.data.x)))
232                    sq_values[index] = s_model.evalDistribution(self.data.x[index])
233                    pq_values[index] = p_model.evalDistribution(self.data.x[index])
234
235            if pq_values is not None and sq_values is not None:
236                intermediate_results  = {
237                    "P(Q)": pq_values,
238                    "S(Q)": sq_values
239                }
240            else:
241                intermediate_results = {}
242
243        elapsed = time.time() - self.starttime
244
245        res = dict(x = self.data.x[index], y = output[index],
246            page_id = self.page_id, state = self.state, weight = self.weight,
247            fid = self.fid, toggle_mode_on = self.toggle_mode_on,
248            elapsed = elapsed, index = index, model = self.model,
249            data = self.data, update_chisqr = self.update_chisqr,
250            source = self.source, unsmeared_output = unsmeared_output,
251            unsmeared_data = unsmeared_data, unsmeared_error = unsmeared_error,
252            intermediate_results = intermediate_results)
253
254        if LocalConfig.USING_TWISTED:
255            return res
256        else:
257            self.completefn(res)
258
259    def results(self):
260        """
261        Send resuts of the computation
262        """
263        return [self.out, self.index]
Note: See TracBrowser for help on using the repository browser.