source: sasview/src/sas/calculator/resolution_calculator.py @ 37bbd5f

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 37bbd5f was 79492222, checked in by krzywon, 9 years ago

Changed the file and folder names to remove all SANS references.

  • Property mode set to 100644
File size: 40.3 KB
Line 
1"""
2This object is a small tool to allow user to quickly
3determine the variance in q  from the
4instrumental parameters.
5"""
6from instrument import Sample
7from instrument import Detector
8from instrument import TOF as Neutron
9from instrument import Aperture
10# import math stuffs
11from math import pi
12from math import sqrt
13import math
14import numpy
15
16#Plank's constant in cgs unit
17_PLANK_H = 6.62606896E-27
18#Gravitational acc. in cgs unit
19_GRAVITY = 981.0
20
21
22class ResolutionCalculator(object):
23    """
24    compute resolution in 2D
25    """
26    def __init__(self):
27       
28        # wavelength
29        self.wave = Neutron()
30        # sample
31        self.sample = Sample()
32        # aperture
33        self.aperture = Aperture()
34        # detector
35        self.detector = Detector()
36        # 2d image of the resolution
37        self.image = []
38        self.image_lam = []
39        # resolutions
40        # lamda in r-direction
41        self.sigma_lamd = 0
42        # x-dir (no lamda)
43        self.sigma_1 = 0
44        #y-dir (no lamda)
45        self.sigma_2 = 0
46        # 1D total
47        self.sigma_1d = 0
48        self.gravity_phi = None
49        # q min and max
50        self.qx_min = -0.3
51        self.qx_max = 0.3
52        self.qy_min = -0.3
53        self.qy_max = 0.3
54        # q min and max of the detector
55        self.detector_qx_min = -0.3
56        self.detector_qx_max = 0.3
57        self.detector_qy_min = -0.3
58        self.detector_qy_max = 0.3
59        # possible max qrange
60        self.qxmin_limit = 0
61        self.qxmax_limit = 0
62        self.qymin_limit = 0
63        self.qymax_limit = 0
64
65        # plots
66        self.plot = None
67        # instrumental params defaults
68        self.mass = 0
69        self.intensity = 0
70        self.wavelength = 0
71        self.wavelength_spread = 0
72        self.source_aperture_size = []
73        self.source2sample_distance = []
74        self.sample2sample_distance = []
75        self.sample_aperture_size = []
76        self.sample2detector_distance = []
77        self.detector_pix_size = []
78        self.detector_size = []
79        # get all the values of the instrumental parameters
80        #self.intensity = self.get_intensity()
81        #self.wavelength = self.get_wavelength()
82        #self.wavelength_spread = self.get_wavelength_spread()
83        self.get_all_instrument_params()
84        # max q range for all lambdas
85        self.qxrange = []
86        self.qyrange = []
87       
88    def compute_and_plot(self, qx_value, qy_value, qx_min, qx_max,
89                          qy_min, qy_max, coord='cartesian'):
90        """
91        Compute the resolution
92        : qx_value: x component of q
93        : qy_value: y component of q
94        """
95        # make sure to update all the variables need.
96        # except lambda, dlambda, and intensity
97        self.get_all_instrument_params()
98        # wavelength etc.
99        lamda_list, dlamb_list = self.get_wave_list()
100        intens_list = []
101        sig1_list = []
102        sig2_list = []
103        sigr_list = []
104        sigma1d_list = []
105        num_lamda = len(lamda_list)
106        for num in range(num_lamda):
107            lam = lamda_list[num]
108            # wavelength spread
109            dlam = dlamb_list[num]
110            intens = self.setup_tof(lam, dlam)
111            intens_list.append(intens)
112            # cehck if tof
113            if num_lamda > 1:
114                tof = True
115            else:
116                tof = False
117            # compute 2d resolution
118            _, _, sigma_1, sigma_2, sigma_r, sigma1d = \
119                        self.compute(lam, dlam, qx_value, qy_value, coord, tof)
120            # make image
121            image = self.get_image(qx_value, qy_value, sigma_1, sigma_2,
122                            sigma_r, qx_min, qx_max, qy_min, qy_max,
123                            coord, False)
124           
125            # Non tof mode to be speed up
126            #if num_lamda < 2:
127            #    return self.plot_image(image)
128           
129            if qx_min > self.qx_min:
130                qx_min = self.qx_min
131            if qx_max < self.qx_max:
132                qx_max = self.qx_max
133            if qy_min > self.qy_min:
134                qy_min = self.qy_min
135            if qy_max < self.qy_max:
136                qy_max = self.qy_max
137               
138            # set max qranges
139            self.qxrange = [qx_min, qx_max]
140            self.qyrange = [qy_min, qy_max]
141            sig1_list.append(sigma_1)
142            sig2_list.append(sigma_2)
143            sigr_list.append(sigma_r)
144            sigma1d_list.append(sigma1d)
145        # redraw image in global 2d q-space.
146        self.image_lam = []
147        total_intensity = 0
148        sigma_1 = 0
149        sigma_r = 0
150        sigma_2 = 0
151        sigma1d = 0
152        for ind in range(num_lamda):
153            lam = lamda_list[ind]
154            dlam = dlamb_list[ind]
155            intens = self.setup_tof(lam, dlam)
156            out = self.get_image(qx_value, qy_value, sig1_list[ind],
157                                   sig2_list[ind], sigr_list[ind],
158                                   qx_min, qx_max, qy_min, qy_max, coord)
159            # this is the case of q being outside the detector
160            #if numpy.all(out==0.0):
161            #    continue
162            image = out
163            # set variance as sigmas
164            sigma_1 += sig1_list[ind] * sig1_list[ind] * self.intensity
165            sigma_r += sigr_list[ind] * sigr_list[ind] * self.intensity
166            sigma_2 += sig2_list[ind] * sig2_list[ind] * self.intensity
167            sigma1d += sigma1d_list[ind] * sigma1d_list[ind] * self.intensity
168            total_intensity += self.intensity
169       
170        if total_intensity != 0:
171            # average variance
172            image_out = image / total_intensity
173            sigma_1 = sigma_1 / total_intensity
174            sigma_r = sigma_r / total_intensity
175            sigma_2 = sigma_2 / total_intensity
176            sigma1d = sigma1d / total_intensity
177            # set sigmas
178            self.sigma_1 = sqrt(sigma_1)
179            self.sigma_lamd = sqrt(sigma_r)
180            self.sigma_2 = sqrt(sigma_2)
181            self.sigma_1d = sqrt(sigma1d)
182            # rescale
183            max_im_val = 1
184            if max_im_val > 0:
185                image_out /= max_im_val
186        else:
187            image_out = image * 0.0
188            # Don't calculate sigmas nor set self.sigmas!
189            sigma_1 = 0
190            sigma_r = 0
191            sigma_2 = 0
192            sigma1d = 0
193        if len(self.image) > 0:
194            self.image += image_out
195        else:
196            self.image = image_out
197       
198        # plot image
199        return self.plot_image(self.image)
200   
201    def setup_tof(self, wavelength, wavelength_spread):
202        """
203        Setup all parameters in instrument
204       
205        : param ind: index of lambda, etc
206        """
207
208        # set wave.wavelength
209        self.set_wavelength(wavelength)
210        self.set_wavelength_spread(wavelength_spread)
211        self.intensity = self.wave.get_intensity()
212       
213        if wavelength == 0:
214            msg = "Can't compute the resolution: the wavelength is zero..."
215            raise RuntimeError, msg
216        return self.intensity
217       
218    def compute(self, wavelength, wavelength_spread, qx_value, qy_value,
219                coord='cartesian', tof=False):
220        """
221        Compute the Q resoltuion in || and + direction of 2D
222        : qx_value: x component of q
223        : qy_value: y component of q
224        """
225        coord = 'cartesian'
226        lamb = wavelength
227        lamb_spread = wavelength_spread
228        # the shape of wavelength distribution
229
230        if tof:
231            # rectangular
232            tof_factor = 2
233        else:
234            # triangular
235            tof_factor = 1
236        # Find polar values
237        qr_value, phi = self._get_polar_value(qx_value, qy_value)
238        # vacuum wave transfer
239        knot = 2*pi/lamb
240        # scattering angle theta; always true for plane detector
241        # aligned vertically to the ko direction
242        if qr_value > knot:
243            theta = pi/2
244        else:
245            theta = math.asin(qr_value/knot)
246        # source aperture size
247        rone = self.source_aperture_size
248        # sample aperture size
249        rtwo = self.sample_aperture_size
250        # detector pixel size
251        rthree = self.detector_pix_size
252        # source to sample(aperture) distance
253        l_ssa = self.source2sample_distance[0]
254        # sample(aperture) to detector distance
255        l_sad = self.sample2detector_distance[0]
256        # sample (aperture) to sample distance
257        l_sas = self.sample2sample_distance[0]
258        # source to sample distance
259        l_one = l_ssa + l_sas
260        # sample to detector distance
261        l_two = l_sad - l_sas
262       
263        # Sample offset correction for l_one and Lp on variance calculation
264        l1_cor = (l_ssa * l_two) / (l_sas + l_two)
265        lp_cor = (l_ssa * l_two) / (l_one + l_two)
266        # the radial distance to the pixel from the center of the detector
267        radius = math.tan(theta) * l_two
268        #Lp = l_one*l_two/(l_one+l_two)
269        # default polar coordinate
270        comp1 = 'radial'
271        comp2 = 'phi'
272        # in the case of the cartesian coordinate
273        if coord == 'cartesian':
274            comp1 = 'x'
275            comp2 = 'y'
276
277        # sigma in the radial/x direction
278        # for source aperture
279        sigma_1  = self.get_variance(rone, l1_cor, phi, comp1)
280        # for sample apperture
281        sigma_1 += self.get_variance(rtwo, lp_cor, phi, comp1)
282        # for detector pix
283        sigma_1 += self.get_variance(rthree, l_two, phi, comp1)
284        # for gravity term for 1d
285        sigma_1grav1d = self.get_variance_gravity(l_ssa, l_sad, lamb,
286                            lamb_spread, phi, comp1, 'on') / tof_factor
287        # for wavelength spread
288        # reserve for 1d calculation
289        A_value = self._cal_A_value(lamb, l_ssa, l_sad)
290        sigma_wave_1, sigma_wave_1_1d = self.get_variance_wave(A_value,
291                                          radius, l_two, lamb_spread,
292                                          phi, 'radial', 'on')
293        sigma_wave_1 /= tof_factor
294        sigma_wave_1_1d /= tof_factor
295        # for 1d
296        variance_1d_1 = (sigma_1 + sigma_1grav1d) / 2 + sigma_wave_1_1d
297        # normalize
298        variance_1d_1 = knot * knot * variance_1d_1 / 12
299       
300        # for 2d
301        #sigma_1 += sigma_wave_1
302        # normalize
303        sigma_1 = knot * sqrt(sigma_1 / 12)
304        sigma_r = knot * sqrt(sigma_wave_1 / (tof_factor *12))
305        # sigma in the phi/y direction
306        # for source apperture
307        sigma_2  = self.get_variance(rone, l1_cor, phi, comp2)
308
309        # for sample apperture
310        sigma_2 += self.get_variance(rtwo, lp_cor, phi, comp2)
311
312        # for detector pix
313        sigma_2 += self.get_variance(rthree, l_two, phi, comp2)
314
315        # for gravity term for 1d
316        sigma_2grav1d = self.get_variance_gravity(l_ssa, l_sad, lamb,
317                                lamb_spread, phi, comp2, 'on') / tof_factor
318
319        # for wavelength spread
320        # reserve for 1d calculation
321        sigma_wave_2, sigma_wave_2_1d = self.get_variance_wave(A_value,
322                                          radius, l_two, lamb_spread,
323                                          phi, 'phi', 'on')
324        sigma_wave_2 /= tof_factor
325        sigma_wave_2_1d /= tof_factor
326        # for 1d
327        variance_1d_2 = (sigma_2 + sigma_2grav1d) / 2 + sigma_wave_2_1d
328        # normalize
329        variance_1d_2 = knot * knot * variance_1d_2 / 12
330       
331        # for 2d
332        #sigma_2 =  knot*sqrt(sigma_2/12)
333        #sigma_2 += sigma_wave_2
334        # normalize
335        sigma_2 = knot * sqrt(sigma_2 / 12)
336        sigma1d = sqrt(variance_1d_1 + variance_1d_2)
337        # set sigmas
338        self.sigma_1 = sigma_1
339        self.sigma_lamd = sigma_r
340        self.sigma_2 = sigma_2
341        self.sigma_1d = sigma1d
342        return qr_value, phi, sigma_1, sigma_2, sigma_r, sigma1d
343   
344    def _within_detector_range(self, qx_value, qy_value):
345        """
346        check if qvalues are within detector range
347        """
348        # detector range
349        detector_qx_min = self.detector_qx_min
350        detector_qx_max = self.detector_qx_max
351        detector_qy_min = self.detector_qy_min
352        detector_qy_max = self.detector_qy_max
353        if self.qxmin_limit > detector_qx_min:
354            self.qxmin_limit = detector_qx_min
355        if self.qxmax_limit < detector_qx_max:
356            self.qxmax_limit = detector_qx_max
357        if self.qymin_limit > detector_qy_min:
358            self.qymin_limit = detector_qy_min
359        if self.qymax_limit < detector_qy_max:
360            self.qymax_limit = detector_qy_max
361        if qx_value < detector_qx_min or qx_value > detector_qx_max:
362            return False
363        if qy_value < detector_qy_min or qy_value > detector_qy_max:
364            return False
365        return True
366   
367    def get_image(self, qx_value, qy_value, sigma_1, sigma_2, sigma_r,
368                  qx_min, qx_max, qy_min, qy_max,
369                  coord='cartesian', full_cal=True):
370        """
371        Get the resolution in polar coordinate ready to plot
372        : qx_value: qx_value value
373        : qy_value: qy_value value
374        : sigma_1: variance in r direction
375        : sigma_2: variance in phi direction
376        : coord: coordinate system of image, 'polar' or 'cartesian'
377        """
378        # Get  qx_max and qy_max...
379        self._get_detector_qxqy_pixels()
380       
381        qr_value, phi = self._get_polar_value(qx_value, qy_value)
382
383        # Check whether the q value is within the detector range
384        #msg = "Invalid input: Q value out of the detector range..."
385        if qx_min < self.qx_min:
386            self.qx_min = qx_min
387            #raise ValueError, msg
388        if qx_max > self.qx_max:
389            self.qx_max = qx_max
390            #raise ValueError, msg
391        if qy_min < self.qy_min:
392            self.qy_min = qy_min
393            #raise ValueError, msg
394        if qy_max > self.qy_max:
395            self.qy_max = qy_max
396            #raise ValueError, msg
397        if not full_cal:
398            return None
399 
400        # Make an empty graph in the detector scale
401        dx_size = (self.qx_max - self.qx_min) / (1000 - 1)
402        dy_size = (self.qy_max - self.qy_min) / (1000 - 1)
403        x_val = numpy.arange(self.qx_min, self.qx_max, dx_size)
404        y_val = numpy.arange(self.qy_max, self.qy_min, -dy_size)
405        q_1, q_2 = numpy.meshgrid(x_val, y_val)
406        #q_phi = numpy.arctan(q_1,q_2)
407        # check whether polar or cartesian
408        if coord == 'polar':
409            # Find polar values
410            qr_value, phi = self._get_polar_value(qx_value, qy_value)
411            q_1, q_2 = self._rotate_z(q_1, q_2, phi)
412            qc_1 = qr_value
413            qc_2 = 0.0
414            # Calculate the 2D Gaussian distribution image
415            image = self._gaussian2d_polar(q_1, q_2, qc_1, qc_2,
416                                 sigma_1, sigma_2, sigma_r)
417        else:
418            # catesian coordinate
419            # qx_center
420            qc_1 = qx_value
421            # qy_center
422            qc_2 = qy_value
423           
424            # Calculate the 2D Gaussian distribution image
425            image = self._gaussian2d(q_1, q_2, qc_1, qc_2,
426                                     sigma_1, sigma_2, sigma_r)
427        # out side of detector
428        if not self._within_detector_range(qx_value, qy_value):
429            image *= 0.0
430            self.intensity = 0.0
431            #return self.image
432
433        # Add it if there are more than one inputs.
434        if len(self.image_lam) > 0:
435            self.image_lam += image * self.intensity
436        else:
437            self.image_lam = image * self.intensity
438       
439        return self.image_lam
440   
441    def plot_image(self, image):
442        """
443        Plot image using pyplot
444        : image: 2d resolution image
445       
446        : return plt: pylab object
447        """
448        import matplotlib.pyplot as plt
449
450        self.plot = plt
451        plt.xlabel('$\\rm{Q}_{x} [A^{-1}]$')
452        plt.ylabel('$\\rm{Q}_{y} [A^{-1}]$')
453        # Max value of the image
454        # max = numpy.max(image)
455        qx_min, qx_max, qy_min, qy_max = self.get_detector_qrange()
456
457        # Image
458        im = plt.imshow(image,
459                extent=[qx_min, qx_max, qy_min, qy_max])
460
461        # bilinear interpolation to make it smoother
462        im.set_interpolation('bilinear')
463
464        return plt
465   
466    def reset_image(self):
467        """
468        Reset image to default (=[])
469        """
470        self.image = []
471       
472    def get_variance(self, size=[], distance=0, phi=0, comp='radial'):
473        """
474        Get the variance when the slit/pinhole size is given
475        : size: list that can be one(diameter for circular) or two components(lengths for rectangular)
476        : distance: [z, x] where z along the incident beam, x // qx_value
477        : comp: direction of the sigma; can be 'phi', 'y', 'x', and 'radial'
478       
479        : return variance: sigma^2
480        """
481        # check the length of size (list)
482        len_size = len(size)
483       
484        # define sigma component direction
485        if comp == 'radial':
486            phi_x = math.cos(phi)
487            phi_y = math.sin(phi)
488        elif comp == 'phi':
489            phi_x = math.sin(phi)
490            phi_y = math.cos(phi)
491        elif comp == 'x':
492            phi_x = 1
493            phi_y = 0
494        elif comp == 'y':
495            phi_x = 0
496            phi_y = 1
497        else:
498            phi_x = 0
499            phi_y = 0
500        # calculate each component
501        # for pinhole w/ radius = size[0]/2
502        if len_size == 1:
503            x_comp = (0.5 * size[0]) * sqrt(3)
504            y_comp = 0
505        # for rectangular slit
506        elif len_size == 2:
507            x_comp = size[0] * phi_x
508            y_comp = size[1] * phi_y
509        # otherwise
510        else:
511            raise ValueError, " Improper input..."
512        # get them squared
513        sigma  = x_comp * x_comp
514        sigma += y_comp * y_comp
515        # normalize by distance
516        sigma /= (distance * distance)
517
518        return sigma
519
520    def get_variance_wave(self, A_value, radius, distance, spread, phi,
521                          comp='radial', switch='on'):
522        """
523        Get the variance when the wavelength spread is given
524       
525        : radius: the radial distance from the beam center to the pix of q
526        : distance: sample to detector distance
527        : spread: wavelength spread (ratio)
528        : comp: direction of the sigma; can be 'phi', 'y', 'x', and 'radial'
529       
530        : return variance: sigma^2 for 2d, sigma^2 for 1d [tuple]
531        """
532        if switch.lower() == 'off':
533            return 0, 0
534        # check the singular point
535        if distance == 0 or comp == 'phi':
536            return 0, 0
537        else:
538            # calculate sigma^2 for 1d
539            sigma1d = 2 * math.pow(radius/distance*spread, 2)
540            if comp == 'x':
541                sigma1d *= (math.cos(phi)*math.cos(phi))
542            elif comp == 'y':
543                sigma1d *= (math.sin(phi)*math.sin(phi))
544            else:
545                sigma1d *= 1
546            # sigma^2 for 2d
547            # shift the coordinate due to the gravitational shift
548            rad_x = radius * math.cos(phi)
549            rad_y = A_value - radius * math.sin(phi)
550            radius = math.sqrt(rad_x * rad_x + rad_y * rad_y)
551            # new phi
552            phi = math.atan2(-rad_y, rad_x)
553            self.gravity_phi = phi
554            # calculate sigma^2
555            sigma = 2 * math.pow(radius/distance*spread, 2)
556            if comp == 'x':
557                sigma *= (math.cos(phi)*math.cos(phi))
558            elif comp == 'y':
559                sigma *= (math.sin(phi)*math.sin(phi))
560            else:
561                sigma *= 1
562               
563            return sigma, sigma1d
564
565    def get_variance_gravity(self, s_distance, d_distance, wavelength, spread,
566                             phi, comp='radial', switch='on'):
567        """
568        Get the variance from gravity when the wavelength spread is given
569       
570        : s_distance: source to sample distance
571        : d_distance: sample to detector distance
572        : wavelength: wavelength
573        : spread: wavelength spread (ratio)
574        : comp: direction of the sigma; can be 'phi', 'y', 'x', and 'radial'
575       
576        : return variance: sigma^2
577        """
578        if switch.lower() == 'off':
579            return 0
580        if self.mass == 0.0:
581            return 0
582        # check the singular point
583        if d_distance == 0 or comp == 'x':
584            return 0
585        else:
586            a_value = self._cal_A_value(None, s_distance, d_distance)
587            # calculate sigma^2
588            sigma = math.pow(a_value / d_distance, 2)
589            sigma *= math.pow(wavelength, 4)
590            sigma *= math.pow(spread, 2)
591            sigma *= 8
592           
593            # only for the polar coordinate
594            #if comp == 'radial':
595            #    sigma *= (math.sin(phi) * math.sin(phi))
596            #elif comp == 'phi':
597            #    sigma *= (math.cos(phi) * math.cos(phi))
598           
599            return sigma
600   
601    def _cal_A_value(self, lamda, s_distance, d_distance):
602        """
603        Calculate A value for gravity
604       
605        : s_distance: source to sample distance
606        : d_distance: sample to detector distance
607        """
608        # neutron mass in cgs unit
609        self.mass = self.get_neutron_mass()
610        # plank constant in cgs unit
611        h_constant = _PLANK_H
612        # gravity in cgs unit
613        gravy = _GRAVITY
614        # m/h
615        m_over_h = self.mass / h_constant
616        # A value
617        a_value = d_distance * (s_distance + d_distance)
618        a_value *= math.pow(m_over_h / 2, 2)
619        a_value *= gravy
620        # unit correction (1/cm to 1/A) for A and d_distance below
621        a_value *= 1.0E-16
622        # if lamda is give (broad meanning of A)  return 2* lamda^2 * A
623        if lamda != None:
624            a_value *= (4 * lamda * lamda)
625        return a_value
626   
627    def get_intensity(self):
628        """
629        Get intensity
630        """
631        return self.wave.intensity
632
633    def get_wavelength(self):
634        """
635        Get wavelength
636        """
637        return self.wave.wavelength
638   
639    #TODO: why was this method duplicated?
640    #def get_spectrum(self):
641    #    """
642    #    Get spectrum
643    #    """
644    #    return self.wave.spectrum
645   
646    def get_default_spectrum(self):
647        """
648        Get default_spectrum
649        """
650        return self.wave.get_default_spectrum()
651   
652    def get_spectrum(self):
653        """
654        Get _spectrum
655        """
656        return self.wave.get_spectrum()
657         
658    def get_wavelength_spread(self):
659        """
660        Get wavelength spread
661        """
662        return self.wave.wavelength_spread
663   
664    def get_neutron_mass(self):
665        """
666        Get Neutron mass
667        """
668        return self.wave.mass
669   
670    def get_source_aperture_size(self):
671        """
672        Get source aperture size
673        """
674        return self.aperture.source_size
675   
676    def get_sample_aperture_size(self):
677        """
678        Get sample aperture size
679        """
680        return self.aperture.sample_size
681   
682    def get_detector_pix_size(self):
683        """
684        Get detector pixel size
685        """
686        return self.detector.pix_size
687       
688    def get_detector_size(self):
689        """
690        Get detector size
691        """
692        return self.detector.size
693     
694    def get_source2sample_distance(self):
695        """
696        Get detector source2sample_distance
697        """
698        return self.aperture.sample_distance
699   
700    def get_sample2sample_distance(self):
701        """
702        Get detector sampleslitsample_distance
703        """
704        return self.sample.distance
705   
706    def get_sample2detector_distance(self):
707        """
708        Get detector sample2detector_distance
709        """
710        return self.detector.distance
711   
712    def set_intensity(self, intensity):
713        """
714        Set intensity
715        """
716        self.wave.set_intensity(intensity)
717       
718    def set_wave(self, wavelength):
719        """
720        Set wavelength list or wavelength
721        """
722        if wavelength.__class__.__name__ == 'list':
723            self.wave.set_wave_list(wavelength)
724        elif wavelength.__class__.__name__ == 'float':
725            self.wave.set_wave_list([wavelength])
726            #self.set_wavelength(wavelength)
727        else:
728            raise
729   
730    def set_wave_spread(self, wavelength_spread):
731        """
732        Set wavelength spread  or wavelength spread
733        """
734        if wavelength_spread.__class__.__name__ == 'list':
735            self.wave.set_wave_spread_list(wavelength_spread)
736        elif wavelength_spread.__class__.__name__ == 'float':
737            self.wave.set_wave_spread_list([wavelength_spread])
738            #self.set_wavelength_spread(wavelength_spread)
739        else:
740            raise
741       
742    def set_wavelength(self, wavelength):
743        """
744        Set wavelength
745        """
746        self.wavelength = wavelength
747        self.wave.set_wavelength(wavelength)
748       
749    def set_spectrum(self, spectrum):
750        """
751        Set spectrum
752        """
753        self.spectrum = spectrum
754        self.wave.set_spectrum(spectrum)
755         
756    def set_wavelength_spread(self, wavelength_spread):
757        """
758        Set wavelength spread
759        """
760        self.wavelength_spread = wavelength_spread
761        self.wave.set_wavelength_spread(wavelength_spread)
762       
763    def set_wave_list(self, wavelength_list, wavelengthspread_list):
764        """
765        Set wavelength and its spread list
766        """
767        self.wave.set_wave_list(wavelength_list)
768        self.wave.set_wave_spread_list(wavelengthspread_list)
769   
770    def get_wave_list(self):
771        """
772        Set wavelength spread
773        """
774        return self.wave.get_wave_list()
775   
776    def get_intensity_list(self):
777        """
778        Set wavelength spread
779        """
780        return self.wave.get_intensity_list()
781           
782    def set_source_aperture_size(self, size):
783        """
784        Set source aperture size
785       
786        : param size: [dia_value] or [x_value, y_value]
787        """
788        if len(size) < 1 or len(size) > 2:
789            raise RuntimeError, "The length of the size must be one or two."
790        self.aperture.set_source_size(size)
791       
792    def set_neutron_mass(self, mass):
793        """
794        Set Neutron mass
795        """
796        self.wave.set_mass(mass)
797        self.mass = mass
798       
799    def set_sample_aperture_size(self, size):
800        """
801        Set sample aperture size
802       
803        : param size: [dia_value] or [xheight_value, yheight_value]
804        """
805        if len(size) < 1 or len(size) > 2:
806            raise RuntimeError, "The length of the size must be one or two."
807        self.aperture.set_sample_size(size)
808   
809    def set_detector_pix_size(self, size):
810        """
811        Set detector pixel size
812        """
813        self.detector.set_pix_size(size)
814       
815    def set_detector_size(self, size):
816        """
817        Set detector size in number of pixels
818        : param size: [pixel_nums] or [x_pix_num, yx_pix_num]
819        """
820        self.detector.set_size(size)
821       
822    def set_source2sample_distance(self, distance):
823        """
824        Set detector source2sample_distance
825       
826        : param distance: [distance, x_offset]
827        """
828        if len(distance) < 1 or len(distance) > 2:
829            raise RuntimeError, "The length of the size must be one or two."
830        self.aperture.set_sample_distance(distance)
831
832    def set_sample2sample_distance(self, distance):
833        """
834        Set detector sample_slit2sample_distance
835       
836        : param distance: [distance, x_offset]
837        """
838        if len(distance) < 1 or len(distance) > 2:
839            raise RuntimeError, "The length of the size must be one or two."
840        self.sample.set_distance(distance)
841   
842    def set_sample2detector_distance(self, distance):
843        """
844        Set detector sample2detector_distance
845       
846        : param distance: [distance, x_offset]
847        """
848        if len(distance) < 1 or len(distance) > 2:
849            raise RuntimeError, "The length of the size must be one or two."
850        self.detector.set_distance(distance)
851       
852    def get_all_instrument_params(self):
853        """
854        Get all instrumental parameters
855        """
856        #self.intensity = self.get_intensity()
857        #self.wavelength = self.get_wavelength()
858        #self.wavelength_spread = self.get_wavelength_spread()
859        self.mass = self.get_neutron_mass()
860        self.spectrum = self.get_spectrum()
861        self.source_aperture_size = self.get_source_aperture_size()
862        self.sample_aperture_size = self.get_sample_aperture_size()
863        self.detector_pix_size = self.get_detector_pix_size()
864        self.detector_size = self.get_detector_size()
865        self.source2sample_distance = self.get_source2sample_distance()
866        self.sample2sample_distance = self.get_sample2sample_distance()
867        self.sample2detector_distance = self.get_sample2detector_distance()
868   
869    def get_detector_qrange(self):
870        """
871        get max detector q ranges
872       
873        : return: qx_min, qx_max, qy_min, qy_max tuple
874        """
875        if len(self.qxrange) != 2 or len(self.qyrange) != 2:
876            return None
877        qx_min = self.qxrange[0]
878        qx_max = self.qxrange[1]
879        qy_min = self.qyrange[0]
880        qy_max = self.qyrange[1]
881       
882        return qx_min, qx_max, qy_min, qy_max
883   
884    def _rotate_z(self, x_value, y_value, theta=0.0):
885        """
886        Rotate x-y cordinate around z-axis by theta
887        : x_value: numpy array of x values
888        : y_value: numpy array of y values
889        : theta: angle to rotate by in rad
890       
891        :return: x_prime, y-prime
892        """       
893        # rotate by theta
894        x_prime = x_value * math.cos(theta) + y_value * math.sin(theta)
895        y_prime = -x_value * math.sin(theta) + y_value * math.cos(theta)
896   
897        return x_prime, y_prime
898   
899    def _gaussian2d(self, x_val, y_val, x0_val, y0_val,
900                    sigma_x, sigma_y, sigma_r):
901        """
902        Calculate 2D Gaussian distribution
903        : x_val: x value
904        : y_val: y value
905        : x0_val: mean value in x-axis
906        : y0_val: mean value in y-axis
907        : sigma_x: variance in x-direction
908        : sigma_y: variance in y-direction
909       
910        : return: gaussian (value)
911        """
912        # phi values at each points (not at the center)
913        x_value = x_val - x0_val
914        y_value = y_val - y0_val
915        phi_i = numpy.arctan2(y_val, x_val)
916       
917        # phi correction due to the gravity shift (in phi)
918        phi_0 = math.atan2(y0_val, x0_val)
919        phi_i = phi_i - phi_0 + self.gravity_phi
920
921        sin_phi = numpy.sin(self.gravity_phi)
922        cos_phi = numpy.cos(self.gravity_phi)
923       
924        x_p = x_value * cos_phi + y_value * sin_phi
925        y_p = -x_value * sin_phi + y_value * cos_phi
926       
927        new_sig_x = sqrt(sigma_r * sigma_r / (sigma_x * sigma_x) + 1)
928        new_sig_y = sqrt(sigma_r * sigma_r / (sigma_y * sigma_y) + 1)
929        new_x = x_p * cos_phi / new_sig_x - y_p * sin_phi
930        new_x /= sigma_x
931        new_y = x_p * sin_phi / new_sig_y + y_p * cos_phi
932        new_y /= sigma_y
933
934        nu_value = -0.5 * (new_x * new_x + new_y * new_y)
935
936        gaussian = numpy.exp(nu_value)
937        # normalizing factor correction
938        gaussian /= gaussian.sum()
939
940        return gaussian
941
942    def _gaussian2d_polar(self, x_val, y_val, x0_val, y0_val,
943                        sigma_x, sigma_y, sigma_r):
944        """
945        Calculate 2D Gaussian distribution for polar coodinate
946        : x_val: x value
947        : y_val: y value
948        : x0_val: mean value in x-axis
949        : y0_val: mean value in y-axis
950        : sigma_x: variance in r-direction
951        : sigma_y: variance in phi-direction
952        : sigma_r: wavelength variance in r-direction
953       
954        : return: gaussian (value)
955        """
956        sigma_x = sqrt(sigma_x * sigma_x + sigma_r * sigma_r)
957        # call gaussian1d
958        gaussian  = self._gaussian1d(x_val, x0_val, sigma_x)
959        gaussian *= self._gaussian1d(y_val, y0_val, sigma_y)
960 
961        # normalizing factor correction
962        if sigma_x != 0 and sigma_y != 0:
963            gaussian *= sqrt(2 * pi)
964        return gaussian
965   
966    def _gaussian1d(self, value, mean, sigma):
967        """
968        Calculate 1D Gaussian distribution
969        : value: value
970        : mean: mean value
971        : sigma: variance
972       
973        : return: gaussian (value)
974        """
975        # default
976        gaussian = 1.0
977        if sigma != 0:
978            # get exponent
979            nu_value = (value - mean) / sigma
980            nu_value *= nu_value
981            nu_value *= -0.5
982            gaussian *= numpy.exp(nu_value)
983            gaussian /= sigma
984            # normalize
985            gaussian /= sqrt(2 * pi)
986           
987        return gaussian
988   
989    def _atan_phi(self, qy_value, qx_value):
990        """
991        Find the angle phi of q on the detector plane for qx_value, qy_value given
992        : qx_value: x component of q
993        : qy_value: y component of q
994       
995        : return phi: the azimuthal angle of q on x-y plane
996        """
997        phi = math.atan2(qy_value, qx_value)
998        return phi
999        # default
1000        phi = 0
1001        # ToDo: This is misterious - sign???
1002        #qy_value = -qy_value
1003        # Take care of the singular point
1004        if qx_value == 0:
1005            if qy_value > 0:
1006                phi = pi / 2
1007            elif qy_value < 0:
1008                phi = -pi / 2
1009            else:
1010                phi = 0
1011        else:
1012            # the angle
1013            phi = math.atan2(qy_value, qx_value)
1014
1015        return phi
1016
1017    def _get_detector_qxqy_pixels(self):
1018        """
1019        Get the pixel positions of the detector in the qx_value-qy_value space
1020        """
1021       
1022        # update all param values
1023        self.get_all_instrument_params()
1024       
1025        # wavelength
1026        wavelength = self.wave.wavelength
1027        # Gavity correction
1028        delta_y = self._get_beamcenter_drop()  # in cm
1029       
1030        # detector_pix size
1031        detector_pix_size = self.detector_pix_size
1032        # Square or circular pixel
1033        if len(detector_pix_size) == 1:
1034            pix_x_size = detector_pix_size[0]
1035            pix_y_size = detector_pix_size[0]
1036        # rectangular pixel pixel
1037        elif len(detector_pix_size) == 2:
1038            pix_x_size = detector_pix_size[0]
1039            pix_y_size = detector_pix_size[1]
1040        else:
1041            raise ValueError, " Input value format error..."
1042        # Sample to detector distance = sample slit to detector
1043        # minus sample offset
1044        sample2detector_distance = self.sample2detector_distance[0] - \
1045                                    self.sample2sample_distance[0]
1046        # detector offset in x-direction
1047        detector_offset = 0
1048        try:
1049            detector_offset = self.sample2detector_distance[1]
1050        except:
1051            pass
1052       
1053        # detector size in [no of pix_x,no of pix_y]
1054        detector_pix_nums_x = self.detector_size[0]
1055       
1056        # get pix_y if it exists, otherwse take it from [0]
1057        try:
1058            detector_pix_nums_y = self.detector_size[1]
1059        except:
1060            detector_pix_nums_y = self.detector_size[0]
1061       
1062        # detector offset in pix number
1063        offset_x = detector_offset / pix_x_size
1064        offset_y = delta_y / pix_y_size
1065       
1066        # beam center position in pix number (start from 0)
1067        center_x, center_y = self._get_beamcenter_position(detector_pix_nums_x,
1068                                    detector_pix_nums_y, offset_x, offset_y)
1069        # distance [cm] from the beam center on detector plane
1070        detector_ind_x = numpy.arange(detector_pix_nums_x)
1071        detector_ind_y = numpy.arange(detector_pix_nums_y)
1072
1073        # shif 0.5 pixel so that pix position is at the center of the pixel
1074        detector_ind_x = detector_ind_x + 0.5
1075        detector_ind_y = detector_ind_y + 0.5
1076
1077        # the relative postion from the beam center
1078        detector_ind_x = detector_ind_x - center_x
1079        detector_ind_y = detector_ind_y - center_y
1080       
1081        # unit correction in cm
1082        detector_ind_x = detector_ind_x * pix_x_size
1083        detector_ind_y = detector_ind_y * pix_y_size
1084       
1085        qx_value = numpy.zeros(len(detector_ind_x))
1086        qy_value = numpy.zeros(len(detector_ind_y))
1087        i = 0
1088
1089        for indx in detector_ind_x:
1090            qx_value[i] = self._get_qx(indx, sample2detector_distance, wavelength)
1091            i += 1
1092        i = 0
1093        for indy in detector_ind_y:
1094            qy_value[i] = self._get_qx(indy, sample2detector_distance, wavelength)
1095            i += 1
1096           
1097        # qx_value and qy_value values in array
1098        qx_value = qx_value.repeat(detector_pix_nums_y)
1099        qx_value = qx_value.reshape(detector_pix_nums_x, detector_pix_nums_y)
1100        qy_value = qy_value.repeat(detector_pix_nums_x)
1101        qy_value = qy_value.reshape(detector_pix_nums_y, detector_pix_nums_x)
1102        qy_value = qy_value.transpose()
1103
1104        # p min and max values among the center of pixels
1105        self.qx_min = numpy.min(qx_value)
1106        self.qx_max = numpy.max(qx_value)
1107        self.qy_min = numpy.min(qy_value)
1108        self.qy_max = numpy.max(qy_value)
1109               
1110        # Appr. min and max values of the detector display limits
1111        # i.e., edges of the last pixels.
1112        self.qy_min += self._get_qx(-0.5 * pix_y_size,
1113                                sample2detector_distance, wavelength)
1114        self.qy_max += self._get_qx(0.5 * pix_y_size,
1115                                sample2detector_distance, wavelength)
1116        #if self.qx_min == self.qx_max:
1117        self.qx_min += self._get_qx(-0.5 * pix_x_size,
1118                                sample2detector_distance, wavelength)
1119        self.qx_max += self._get_qx(0.5 * pix_x_size,
1120                                    sample2detector_distance, wavelength)
1121       
1122        # min and max values of detecter
1123        self.detector_qx_min = self.qx_min
1124        self.detector_qx_max = self.qx_max
1125        self.detector_qy_min = self.qy_min
1126        self.detector_qy_max = self.qy_max
1127       
1128        # try to set it as a Data2D otherwise pass (not required for now)
1129        try:
1130            from sas.dataloader.data_info import Data2D
1131            output = Data2D()
1132            inten = numpy.zeros_like(qx_value)
1133            output.data    = inten
1134            output.qx_data = qx_value
1135            output.qy_data = qy_value
1136        except:
1137            pass
1138       
1139        return output
1140       
1141    def _get_qx(self, dx_size, det_dist, wavelength):
1142        """
1143        :param dx_size: x-distance from beam center [cm]
1144        :param det_dist: sample to detector distance [cm]
1145       
1146        :return: q-value at the given position
1147        """
1148        # Distance from beam center in the plane of detector
1149        plane_dist = dx_size
1150        # full scattering angle on the x-axis
1151        theta = numpy.arctan(plane_dist / det_dist)
1152        qx_value = (2.0 * pi / wavelength) * numpy.sin(theta)
1153        return qx_value
1154   
1155    def _get_polar_value(self, qx_value, qy_value):
1156        """
1157        Find qr_value and phi from qx_value and qy_value values
1158       
1159        : return qr_value, phi
1160        """
1161        # find |q| on detector plane
1162        qr_value = sqrt(qx_value*qx_value + qy_value*qy_value)
1163        # find angle phi
1164        phi = self._atan_phi(qy_value, qx_value)
1165       
1166        return qr_value, phi
1167   
1168    def _get_beamcenter_position(self, num_x, num_y, offset_x, offset_y):
1169        """
1170        :param num_x: number of pixel in x-direction
1171        :param num_y: number of pixel in y-direction
1172        :param offset: detector offset in x-direction in pix number
1173       
1174        :return: pix number; pos_x, pos_y in pix index
1175        """
1176        # beam center position
1177        pos_x = num_x / 2
1178        pos_y = num_y / 2
1179
1180        # correction for offset
1181        pos_x += offset_x
1182        # correction for gravity that is always negative
1183        pos_y -= offset_y
1184
1185        return pos_x, pos_y
1186
1187    def _get_beamcenter_drop(self):
1188        """
1189        Get the beam center drop (delta y) in y diection due to gravity
1190       
1191        :return delta y: the beam center drop in cm
1192        """
1193        # Check if mass == 0 (X-ray).
1194        if self.mass == 0:
1195            return 0
1196        # Covert unit from A to cm
1197        unit_cm = 1e-08
1198        # Velocity of neutron in horizontal direction (~ actual velocity)
1199        velocity = _PLANK_H / (self.mass * self.wave.wavelength * unit_cm)
1200        # Compute delta y
1201        delta_y = 0.5
1202        delta_y *= _GRAVITY
1203        sampletodetector = self.sample2detector_distance[0] - \
1204                                    self.sample2sample_distance[0]
1205        delta_y *= sampletodetector
1206        delta_y *= (self.source2sample_distance[0] + self.sample2detector_distance[0])
1207        delta_y /= (velocity * velocity)
1208
1209        return delta_y
Note: See TracBrowser for help on using the repository browser.