source: sasview/src/sas/sasgui/perspectives/fitting/model_thread.py @ 83eb5208

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 83eb5208 was 9687d58, checked in by Piotr Rozyczko <rozyczko@…>, 8 years ago

Merge branch 'master' into ESS_GUI

  • Property mode set to 100644
File size: 11.5 KB
RevLine 
[f32d144]1"""
2    Calculation thread for modeling
3"""
[5062bbf]4
[bb18ef1]5import time
[7e7e806]6import numpy
7import math
[b699768]8from sas.sascalc.data_util.calcthread import CalcThread
[ca4d985]9from sas.sascalc.fit.MultiplicationModel import MultiplicationModel
[5062bbf]10
[bb18ef1]11class Calc2D(CalcThread):
12    """
[5062bbf]13    Compute 2D model
14    This calculation assumes a 2-fold symmetry of the model
15    where points are computed for one half of the detector
16    and I(qx, qy) = I(-qx, -qy) is assumed.
[bb18ef1]17    """
[f32d144]18    def __init__(self, data, model, smearer, qmin, qmax, page_id,
[5ef55d2]19                 state=None,
[62f851f]20                 weight=None,
[f64a4b7]21                 fid=None,
[fa65e99]22                 toggle_mode_on=False,
[7e7e806]23                 completefn=None,
24                 updatefn=None,
[2296316]25                 update_chisqr=True,
[e3f6ef5]26                 source='model',
[7e7e806]27                 yieldtime=0.04,
[934ce649]28                 worktime=0.04,
29                 exception_handler=None,
[bb18ef1]30                 ):
[934ce649]31        CalcThread.__init__(self, completefn, updatefn, yieldtime, worktime,
32                            exception_handler=exception_handler)
[7e7e806]33        self.qmin = qmin
34        self.qmax = qmax
[62f851f]35        self.weight = weight
[f64a4b7]36        self.fid = fid
[7e7e806]37        #self.qstep = qstep
[fa65e99]38        self.toggle_mode_on = toggle_mode_on
[7e7e806]39        self.data = data
[66ff250]40        self.page_id = page_id
[5ef55d2]41        self.state = None
[1b001a7]42        # the model on to calculate
[bb18ef1]43        self.model = model
[7e7e806]44        self.smearer = smearer
[f32d144]45        self.starttime = 0
[2296316]46        self.update_chisqr = update_chisqr
[e3f6ef5]47        self.source = source
[2f4b430]48
[bb18ef1]49    def compute(self):
50        """
[5062bbf]51        Compute the data given a model function
[bb18ef1]52        """
[1b001a7]53        self.starttime = time.time()
54        # Determine appropriate q range
[7e7e806]55        if self.qmin == None:
[c77d859]56            self.qmin = 0
[7e7e806]57        if self.qmax == None:
58            if self.data != None:
59                newx = math.pow(max(math.fabs(self.data.xmax),
60                                   math.fabs(self.data.xmin)), 2)
61                newy = math.pow(max(math.fabs(self.data.ymax),
62                                   math.fabs(self.data.ymin)), 2)
63                self.qmax = math.sqrt(newx + newy)
[2f4b430]64
[7e7e806]65        if self.data is None:
[f32d144]66            msg = "Compute Calc2D receive data = %s.\n" % str(self.data)
[7e7e806]67            raise ValueError, msg
[2f4b430]68
[f32d144]69        # Define matrix where data will be plotted
70        radius = numpy.sqrt((self.data.qx_data * self.data.qx_data) + \
[7e7e806]71                    (self.data.qy_data * self.data.qy_data))
[43e685d]72
[e575db9]73        # For theory, qmax is based on 1d qmax
74        # so that must be mulitified by sqrt(2) to get actual max for 2d
[7e7e806]75        index_model = (self.qmin <= radius) & (radius <= self.qmax)
76        index_model = index_model & self.data.mask
77        index_model = index_model & numpy.isfinite(self.data.data)
[2f4b430]78
[7e7e806]79        if self.smearer is not None:
[f72333f]80            # Set smearer w/ data, model and index.
81            fn = self.smearer
82            fn.set_model(self.model)
83            fn.set_index(index_model)
[f32d144]84            # Calculate smeared Intensity
[7e7e806]85            #(by Gaussian averaging): DataLoader/smearing2d/Smearer2D()
[f72333f]86            value = fn.get_value()
[f32d144]87        else:
[f72333f]88            # calculation w/o smearing
[d3911e3]89            value = self.model.evalDistribution([
90                self.data.qx_data[index_model],
91                self.data.qy_data[index_model]
92            ])
[7e7e806]93        output = numpy.zeros(len(self.data.qx_data))
[43e685d]94        # output default is None
[f32d144]95        # This method is to distinguish between masked
[7e7e806]96        #point(nan) and data point = 0.
[f32d144]97        output = output / output
[43e685d]98        # set value for self.mask==True, else still None to Plottools
[f32d144]99        output[index_model] = value
100        elapsed = time.time() - self.starttime
[cbcdd2c]101        #self.complete(image=output,
102        #               data=self.data,
103        #               page_id=self.page_id,
104        #               model=self.model,
105        #               state=self.state,
106        #               toggle_mode_on=self.toggle_mode_on,
107        #               elapsed=elapsed,
108        #               index=index_model,
109        #               fid=self.fid,
110        #               qmin=self.qmin,
111        #               qmax=self.qmax,
112        #               weight=self.weight,
113        #               #qstep=self.qstep,
114        #               update_chisqr=self.update_chisqr,
115        #               source=self.source)
116        return (output,
117                self.data,
118                self.page_id,
119                self.model,
120                self.state,
121                self.toggle_mode_on,
122                elapsed,
123                index_model,
124                self.fid,
125                self.qmin,
126                self.qmax,
127                self.weight,
128                self.update_chisqr,
129                self.source)
[2f4b430]130
[bb18ef1]131
132class Calc1D(CalcThread):
[5062bbf]133    """
134    Compute 1D data
135    """
[7e7e806]136    def __init__(self, model,
[66ff250]137                 page_id,
[7e7e806]138                 data,
[f64a4b7]139                 fid=None,
[bb18ef1]140                 qmin=None,
141                 qmax=None,
[62f851f]142                 weight=None,
[bb18ef1]143                 smearer=None,
[fa65e99]144                 toggle_mode_on=False,
[5ef55d2]145                 state=None,
[f32d144]146                 completefn=None,
[2296316]147                 update_chisqr=True,
[e3f6ef5]148                 source='model',
[7e7e806]149                 updatefn=None,
150                 yieldtime=0.01,
[934ce649]151                 worktime=0.01,
152                 exception_handler=None,
[bb18ef1]153                 ):
[5062bbf]154        """
155        """
[934ce649]156        CalcThread.__init__(self, completefn, updatefn, yieldtime, worktime,
157                            exception_handler=exception_handler)
[f64a4b7]158        self.fid = fid
[fa65e99]159        self.data = data
160        self.qmin = qmin
161        self.qmax = qmax
[bb18ef1]162        self.model = model
[62f851f]163        self.weight = weight
[fa65e99]164        self.toggle_mode_on = toggle_mode_on
[5ef55d2]165        self.state = state
[66ff250]166        self.page_id = page_id
[fa65e99]167        self.smearer = smearer
[bb18ef1]168        self.starttime = 0
[2296316]169        self.update_chisqr = update_chisqr
[e3f6ef5]170        self.source = source
[da7cacb]171        self.out = None
172        self.index = None
[2f4b430]173
[bb18ef1]174    def compute(self):
[c77d859]175        """
[f32d144]176        Compute model 1d value given qmin , qmax , x value
[c77d859]177        """
[bb18ef1]178        self.starttime = time.time()
[7e7e806]179        output = numpy.zeros((len(self.data.x)))
[f32d144]180        index = (self.qmin <= self.data.x) & (self.data.x <= self.qmax)
[2f4b430]181
[c807957]182        # If we use a smearer, also return the unsmeared model
[804fefa]183        unsmeared_output = None
184        unsmeared_data = None
185        unsmeared_error = None
[f32d144]186        ##smearer the ouput of the plot
[7e7e806]187        if self.smearer is not None:
[f32d144]188            first_bin, last_bin = self.smearer.get_bin_range(self.qmin,
[7e7e806]189                                                             self.qmax)
[a3f125f0]190            mask = self.data.x[first_bin:last_bin+1]
[804fefa]191            unsmeared_output = numpy.zeros((len(self.data.x)))
192            unsmeared_output[first_bin:last_bin+1] = self.model.evalDistribution(mask)
193            output = self.smearer(unsmeared_output, first_bin, last_bin)
[286c757]194
[804fefa]195            # Rescale data to unsmeared model
[286c757]196            # Check that the arrays are compatible. If we only have a model but no data,
197            # the length of data.y will be zero.
198            if isinstance(self.data.y, numpy.ndarray) and output.shape == self.data.y.shape:
199                unsmeared_data = numpy.zeros((len(self.data.x)))
200                unsmeared_error = numpy.zeros((len(self.data.x)))
201                unsmeared_data[first_bin:last_bin+1] = self.data.y[first_bin:last_bin+1]\
202                                                        * unsmeared_output[first_bin:last_bin+1]\
203                                                        / output[first_bin:last_bin+1]
204                unsmeared_error[first_bin:last_bin+1] = self.data.dy[first_bin:last_bin+1]\
205                                                        * unsmeared_output[first_bin:last_bin+1]\
206                                                        / output[first_bin:last_bin+1]
207                unsmeared_output=unsmeared_output[index]
208                unsmeared_data=unsmeared_data[index]
209                unsmeared_error=unsmeared_error
[e627f19]210        else:
[7e7e806]211            output[index] = self.model.evalDistribution(self.data.x[index])
[2f4b430]212
[b0bebdc]213        sq_values = None
214        pq_values = None
215        s_model = None
216        p_model = None
[ca4d985]217        if isinstance(self.model, MultiplicationModel):
[b0bebdc]218            s_model = self.model.s_model
219            p_model = self.model.p_model
[c1681ea]220        elif hasattr(self.model, "get_composition_models"):
[b0bebdc]221            p_model, s_model = self.model.get_composition_models()
222
223        if p_model is not None and s_model is not None:
224            sq_values = numpy.zeros((len(self.data.x)))
225            pq_values = numpy.zeros((len(self.data.x)))
226            sq_values[index] = s_model.evalDistribution(self.data.x[index])
227            pq_values[index] = p_model.evalDistribution(self.data.x[index])
[ca4d985]228
[5062bbf]229        elapsed = time.time() - self.starttime
[2f4b430]230
[cbcdd2c]231        #self.complete(x=self.data.x[index], y=output[index],
232        #              page_id=self.page_id,
233        #              state=self.state,
234        #              weight=self.weight,
235        #              fid=self.fid,
236        #              toggle_mode_on=self.toggle_mode_on,
237        #              elapsed=elapsed, index=index, model=self.model,
238        #              data=self.data,
239        #              update_chisqr=self.update_chisqr,
240        #              source=self.source)
241        return (self.data.x[index], output[index],
242                self.page_id,
243                self.state,
244                self.weight,
245                self.fid,
246                self.toggle_mode_on,
247                elapsed, index, self.model,
248                self.data,
249                self.update_chisqr,
250                self.source)
[2f4b430]251
[9687d58]252        # TODO: as of 4.1, the output contains more items:
253        # unsmeared_* and pq_model/sq_model
254        # Need to add these too
255
256        #self.complete(x=self.data.x[index], y=output[index],
257        #              page_id=self.page_id,
258        #              state=self.state,
259        #              weight=self.weight,
260        #              fid=self.fid,
261        #              toggle_mode_on=self.toggle_mode_on,
262        #              elapsed=elapsed, index=index, model=self.model,
263        #              data=self.data,
264        #              update_chisqr=self.update_chisqr,
265        #              source=self.source,
266        #              unsmeared_model=unsmeared_output,
267        #              unsmeared_data=unsmeared_data,
268        #              unsmeared_error=unsmeared_error,
269        #              pq_model=pq_values,
270        #              sq_model=sq_values)
[2f4b430]271
[f72333f]272    def results(self):
273        """
[5062bbf]274        Send resuts of the computation
[f72333f]275        """
276        return [self.out, self.index]
[5062bbf]277
278"""
279Example: ::
[2f4b430]280
[5062bbf]281    class CalcCommandline:
282        def __init__(self, n=20000):
283            #print thread.get_ident()
[79492222]284            from sas.models.CylinderModel import CylinderModel
[2f4b430]285
[5062bbf]286            model = CylinderModel()
[2f4b430]287
288
[5062bbf]289            print model.runXY([0.01, 0.02])
[2f4b430]290
[5062bbf]291            qmax = 0.01
292            qstep = 0.0001
293            self.done = False
[2f4b430]294
[5062bbf]295            x = numpy.arange(-qmax, qmax+qstep*0.01, qstep)
296            y = numpy.arange(-qmax, qmax+qstep*0.01, qstep)
[2f4b430]297
298
[5062bbf]299            calc_thread_2D = Calc2D(x, y, None, model.clone(),None,
300                                    -qmax, qmax,qstep,
301                                            completefn=self.complete,
302                                            updatefn=self.update ,
303                                            yieldtime=0.0)
[2f4b430]304
[5062bbf]305            calc_thread_2D.queue()
306            calc_thread_2D.ready(2.5)
[2f4b430]307
[5062bbf]308            while not self.done:
309                time.sleep(1)
[2f4b430]310
[5062bbf]311        def update(self,output):
312            print "update"
[2f4b430]313
[5062bbf]314        def complete(self, image, data, model, elapsed, qmin, qmax,index, qstep ):
315            print "complete"
316            self.done = True
[2f4b430]317
[5062bbf]318    if __name__ == "__main__":
319        CalcCommandline()
[f32d144]320"""
Note: See TracBrowser for help on using the repository browser.