source: sasview/sansinvariant/invariant.py @ ad4053a

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.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since ad4053a was ad4053a, checked in by Jessica Tumarkin <jtumarki@…>, 13 years ago
  • Property mode set to 100644
File size: 36.0 KB
Line 
1#####################################################################
2#This software was developed by the University of Tennessee as part of the
3#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
4#project funded by the US National Science Foundation.
5#See the license text in license.txt
6#copyright 2010, University of Tennessee
7######################################################################
8
9"""
10This module implements invariant and its related computations.
11
12:author: Gervaise B. Alina/UTK
13:author: Mathieu Doucet/UTK
14:author: Jae Cho/UTK
15
16"""
17import math 
18import numpy
19
20from DataLoader.data_info import Data1D as LoaderData1D
21
22# The minimum q-value to be used when extrapolating
23Q_MINIMUM  = 1e-5
24
25# The maximum q-value to be used when extrapolating
26Q_MAXIMUM  = 10
27
28# Number of steps in the extrapolation
29INTEGRATION_NSTEPS = 1000
30
31class Transform(object):
32    """
33    Define interface that need to compute a function or an inverse
34    function given some x, y
35    """
36   
37    def linearize_data(self, data):
38        """
39        Linearize data so that a linear fit can be performed.
40        Filter out the data that can't be transformed.
41       
42        :param data: LoadData1D instance
43       
44        """
45        # Check that the vector lengths are equal
46        assert(len(data.x)==len(data.y))
47        if data.dy is not None:
48            assert(len(data.x)==len(data.dy))
49            dy = data.dy
50        else:
51            dy = numpy.ones(len(data.y))
52           
53        # Transform the data
54        data_points = zip(data.x, data.y, dy)
55
56        output_points = [(self.linearize_q_value(p[0]),
57                          math.log(p[1]),
58                          p[2]/p[1]) for p in data_points if p[0]>0 and \
59                          p[1]>0 and p[2]>0]
60       
61        x_out, y_out, dy_out = zip(*output_points)
62       
63        # Create Data1D object
64        x_out = numpy.asarray(x_out)
65        y_out = numpy.asarray(y_out)
66        dy_out = numpy.asarray(dy_out)
67        linear_data = LoaderData1D(x=x_out, y=y_out, dy=dy_out)
68       
69        return linear_data
70   
71    def get_allowed_bins(self, data):
72        """
73        Goes through the data points and returns a list of boolean values
74        to indicate whether each points is allowed by the model or not.
75       
76        :param data: Data1D object
77        """
78        return [p[0]>0 and p[1]>0 and p[2]>0 for p in zip(data.x, data.y,
79                                                           data.dy)]
80       
81    def linearize_q_value(self, value):
82        """
83        Transform the input q-value for linearization
84        """
85        return NotImplemented
86
87    def extract_model_parameters(self, constant, slope, dconstant=0, dslope=0):
88        """
89        set private member
90        """
91        return NotImplemented
92     
93    def evaluate_model(self, x):
94        """
95        Returns an array f(x) values where f is the Transform function.
96        """
97        return NotImplemented
98   
99    def evaluate_model_errors(self, x):
100        """
101        Returns an array of I(q) errors
102        """
103        return NotImplemented
104   
105class Guinier(Transform):
106    """
107    class of type Transform that performs operations related to guinier
108    function
109    """
110    def __init__(self, scale=1, radius=60):
111        Transform.__init__(self)
112        self.scale = scale
113        self.radius = radius
114        ## Uncertainty of scale parameter
115        self.dscale  = 0
116        ## Unvertainty of radius parameter
117        self.dradius = 0
118       
119    def linearize_q_value(self, value):
120        """
121        Transform the input q-value for linearization
122       
123        :param value: q-value
124       
125        :return: q*q
126        """
127        return value * value
128   
129    def extract_model_parameters(self, constant, slope, dconstant=0, dslope=0):
130        """
131            assign new value to the scale and the radius
132        """
133        self.scale = math.exp(constant)
134        self.radius = math.sqrt(-3 * slope)
135       
136        # Errors
137        self.dscale = math.exp(constant)*dconstant
138        self.dradius = -3.0/2.0/math.sqrt(-3 * slope)*dslope
139       
140        return [self.radius, self.scale], [self.dradius, self.dscale]
141       
142    def evaluate_model(self, x):
143        """
144        return F(x)= scale* e-((radius*x)**2/3)
145        """
146        return self._guinier(x)
147             
148    def evaluate_model_errors(self, x):
149        """
150        Returns the error on I(q) for the given array of q-values
151       
152        :param x: array of q-values
153        """
154        p1 = numpy.array([self.dscale * math.exp(-((self.radius * q)**2/3)) \
155                          for q in x])
156        p2 = numpy.array([self.scale * math.exp(-((self.radius * q)**2/3))\
157                     * (-(q**2/3)) * 2 * self.radius * self.dradius for q in x])
158        diq2 = p1*p1 + p2*p2       
159        return numpy.array( [math.sqrt(err) for err in diq2] )
160             
161    def _guinier(self, x):
162        """
163        Retrive the guinier function after apply an inverse guinier function
164        to x
165        Compute a F(x) = scale* e-((radius*x)**2/3).
166       
167        :param x: a vector of q values
168        :param scale: the scale value
169        :param radius: the guinier radius value
170       
171        :return: F(x)
172        """   
173        # transform the radius of coming from the inverse guinier function to a
174        # a radius of a guinier function
175        if self.radius <= 0:
176            msg = "Rg expected positive value, but got %s"%self.radius
177            raise ValueError(msg) 
178        value = numpy.array([math.exp(-((self.radius * i)**2/3)) for i in x ]) 
179        return self.scale * value
180
181class PowerLaw(Transform):
182    """
183    class of type transform that perform operation related to power_law
184    function
185    """
186    def __init__(self, scale=1, power=4):
187        Transform.__init__(self)
188        self.scale = scale
189        self.power = power
190   
191    def linearize_q_value(self, value):
192        """
193        Transform the input q-value for linearization
194       
195        :param value: q-value
196       
197        :return: log(q)
198        """
199        return math.log(value)
200   
201    def extract_model_parameters(self, constant, slope, dconstant=0, dslope=0):
202        """
203        Assign new value to the scale and the power
204        """
205        self.power = -slope
206        self.scale = math.exp(constant)
207       
208        # Errors
209        self.dscale = math.exp(constant)*dconstant
210        self.dpower = -dslope
211       
212        return [self.power, self.scale], [self.dpower, self.dscale]
213       
214    def evaluate_model(self, x):
215        """
216        given a scale and a radius transform x, y using a power_law
217        function
218        """
219        return self._power_law(x)
220   
221    def evaluate_model_errors(self, x):
222        """
223        Returns the error on I(q) for the given array of q-values
224        :param x: array of q-values
225        """
226        p1 = numpy.array([self.dscale * math.pow(q, -self.power) for q in x])
227        p2 = numpy.array([self.scale * self.power * math.pow(q, -self.power-1)\
228                           * self.dpower for q in x])
229        diq2 = p1*p1 + p2*p2       
230        return numpy.array( [math.sqrt(err) for err in diq2] )
231       
232    def _power_law(self, x):
233        """
234        F(x) = scale* (x)^(-power)
235            when power= 4. the model is porod
236            else power_law
237        The model has three parameters: ::
238            1. x: a vector of q values
239            2. power: power of the function
240            3. scale : scale factor value
241       
242        :param x: array
243        :return: F(x)
244        """
245        if self.power <= 0:
246            msg = "Power_law function expected positive power,"
247            msg += " but got %s"%self.power
248            raise ValueError(msg)
249        if self.scale <= 0:
250            msg = "scale expected positive value, but got %s"%self.scale
251            raise ValueError(msg) 
252       
253        value = numpy.array([ math.pow(i, -self.power) for i in x ]) 
254        return self.scale * value
255
256class Extrapolator:
257    """
258    Extrapolate I(q) distribution using a given model
259    """
260    def __init__(self, data, model=None):
261        """
262        Determine a and b given a linear equation y = ax + b
263       
264        If a model is given, it will be used to linearize the data before
265        the extrapolation is performed. If None,
266        a simple linear fit will be done.
267       
268        :param data: data containing x and y  such as  y = ax + b
269        :param model: optional Transform object
270        """
271        self.data  = data
272        self.model = model
273       
274        # Set qmin as the lowest non-zero value
275        self.qmin = Q_MINIMUM
276        for q_value in self.data.x:
277            if q_value > 0: 
278                self.qmin = q_value
279                break
280        self.qmax = max(self.data.x)
281             
282    def fit(self, power=None, qmin=None, qmax=None):
283        """
284        Fit data for y = ax + b  return a and b
285       
286        :param power: a fixed, otherwise None
287        :param qmin: Minimum Q-value
288        :param qmax: Maximum Q-value
289        """
290        if qmin is None:
291            qmin = self.qmin
292        if qmax is None:
293            qmax = self.qmax
294           
295        # Identify the bin range for the fit
296        idx = (self.data.x >= qmin) & (self.data.x <= qmax)
297       
298        fx = numpy.zeros(len(self.data.x))
299
300        # Uncertainty
301        if type(self.data.dy)==numpy.ndarray and \
302            len(self.data.dy)==len(self.data.x):
303            sigma = self.data.dy
304        else:
305            sigma = numpy.ones(len(self.data.x))
306           
307        # Compute theory data f(x)
308        fx[idx] = self.data.y[idx]
309       
310        # Linearize the data
311        if self.model is not None:
312            linearized_data = self.model.linearize_data(\
313                                            LoaderData1D(self.data.x[idx],
314                                                                fx[idx],
315                                                            dy = sigma[idx]))
316        else:
317            linearized_data = LoaderData1D(self.data.x[idx],
318                                           fx[idx],
319                                           dy = sigma[idx])
320       
321        ##power is given only for function = power_law   
322        if power != None:
323            sigma2 = linearized_data.dy * linearized_data.dy
324            a = -(power)
325            b = (numpy.sum(linearized_data.y/sigma2) \
326                 - a*numpy.sum(linearized_data.x/sigma2))/numpy.sum(1.0/sigma2)
327           
328           
329            deltas = linearized_data.x*a + \
330                    numpy.ones(len(linearized_data.x))*b-linearized_data.y
331            residuals = numpy.sum(deltas*deltas/sigma2)
332           
333            err = math.fabs(residuals) / numpy.sum(1.0/sigma2)
334            return [a, b], [0, math.sqrt(err)]
335        else:
336            A = numpy.vstack([ linearized_data.x/linearized_data.dy,
337                               1.0/linearized_data.dy]).T       
338            (p, residuals, rank, s) = numpy.linalg.lstsq(A,
339                                        linearized_data.y/linearized_data.dy)
340           
341            # Get the covariance matrix, defined as inv_cov = a_transposed * a
342            err = numpy.zeros(2)
343            try:
344                inv_cov = numpy.dot(A.transpose(), A)
345                cov = numpy.linalg.pinv(inv_cov)
346                err_matrix = math.fabs(residuals) * cov
347                err = [math.sqrt(err_matrix[0][0]), math.sqrt(err_matrix[1][1])]
348            except:
349                err = [-1.0, -1.0]
350               
351            return p, err
352       
353
354class InvariantCalculator(object):
355    """
356    Compute invariant if data is given.
357    Can provide volume fraction and surface area if the user provides
358    Porod constant  and contrast values.
359   
360    :precondition:  the user must send a data of type DataLoader.Data1D
361                    the user provide background and scale values.
362                   
363    :note: Some computations depends on each others.
364    """
365    def __init__(self, data, background=0, scale=1 ):
366        """
367        Initialize variables.
368       
369        :param data: data must be of type DataLoader.Data1D
370        :param background: Background value. The data will be corrected
371            before processing
372        :param scale: Scaling factor for I(q). The data will be corrected
373            before processing
374        """
375        # Background and scale should be private data member if the only way to
376        # change them are by instantiating a new object.
377        self._background = background
378        self._scale = scale
379        # slit height for smeared data
380        self._smeared = None
381        # The data should be private
382        self._data = self._get_data(data)
383        # get the dxl if the data is smeared: This is done only once on init.
384        if self._data.dxl != None and self._data.dxl.all() >0:
385            # assumes constant dxl
386            self._smeared = self._data.dxl[0]
387     
388        # Since there are multiple variants of Q*, you should force the
389        # user to use the get method and keep Q* a private data member
390        self._qstar = None
391       
392        # You should keep the error on Q* so you can reuse it without
393        # recomputing the whole thing.
394        self._qstar_err = 0
395       
396        # Extrapolation parameters
397        self._low_extrapolation_npts = 4
398        self._low_extrapolation_function = Guinier()
399        self._low_extrapolation_power = None
400        self._low_extrapolation_power_fitted = None
401   
402        self._high_extrapolation_npts = 4
403        self._high_extrapolation_function = PowerLaw()
404        self._high_extrapolation_power = None
405        self._high_extrapolation_power_fitted = None
406       
407        # Extrapolation range
408        self._low_q_limit = Q_MINIMUM
409       
410    def _get_data(self, data):
411        """
412        :note: this function must be call before computing any type
413         of invariant
414         
415        :return: new data = self._scale *data - self._background
416        """
417        if not issubclass(data.__class__, LoaderData1D):
418            #Process only data that inherited from DataLoader.Data_info.Data1D
419            raise ValueError,"Data must be of type DataLoader.Data1D"
420        #from copy import deepcopy
421        new_data = (self._scale * data) - self._background   
422       
423        # Check that the vector lengths are equal
424        assert(len(new_data.x)==len(new_data.y))
425       
426        # Verify that the errors are set correctly
427        if new_data.dy is None or len(new_data.x) != len(new_data.dy) or \
428            (min(new_data.dy)==0 and max(new_data.dy)==0):
429            new_data.dy = numpy.ones(len(new_data.x)) 
430        return  new_data
431     
432    def _fit(self, model, qmin=Q_MINIMUM, qmax=Q_MAXIMUM, power=None):
433        """
434        fit data with function using
435        data = self._get_data()
436        fx = Functor(data , function)
437        y = data.y
438        slope, constant = linalg.lstsq(y,fx)
439       
440        :param qmin: data first q value to consider during the fit
441        :param qmax: data last q value to consider during the fit
442        :param power : power value to consider for power-law
443        :param function: the function to use during the fit
444       
445        :return a: the scale of the function
446        :return b: the other parameter of the function for guinier will be radius
447                for power_law will be the power value
448        """
449        extrapolator = Extrapolator(data=self._data, model=model)
450        p, dp = extrapolator.fit(power=power, qmin=qmin, qmax=qmax) 
451       
452        return model.extract_model_parameters(constant=p[1], slope=p[0],
453                                              dconstant=dp[1], dslope=dp[0])
454   
455    def _get_qstar(self, data):
456        """
457        Compute invariant for pinhole data.
458        This invariant is given by: ::
459   
460            q_star = x0**2 *y0 *dx0 +x1**2 *y1 *dx1
461                        + ..+ xn**2 *yn *dxn    for non smeared data
462                       
463            q_star = dxl0 *x0 *y0 *dx0 +dxl1 *x1 *y1 *dx1
464                        + ..+ dlxn *xn *yn *dxn    for smeared data
465                       
466            where n >= len(data.x)-1
467            dxl = slit height dQl
468            dxi = 1/2*(xi+1 - xi) + (xi - xi-1)
469            dx0 = (x1 - x0)/2
470            dxn = (xn - xn-1)/2
471           
472        :param data: the data to use to compute invariant.
473       
474        :return q_star: invariant value for pinhole data. q_star > 0
475        """
476        if len(data.x) <= 1 or len(data.y) <= 1 or len(data.x)!= len(data.y):
477            msg =  "Length x and y must be equal"
478            msg += " and greater than 1; got x=%s, y=%s"%(len(data.x),
479                                                          len(data.y))
480            raise ValueError, msg
481        else:
482            # Take care of smeared data
483            if self._smeared is None:
484                gx = data.x * data.x
485            # assumes that len(x) == len(dxl).
486            else:               
487                gx = data.dxl * data.x
488               
489            n = len(data.x)- 1
490            #compute the first delta q
491            dx0 = (data.x[1] - data.x[0])/2
492            #compute the last delta q
493            dxn = (data.x[n] - data.x[n-1])/2
494            sum = 0
495            sum += gx[0] * data.y[0] * dx0
496            sum += gx[n] * data.y[n] * dxn
497           
498            if len(data.x) == 2:
499                return sum
500            else:
501                #iterate between for element different
502                #from the first and the last
503                for i in xrange(1, n-1):
504                    dxi = (data.x[i+1] - data.x[i-1])/2
505                    sum += gx[i] * data.y[i] * dxi
506                return sum
507           
508    def _get_qstar_uncertainty(self, data):
509        """
510        Compute invariant uncertainty with with pinhole data.
511        This uncertainty is given as follow: ::
512       
513           dq_star = math.sqrt[(x0**2*(dy0)*dx0)**2 +
514                (x1**2 *(dy1)*dx1)**2 + ..+ (xn**2 *(dyn)*dxn)**2 ]
515        where n >= len(data.x)-1
516        dxi = 1/2*(xi+1 - xi) + (xi - xi-1)
517        dx0 = (x1 - x0)/2
518        dxn = (xn - xn-1)/2
519        dyn: error on dy
520       
521        :param data:
522        :note: if data doesn't contain dy assume dy= math.sqrt(data.y)
523        """         
524        if len(data.x) <= 1 or len(data.y) <= 1 or \
525            len(data.x) != len(data.y) or \
526            (data.dy is not None and (len(data.dy) != len(data.y))):
527            msg = "Length of data.x and data.y must be equal"
528            msg += " and greater than 1; got x=%s, y=%s"%(len(data.x),
529                                                         len(data.y))
530            raise ValueError, msg
531        else:
532            #Create error for data without dy error
533            if data.dy is None:
534                dy = math.sqrt(y) 
535            else:
536                dy = data.dy
537            # Take care of smeared data
538            if self._smeared is None:
539                gx = data.x * data.x
540            # assumes that len(x) == len(dxl).
541            else:
542                gx = data.dxl * data.x
543 
544            n = len(data.x) - 1
545            #compute the first delta
546            dx0 = (data.x[1] - data.x[0])/2
547            #compute the last delta
548            dxn= (data.x[n] - data.x[n-1])/2
549            sum = 0
550            sum += (gx[0] * dy[0] * dx0)**2
551            sum += (gx[n] * dy[n] * dxn)**2
552            if len(data.x) == 2:
553                return math.sqrt(sum)
554            else:
555                #iterate between for element different
556                #from the first and the last
557                for i in xrange(1, n-1):
558                    dxi = (data.x[i+1] - data.x[i-1])/2
559                    sum += (gx[i] * dy[i] * dxi)**2
560                return math.sqrt(sum)
561       
562    def _get_extrapolated_data(self, model, npts=INTEGRATION_NSTEPS,
563                              q_start=Q_MINIMUM, q_end=Q_MAXIMUM):
564        """
565        :return: extrapolate data create from data
566        """
567        #create new Data1D to compute the invariant
568        q = numpy.linspace(start=q_start,
569                           stop=q_end,
570                           num=npts,
571                           endpoint=True)
572        iq = model.evaluate_model(q)
573        diq = model.evaluate_model_errors(q)
574         
575        result_data = LoaderData1D(x=q, y=iq, dy=diq)
576        if self._smeared != None:
577            result_data.dxl = self._smeared * numpy.ones(len(q))
578        return result_data
579   
580    def get_data(self):
581        """
582        :return: self._data
583        """
584        return self._data
585   
586    def get_extrapolation_power(self, range='high'):
587        """
588        :return: the fitted power for power law function for a given
589            extrapolation range
590        """
591        if range == 'low':
592            return self._low_extrapolation_power_fitted
593        return self._high_extrapolation_power_fitted
594   
595    def get_qstar_low(self):
596        """
597        Compute the invariant for extrapolated data at low q range.
598       
599        Implementation:
600            data = self._get_extra_data_low()
601            return self._get_qstar()
602           
603        :return q_star: the invariant for data extrapolated at low q.
604        """
605        # Data boundaries for fitting
606        qmin = self._data.x[0]
607        qmax = self._data.x[self._low_extrapolation_npts - 1]
608       
609        # Extrapolate the low-Q data
610        p, dp = self._fit(model=self._low_extrapolation_function,
611                              qmin=qmin,
612                          qmax=qmax,
613                          power=self._low_extrapolation_power)
614        self._low_extrapolation_power_fitted = p[0]
615       
616        # Distribution starting point
617        self._low_q_limit = Q_MINIMUM
618        if Q_MINIMUM >= qmin:
619            self._low_q_limit = qmin/10
620       
621        data = self._get_extrapolated_data(\
622                                    model=self._low_extrapolation_function,
623                                            npts=INTEGRATION_NSTEPS,
624                                        q_start=self._low_q_limit, q_end=qmin)
625       
626        # Systematic error
627        # If we have smearing, the shape of the I(q) distribution at low Q will
628        # may not be a Guinier or simple power law. The following is
629        # a conservative estimation for the systematic error.
630        err = qmin*qmin*math.fabs((qmin-self._low_q_limit)*\
631                                  (data.y[0] - data.y[INTEGRATION_NSTEPS-1]))
632        return self._get_qstar(data), self._get_qstar_uncertainty(data)+err
633       
634    def get_qstar_high(self):
635        """
636        Compute the invariant for extrapolated data at high q range.
637       
638        Implementation:
639            data = self._get_extra_data_high()
640            return self._get_qstar()
641           
642        :return q_star: the invariant for data extrapolated at high q.
643        """
644        # Data boundaries for fitting
645        x_len = len(self._data.x) - 1
646        qmin = self._data.x[x_len - (self._high_extrapolation_npts - 1)]
647        qmax = self._data.x[x_len]
648       
649        # fit the data with a model to get the appropriate parameters
650        p, dp = self._fit(model=self._high_extrapolation_function,
651                          qmin=qmin,
652                          qmax=qmax,
653                          power=self._high_extrapolation_power)
654        self._high_extrapolation_power_fitted = p[0]
655       
656        #create new Data1D to compute the invariant
657        data = self._get_extrapolated_data(\
658                                    model=self._high_extrapolation_function,
659                                           npts=INTEGRATION_NSTEPS,
660                                           q_start=qmax, q_end=Q_MAXIMUM)       
661       
662        return self._get_qstar(data), self._get_qstar_uncertainty(data)
663   
664    def get_extra_data_low(self, npts_in=None, q_start=None, npts=20):
665        """
666        Returns the extrapolated data used for the loew-Q invariant calculation.
667        By default, the distribution will cover the data points used for the
668        extrapolation. The number of overlap points is a parameter (npts_in).
669        By default, the maximum q-value of the distribution will be 
670        the minimum q-value used when extrapolating for the purpose of the
671        invariant calculation.
672       
673        :param npts_in: number of data points for which
674            the extrapolated data overlap
675        :param q_start: is the minimum value to uses for extrapolated data
676        :param npts: the number of points in the extrapolated distribution
677           
678        """
679        # Get extrapolation range
680        if q_start is None:
681            q_start = self._low_q_limit
682           
683        if npts_in is None:
684            npts_in = self._low_extrapolation_npts
685        q_end = self._data.x[max(0, npts_in-1)]
686       
687        if q_start >= q_end:
688            return numpy.zeros(0), numpy.zeros(0)
689
690        return self._get_extrapolated_data(\
691                                    model=self._low_extrapolation_function,
692                                           npts=npts,
693                                           q_start=q_start, q_end=q_end)
694         
695    def get_extra_data_high(self, npts_in=None, q_end=Q_MAXIMUM, npts=20):
696        """
697        Returns the extrapolated data used for the high-Q invariant calculation.
698        By default, the distribution will cover the data points used for the
699        extrapolation. The number of overlap points is a parameter (npts_in).
700        By default, the maximum q-value of the distribution will be Q_MAXIMUM,
701        the maximum q-value used when extrapolating for the purpose of the
702        invariant calculation.
703       
704        :param npts_in: number of data points for which the
705            extrapolated data overlap
706        :param q_end: is the maximum value to uses for extrapolated data
707        :param npts: the number of points in the extrapolated distribution
708        """
709        # Get extrapolation range
710        if npts_in is None:
711            npts_in = self._high_extrapolation_npts
712        _npts = len(self._data.x)
713        q_start = self._data.x[min(_npts, _npts-npts_in)]
714       
715        if q_start >= q_end:
716            return numpy.zeros(0), numpy.zeros(0)
717       
718        return self._get_extrapolated_data(\
719                                model=self._high_extrapolation_function,
720                                           npts=npts,
721                                           q_start=q_start, q_end=q_end)
722     
723    def set_extrapolation(self, range, npts=4, function=None, power=None):
724        """
725        Set the extrapolation parameters for the high or low Q-range.
726        Note that this does not turn extrapolation on or off.
727       
728        :param range: a keyword set the type of extrapolation . type string
729        :param npts: the numbers of q points of data to consider
730            for extrapolation
731        :param function: a keyword to select the function to use
732            for extrapolation.
733            of type string.
734        :param power: an power to apply power_low function
735               
736        """
737        range = range.lower()
738        if range not in ['high', 'low']:
739            raise ValueError, "Extrapolation range should be 'high' or 'low'"
740        function = function.lower()
741        if function not in ['power_law', 'guinier']:
742            msg = "Extrapolation function should be 'guinier' or 'power_law'"
743            raise ValueError, msg
744       
745        if range == 'high':
746            if function != 'power_law':
747                msg = "Extrapolation only allows a power law at high Q"
748                raise ValueError, msg
749            self._high_extrapolation_npts  = npts
750            self._high_extrapolation_power = power
751            self._high_extrapolation_power_fitted = power
752        else:
753            if function == 'power_law':
754                self._low_extrapolation_function = PowerLaw()
755            else:
756                self._low_extrapolation_function = Guinier()
757            self._low_extrapolation_npts  = npts
758            self._low_extrapolation_power = power
759            self._low_extrapolation_power_fitted = power
760       
761    def get_qstar(self, extrapolation=None):
762        """
763        Compute the invariant of the local copy of data.
764       
765        :param extrapolation: string to apply optional extrapolation
766           
767        :return q_star: invariant of the data within data's q range
768       
769        :warning: When using setting data to Data1D ,
770            the user is responsible of
771            checking that the scale and the background are
772            properly apply to the data
773       
774        """
775        self._qstar = self._get_qstar(self._data)
776        self._qstar_err = self._get_qstar_uncertainty(self._data)
777       
778        if extrapolation is None:
779            return self._qstar
780       
781        # Compute invariant plus invariant of extrapolated data
782        extrapolation = extrapolation.lower()   
783        if extrapolation == "low":
784            qs_low, dqs_low = self.get_qstar_low()
785            qs_hi, dqs_hi   = 0, 0
786           
787        elif extrapolation == "high":
788            qs_low, dqs_low = 0, 0
789            qs_hi, dqs_hi   = self.get_qstar_high()
790           
791        elif extrapolation == "both":
792            qs_low, dqs_low = self.get_qstar_low()
793            qs_hi, dqs_hi   = self.get_qstar_high()
794           
795        self._qstar     += qs_low + qs_hi
796        self._qstar_err = math.sqrt(self._qstar_err*self._qstar_err \
797                                    + dqs_low*dqs_low + dqs_hi*dqs_hi)
798       
799        return self._qstar
800       
801    def get_surface(self, contrast, porod_const, extrapolation=None):
802        """
803        Compute the specific surface from the data.
804       
805        Implementation::
806       
807          V =  self.get_volume_fraction(contrast, extrapolation)
808   
809          Compute the surface given by:
810            surface = (2*pi *V(1- V)*porod_const)/ q_star
811           
812        :param contrast: contrast value to compute the volume
813        :param porod_const: Porod constant to compute the surface
814        :param extrapolation: string to apply optional extrapolation
815       
816        :return: specific surface
817        """
818        # Compute the volume
819        volume = self.get_volume_fraction(contrast, extrapolation)
820        return 2 * math.pi * volume *(1 - volume) * \
821            float(porod_const)/self._qstar
822       
823    def get_volume_fraction(self, contrast, extrapolation=None):
824        """
825        Compute volume fraction is deduced as follow: ::
826       
827            q_star = 2*(pi*contrast)**2* volume( 1- volume)
828            for k = 10^(-8)*q_star/(2*(pi*|contrast|)**2)
829            we get 2 values of volume:
830                 with   1 - 4 * k >= 0
831                 volume1 = (1- sqrt(1- 4*k))/2
832                 volume2 = (1+ sqrt(1- 4*k))/2
833           
834            q_star: the invariant value included extrapolation is applied
835                         unit  1/A^(3)*1/cm
836                    q_star = self.get_qstar()
837                   
838            the result returned will be 0 <= volume <= 1
839       
840        :param contrast: contrast value provides by the user of type float.
841                 contrast unit is 1/A^(2)= 10^(16)cm^(2)
842        :param extrapolation: string to apply optional extrapolation
843       
844        :return: volume fraction
845       
846        :note: volume fraction must have no unit
847        """
848        if contrast <= 0:
849            raise ValueError, "The contrast parameter must be greater than zero" 
850       
851        # Make sure Q star is up to date
852        self.get_qstar(extrapolation)
853       
854        if self._qstar <= 0:
855            msg = "Invalid invariant: Invariant Q* must be greater than zero"
856            raise RuntimeError, msg
857       
858        # Compute intermediate constant
859        k =  1.e-8 * self._qstar/(2 * (math.pi * math.fabs(float(contrast)))**2)
860        # Check discriminant value
861        discrim = 1 - 4 * k
862       
863        # Compute volume fraction
864        if discrim < 0:
865            msg = "Could not compute the volume fraction: negative discriminant"
866            raise RuntimeError, msg
867        elif discrim == 0:
868            return 1/2
869        else:
870            volume1 = 0.5 * (1 - math.sqrt(discrim))
871            volume2 = 0.5 * (1 + math.sqrt(discrim))
872           
873            if 0 <= volume1 and volume1 <= 1:
874                return volume1
875            elif 0 <= volume2 and volume2 <= 1: 
876                return volume2
877            msg = "Could not compute the volume fraction: inconsistent results"
878            raise RuntimeError, msg
879   
880    def get_qstar_with_error(self, extrapolation=None):
881        """
882        Compute the invariant uncertainty.
883        This uncertainty computation depends on whether or not the data is
884        smeared.
885       
886        :param extrapolation: string to apply optional extrapolation
887       
888        :return: invariant, the invariant uncertainty
889        """   
890        self.get_qstar(extrapolation)
891        return self._qstar, self._qstar_err
892   
893    def get_volume_fraction_with_error(self, contrast, extrapolation=None):
894        """
895        Compute uncertainty on volume value as well as the volume fraction
896        This uncertainty is given by the following equation: ::
897       
898            dV = 0.5 * (4*k* dq_star) /(2* math.sqrt(1-k* q_star))
899                                 
900            for k = 10^(-8)*q_star/(2*(pi*|contrast|)**2)
901           
902            q_star: the invariant value including extrapolated value if existing
903            dq_star: the invariant uncertainty
904            dV: the volume uncertainty
905       
906        The uncertainty will be set to -1 if it can't be computed.
907       
908        :param contrast: contrast value
909        :param extrapolation: string to apply optional extrapolation
910       
911        :return: V, dV = volume fraction, error on volume fraction
912        """
913        volume = self.get_volume_fraction(contrast, extrapolation)
914       
915        # Compute error
916        k =  1.e-8 * self._qstar /(2 * (math.pi* math.fabs(float(contrast)))**2)
917        # Check value inside the sqrt function
918        value = 1 - k * self._qstar
919        if (value) <= 0:
920            uncertainty = -1
921        # Compute uncertainty
922        uncertainty = math.fabs((0.5 * 4 * k * \
923                        self._qstar_err)/(2 * math.sqrt(1 - k * self._qstar)))
924       
925        return volume, uncertainty
926   
927    def get_surface_with_error(self, contrast, porod_const, extrapolation=None):
928        """
929        Compute uncertainty of the surface value as well as the surface value.
930        The uncertainty is given as follow: ::
931       
932            dS = porod_const *2*pi[( dV -2*V*dV)/q_star
933                 + dq_star(v-v**2)
934                 
935            q_star: the invariant value
936            dq_star: the invariant uncertainty
937            V: the volume fraction value
938            dV: the volume uncertainty
939       
940        :param contrast: contrast value
941        :param porod_const: porod constant value
942        :param extrapolation: string to apply optional extrapolation
943       
944        :return S, dS: the surface, with its uncertainty
945        """
946        # We get the volume fraction, with error
947        #   get_volume_fraction_with_error calls get_volume_fraction
948        #   get_volume_fraction calls get_qstar
949        #   which computes Qstar and dQstar
950        v, dv = self.get_volume_fraction_with_error(contrast, extrapolation)
951
952        s = self.get_surface(contrast=contrast, porod_const=porod_const, 
953                             extrapolation=extrapolation)
954        ds = porod_const * 2 * math.pi * (( dv - 2 * v * dv)/ self._qstar\
955                 + self._qstar_err * ( v - v**2))
956
957        return s, ds
Note: See TracBrowser for help on using the repository browser.