source: sasview/src/sas/sasgui/perspectives/fitting/model_thread.py @ 24b3821

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.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 24b3821 was 24b3821, checked in by butler, 7 years ago

re-enable calculation/separation of P & S in SasView? (appearing under
the model they fit or in theory as appropriate) addresses #741

  • Property mode set to 100644
File size: 10.4 KB
RevLine 
[f32d144]1"""
2    Calculation thread for modeling
3"""
[5062bbf]4
[bb18ef1]5import time
[9a5097c]6import numpy as np
[7e7e806]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
[235f514]55        if self.qmin is None:
[c77d859]56            self.qmin = 0
[235f514]57        if self.qmax is None:
[7432acb]58            if self.data is not None:
[7e7e806]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
[9a5097c]70        radius = np.sqrt((self.data.qx_data * self.data.qx_data) + \
[7e7e806]71                    (self.data.qy_data * self.data.qy_data))
[43e685d]72
[24b3821]73        # For theory, qmax is based on 1d qmax
[e575db9]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
[9a5097c]77        index_model = index_model & np.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            ])
[24b3821]93        # Initialize output to NaN so masked elements do not get plotted.
94        output = np.empty_like(self.data.qx_data)
[43e685d]95        # output default is None
[f32d144]96        # This method is to distinguish between masked
[7e7e806]97        #point(nan) and data point = 0.
[24b3821]98        output[:] = np.NaN
[43e685d]99        # set value for self.mask==True, else still None to Plottools
[f32d144]100        output[index_model] = value
101        elapsed = time.time() - self.starttime
[6bbeacd4]102        self.complete(image=output,
[f32d144]103                       data=self.data,
[66ff250]104                       page_id=self.page_id,
[6bbeacd4]105                       model=self.model,
[5ef55d2]106                       state=self.state,
[fa65e99]107                       toggle_mode_on=self.toggle_mode_on,
[6bbeacd4]108                       elapsed=elapsed,
109                       index=index_model,
[f64a4b7]110                       fid=self.fid,
[6bbeacd4]111                       qmin=self.qmin,
112                       qmax=self.qmax,
[62f851f]113                       weight=self.weight,
[7e7e806]114                       #qstep=self.qstep,
[f32d144]115                       update_chisqr=self.update_chisqr,
[e3f6ef5]116                       source=self.source)
[2f4b430]117
[bb18ef1]118
119class Calc1D(CalcThread):
[5062bbf]120    """
121    Compute 1D data
122    """
[7e7e806]123    def __init__(self, model,
[66ff250]124                 page_id,
[7e7e806]125                 data,
[f64a4b7]126                 fid=None,
[bb18ef1]127                 qmin=None,
128                 qmax=None,
[62f851f]129                 weight=None,
[bb18ef1]130                 smearer=None,
[fa65e99]131                 toggle_mode_on=False,
[5ef55d2]132                 state=None,
[f32d144]133                 completefn=None,
[2296316]134                 update_chisqr=True,
[e3f6ef5]135                 source='model',
[7e7e806]136                 updatefn=None,
137                 yieldtime=0.01,
[934ce649]138                 worktime=0.01,
139                 exception_handler=None,
[bb18ef1]140                 ):
[5062bbf]141        """
142        """
[934ce649]143        CalcThread.__init__(self, completefn, updatefn, yieldtime, worktime,
144                            exception_handler=exception_handler)
[f64a4b7]145        self.fid = fid
[fa65e99]146        self.data = data
147        self.qmin = qmin
148        self.qmax = qmax
[bb18ef1]149        self.model = model
[62f851f]150        self.weight = weight
[fa65e99]151        self.toggle_mode_on = toggle_mode_on
[5ef55d2]152        self.state = state
[66ff250]153        self.page_id = page_id
[fa65e99]154        self.smearer = smearer
[bb18ef1]155        self.starttime = 0
[2296316]156        self.update_chisqr = update_chisqr
[e3f6ef5]157        self.source = source
[da7cacb]158        self.out = None
159        self.index = None
[2f4b430]160
[bb18ef1]161    def compute(self):
[c77d859]162        """
[f32d144]163        Compute model 1d value given qmin , qmax , x value
[c77d859]164        """
[bb18ef1]165        self.starttime = time.time()
[9a5097c]166        output = np.zeros((len(self.data.x)))
[f32d144]167        index = (self.qmin <= self.data.x) & (self.data.x <= self.qmax)
[2f4b430]168
[c807957]169        # If we use a smearer, also return the unsmeared model
[804fefa]170        unsmeared_output = None
171        unsmeared_data = None
172        unsmeared_error = None
[f32d144]173        ##smearer the ouput of the plot
[7e7e806]174        if self.smearer is not None:
[f32d144]175            first_bin, last_bin = self.smearer.get_bin_range(self.qmin,
[7e7e806]176                                                             self.qmax)
[a3f125f0]177            mask = self.data.x[first_bin:last_bin+1]
[9a5097c]178            unsmeared_output = np.zeros((len(self.data.x)))
[804fefa]179            unsmeared_output[first_bin:last_bin+1] = self.model.evalDistribution(mask)
[c1c9929]180            self.smearer.model = self.model
[804fefa]181            output = self.smearer(unsmeared_output, first_bin, last_bin)
[286c757]182
[804fefa]183            # Rescale data to unsmeared model
[286c757]184            # Check that the arrays are compatible. If we only have a model but no data,
185            # the length of data.y will be zero.
[9a5097c]186            if isinstance(self.data.y, np.ndarray) and output.shape == self.data.y.shape:
187                unsmeared_data = np.zeros((len(self.data.x)))
188                unsmeared_error = np.zeros((len(self.data.x)))
[286c757]189                unsmeared_data[first_bin:last_bin+1] = self.data.y[first_bin:last_bin+1]\
190                                                        * unsmeared_output[first_bin:last_bin+1]\
191                                                        / output[first_bin:last_bin+1]
192                unsmeared_error[first_bin:last_bin+1] = self.data.dy[first_bin:last_bin+1]\
193                                                        * unsmeared_output[first_bin:last_bin+1]\
194                                                        / output[first_bin:last_bin+1]
195                unsmeared_output=unsmeared_output[index]
196                unsmeared_data=unsmeared_data[index]
197                unsmeared_error=unsmeared_error
[e627f19]198        else:
[7e7e806]199            output[index] = self.model.evalDistribution(self.data.x[index])
[2f4b430]200
[24b3821]201        x=self.data.x[index]
202        y=output[index]
[b0bebdc]203        sq_values = None
204        pq_values = None
[ca4d985]205        if isinstance(self.model, MultiplicationModel):
[b0bebdc]206            s_model = self.model.s_model
207            p_model = self.model.p_model
[24b3821]208            #sq_values = np.zeros((len(self.data.x)))
209            #pq_values = np.zeros((len(self.data.x)))
210            #sq_values[index] = s_model.evalDistribution(self.data.x[index])
211            #pq_values[index] = p_model.evalDistribution(self.data.x[index])
212            sq_values = s_model.evalDistribution(x)
213            pq_values = p_model.evalDistribution(x)
214        elif hasattr(self.model, "calc_composition_models"):
215            results = self.model.calc_composition_models(x)
216            if results is not None:
217                sq_values = results[0]
218                pq_values = results[1]
[b0bebdc]219
[ca4d985]220
[5062bbf]221        elapsed = time.time() - self.starttime
[2f4b430]222
[24b3821]223        self.complete(x=x, y=y,
[66ff250]224                      page_id=self.page_id,
[5ef55d2]225                      state=self.state,
[62f851f]226                      weight=self.weight,
[f64a4b7]227                      fid=self.fid,
[fa65e99]228                      toggle_mode_on=self.toggle_mode_on,
[f32d144]229                      elapsed=elapsed, index=index, model=self.model,
230                      data=self.data,
231                      update_chisqr=self.update_chisqr,
[c807957]232                      source=self.source,
[804fefa]233                      unsmeared_model=unsmeared_output,
234                      unsmeared_data=unsmeared_data,
[ca4d985]235                      unsmeared_error=unsmeared_error,
[b0bebdc]236                      pq_model=pq_values,
237                      sq_model=sq_values)
[2f4b430]238
[f72333f]239    def results(self):
240        """
[5062bbf]241        Send resuts of the computation
[f72333f]242        """
243        return [self.out, self.index]
[5062bbf]244
245"""
246Example: ::
[2f4b430]247
[5062bbf]248    class CalcCommandline:
249        def __init__(self, n=20000):
250            #print thread.get_ident()
[79492222]251            from sas.models.CylinderModel import CylinderModel
[2f4b430]252
[5062bbf]253            model = CylinderModel()
[2f4b430]254
255
[5062bbf]256            print model.runXY([0.01, 0.02])
[2f4b430]257
[5062bbf]258            qmax = 0.01
259            qstep = 0.0001
260            self.done = False
[2f4b430]261
[5062bbf]262            x = numpy.arange(-qmax, qmax+qstep*0.01, qstep)
263            y = numpy.arange(-qmax, qmax+qstep*0.01, qstep)
[2f4b430]264
265
[5062bbf]266            calc_thread_2D = Calc2D(x, y, None, model.clone(),None,
267                                    -qmax, qmax,qstep,
268                                            completefn=self.complete,
269                                            updatefn=self.update ,
270                                            yieldtime=0.0)
[2f4b430]271
[5062bbf]272            calc_thread_2D.queue()
273            calc_thread_2D.ready(2.5)
[2f4b430]274
[5062bbf]275            while not self.done:
276                time.sleep(1)
[2f4b430]277
[5062bbf]278        def update(self,output):
279            print "update"
[2f4b430]280
[5062bbf]281        def complete(self, image, data, model, elapsed, qmin, qmax,index, qstep ):
282            print "complete"
283            self.done = True
[2f4b430]284
[5062bbf]285    if __name__ == "__main__":
286        CalcCommandline()
[f32d144]287"""
Note: See TracBrowser for help on using the repository browser.