source: sasview/src/sas/calculator/resolution_calculator.py @ 5a7d933

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 5a7d933 was 6bd3a8d1, checked in by Doucet, Mathieu <doucetm@…>, 9 years ago

Remove extra white spaces

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