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