source: sasview/calculator/resolution_calculator.py @ 580ee7a

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 580ee7a was 580ee7a, checked in by Jae Cho <jhjcho@…>, 13 years ago

extended rescal to tof

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