Coverage for spectractor/extractor/dispersers.py: 12%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from scipy import interpolate
2from scipy import ndimage
3import matplotlib.pyplot as plt
4import numpy as np
5import os
7from spectractor import parameters
8from spectractor.tools import fit_poly2d
9from spectractor.logbook import set_logger
12def build_hologram(order0_position, order1_position, theta_tilt=0, lambda_plot=256000):
13 """Produce the interference pattern printed on a hologram, with two sources
14 located at order0_position and order1_position, with an angle theta_tilt with respect
15 to the X axis. For plotting reasons, the wavelength can be set very large with
16 the lambda_plot parameter.
18 Parameters
19 ----------
20 order0_position: array
21 List [x0,y0] of the pixel coordinates of the order 0 source position (source A).
22 order1_position: array
23 List [x1,y1] of the pixel coordinates of the order 1 source position (source B).
24 theta_tilt: float
25 Angle (in degree) to tilt the interference pattern with respect to X axis (default: 0)
26 lambda_plot: float
27 Wavelength to produce the interference pattern (default: 256000)
29 Returns
30 -------
31 hologram: 2D-array,
32 The hologram figure, of shape (CCD_IMSIZE,CCD_IMSIZE)
34 Examples
35 --------
36 >>> hologram = build_hologram([500,500],[800,500],theta_tilt=-1,lambda_plot=200000)
37 >>> assert np.all(np.isclose(hologram[:5,:5],np.zeros((5,5))))
38 """
39 # wavelength in nm, hologram produced at 639nm
40 # spherical wave centered in 0,0,0
41 U = lambda x, y, z: np.exp(2j * np.pi * np.sqrt(x * x + y * y + z * z) * 1e6 /
42 lambda_plot) / np.sqrt(x * x + y * y + z * z)
43 # superposition of two spherical sources centered in order 0 and order 1 positions
44 xA = [order0_position[0] * parameters.CCD_PIXEL2MM, order0_position[1] * parameters.CCD_PIXEL2MM]
45 xB = [order1_position[0] * parameters.CCD_PIXEL2MM, order1_position[1] * parameters.CCD_PIXEL2MM]
46 A = lambda x, y: U(x - xA[0], y - xA[1], -parameters.DISTANCE2CCD) + U(x - xB[0], y - xB[1],
47 -parameters.DISTANCE2CCD)
48 intensity = lambda x, y: np.abs(A(x, y)) ** 2
49 xholo = np.linspace(0, parameters.CCD_IMSIZE * parameters.CCD_PIXEL2MM, parameters.CCD_IMSIZE)
50 yholo = np.linspace(0, parameters.CCD_IMSIZE * parameters.CCD_PIXEL2MM, parameters.CCD_IMSIZE)
51 xxholo, yyholo = np.meshgrid(xholo, yholo)
52 holo = intensity(xxholo, yyholo)
53 rotated_holo = ndimage.interpolation.rotate(holo, theta_tilt)
54 return rotated_holo
57def build_ronchi(x_center, theta_tilt=0, grooves=400):
58 """Produce the Ronchi pattern (alternance of recatngular stripes of transparancy 0 and 1),
59 centered at x_center, with an angle theta_tilt with respect
60 to the X axis. Grooves parameter set the number of grooves per mm.
62 Parameters
63 ----------
64 x_center: float
65 Center pixel to start the figure with a black stripe.
66 theta_tilt: float
67 Angle (in degree) to tilt the interference pattern with respect to X axis (default: 0)
68 grooves: float
69 Number of grooves per mm (default: 400)
71 Returns
72 -------
73 hologram: 2D-array,
74 The hologram figure, of shape (CCD_IMSIZE,CCD_IMSIZE)
76 Examples
77 --------
78 >>> ronchi = build_ronchi(0,theta_tilt=0,grooves=400)
79 >>> print(ronchi[:5,:5])
80 [[0 1 0 0 1]
81 [0 1 0 0 1]
82 [0 1 0 0 1]
83 [0 1 0 0 1]
84 [0 1 0 0 1]]
86 """
87 intensity = lambda x, y: 2 * np.sin(2 * np.pi *
88 (x - x_center * parameters.CCD_PIXEL2MM) * 0.5 * grooves) ** 2
89 xronchi = np.linspace(0, parameters.CCD_IMSIZE * parameters.CCD_PIXEL2MM, parameters.CCD_IMSIZE)
90 yronchi = np.linspace(0, parameters.CCD_IMSIZE * parameters.CCD_PIXEL2MM, parameters.CCD_IMSIZE)
91 xxronchi, yyronchi = np.meshgrid(xronchi, yronchi)
92 ronchi = (intensity(xxronchi, yyronchi)).astype(int)
93 rotated_ronchi = ndimage.interpolation.rotate(ronchi, theta_tilt)
94 return rotated_ronchi
97def get_theta0(x0):
98 """ Return the incident angle on the disperser in radians, with respect to the disperser normal and the X axis.
100 Parameters
101 ----------
102 x0: float, tuple, list
103 The order 0 position in the full non-rotated image.
105 Returns
106 -------
107 theta0: float
108 The incident angle in radians
110 Examples
111 --------
112 >>> get_theta0((parameters.CCD_IMSIZE/2,parameters.CCD_IMSIZE/2))
113 0.0
114 >>> get_theta0(parameters.CCD_IMSIZE/2)
115 0.0
116 """
117 if isinstance(x0, (list, tuple, np.ndarray)):
118 return (x0[0] - parameters.CCD_IMSIZE / 2) * parameters.CCD_PIXEL2ARCSEC * parameters.CCD_ARCSEC2RADIANS
119 else:
120 return (x0 - parameters.CCD_IMSIZE / 2) * parameters.CCD_PIXEL2ARCSEC * parameters.CCD_ARCSEC2RADIANS
123def get_delta_pix_ortho(deltaX, x0, D=parameters.DISTANCE2CCD):
124 """ Subtract from the distance deltaX in pixels between a pixel x the order 0 the distance between
125 the projected incident point on the disperser and the order 0. In other words, the projection of the incident
126 angle theta0 from the disperser to the CCD is removed. The distance to the CCD D is in mm.
128 Parameters
129 ----------
130 deltaX: float
131 The distance in pixels between the order 0 and a spectrum pixel in the rotated image.
132 x0: list, [x0,y0]
133 The order 0 position in the full non-rotated image.
134 D: float
135 The distance between the CCD and the disperser in mm.
137 Returns
138 -------
139 distance: float
140 The projected distance in pixels
142 Examples
143 --------
144 >>> delta, D = 500, 55
145 >>> get_delta_pix_ortho(delta, [parameters.CCD_IMSIZE/2, parameters.CCD_IMSIZE/2], D=D)
146 500.0
147 >>> get_delta_pix_ortho(delta, [500,500], D=D)
148 497.6654556732099
149 """
150 theta0 = get_theta0(x0)
151 deltaX0 = np.tan(theta0) * D / parameters.CCD_PIXEL2MM
152 return deltaX + deltaX0
155def get_refraction_angle(deltaX, x0, D=parameters.DISTANCE2CCD):
156 """ Return the refraction angle with respect to the disperser normal, using geometrical consideration.
158 Parameters
159 ----------
160 deltaX: float
161 The distance in pixels between the order 0 and a spectrum pixel in the rotated image.
162 x0: list, [x0,y0]
163 The order 0 position in the full non-rotated image.
164 D: float
165 The distance between the CCD and the disperser in mm.
167 Returns
168 -------
169 theta: float
170 The refraction angle in radians.
172 Examples
173 --------
174 >>> delta, D = 500, 55
175 >>> theta = get_refraction_angle(delta, [parameters.CCD_IMSIZE/2, parameters.CCD_IMSIZE/2], D=D)
176 >>> assert np.isclose(theta, np.arctan2(delta*parameters.CCD_PIXEL2MM, D))
177 >>> theta = get_refraction_angle(delta, [500,500], D=D)
178 >>> print('{:.2f}'.format(theta))
179 0.21
180 """
181 delta = get_delta_pix_ortho(deltaX, x0, D=D)
182 theta = np.arctan2(delta * parameters.CCD_PIXEL2MM, D)
183 return theta
186def get_N(deltaX, x0, D=parameters.DISTANCE2CCD, wavelength=656, order=1):
187 """ Return the grooves per mm number given the spectrum pixel x position with
188 its wavelength in mm, the distance to the CCD in mm and the order number. It
189 uses the disperser formula.
191 Parameters
192 ----------
193 deltaX: float
194 The distance in pixels between the order 0 and a spectrum pixel in the rotated image.
195 x0: list, [x0,y0]
196 The order 0 position in the full non-rotated image.
197 D: float
198 The distance between the CCD and the disperser in mm.
199 wavelength: float
200 The wavelength at pixel x in nm (default: 656).
201 order: int
202 The order of the spectrum (default: 1).
204 Returns
205 -------
206 theta: float
207 The number of grooves per mm.
209 Examples
210 --------
211 >>> delta, D, w = 500, 55, 600
212 >>> N = get_N(delta, [500,500], D=D, wavelength=w, order=1)
213 >>> print('{:.0f}'.format(N))
214 355
215 """
216 theta = get_refraction_angle(deltaX, x0, D=D)
217 theta0 = get_theta0(x0)
218 N = (np.sin(theta) - np.sin(theta0)) / (order * wavelength * 1e-6)
219 return N
222def neutral_lines(x_center, y_center, theta_tilt):
223 """Return the nuetrla lines of an hologram."""
224 xs = np.linspace(0, parameters.CCD_IMSIZE, 20)
225 line1 = np.tan(theta_tilt * np.pi / 180) * (xs - x_center) + y_center
226 line2 = np.tan((theta_tilt + 90) * np.pi / 180) * (xs - x_center) + y_center
227 return xs, line1, line2
230def order01_positions(holo_center, N, theta_tilt, theta0=0, lambda_constructor=639e-6, verbose=True): # pragma: no cover
231 """Return the order 0 and order 1 positions of an hologram."""
232 # refraction angle between order 0 and order 1 at construction
233 alpha = np.arcsin(N * lambda_constructor + np.sin(theta0))
234 # distance between order 0 and order 1 in pixels
235 AB = (np.tan(alpha) - np.tan(theta0)) * parameters.DISTANCE2CCD / parameters.CCD_PIXEL2MM
236 # position of order 1 in pixels
237 x_center = holo_center[0]
238 y_center = holo_center[1]
239 order1_position = [0.5 * AB * np.cos(theta_tilt * np.pi / 180) + x_center,
240 0.5 * AB * np.sin(theta_tilt * np.pi / 180) + y_center]
241 # position of order 0 in pixels
242 order0_position = [-0.5 * AB * np.cos(theta_tilt * np.pi / 180) + x_center,
243 -0.5 * AB * np.sin(theta_tilt * np.pi / 180) + y_center]
244 if verbose:
245 my_logger = set_logger(__name__)
246 my_logger.info(f'\n\tOrder 0 position at x0 = {order0_position[0]:.1f} and y0 = {order0_position[1]:.1f}'
247 f'\n\tOrder +1 position at x0 = {order1_position[0]:.1f} and y0 = {order1_position[1]:.1f}'
248 f'\n\tDistance between the orders: {AB:.2f} pixels ({AB * parameters.CCD_PIXEL2MM:.2f} mm)')
249 return order0_position, order1_position, AB
252def find_order01_positions(holo_center, N_interp, theta_interp, lambda_constructor=639e-6, verbose=True): # pragma: no cover
253 """Find the order 0 and order 1 positions of an hologram."""
254 N = N_interp(holo_center)
255 theta_tilt = theta_interp(holo_center)
256 theta0 = 0
257 convergence = 0
258 while abs(N - convergence) > 1e-6:
259 order0_position, order1_position, AB = order01_positions(holo_center, N, theta_tilt, theta0,
260 lambda_constructor=lambda_constructor, verbose=False)
261 convergence = np.copy(N)
262 N = N_interp(order0_position)
263 theta_tilt = theta_interp(order0_position)
264 theta0 = get_theta0(order0_position)
265 order0_position, order1_position, AB = order01_positions(holo_center, N, theta_tilt, theta0,
266 lambda_constructor=lambda_constructor, verbose=verbose)
267 return order0_position, order1_position, AB
270class Grating:
271 """Generic class for dispersers."""
273 def __init__(self, N, label="", D=parameters.DISTANCE2CCD, data_dir=parameters.DISPERSER_DIR, verbose=False):
274 """Initialize a standard grating object.
276 Parameters
277 ----------
278 N: float
279 The number of grooves per mm of the grating
280 label: str
281 String label for the grating (default: '')
282 D: float
283 The distance between the CCD and the disperser in mm.
284 data_dir: str
285 The directory where information about this disperser is stored. Must be in the form data_dir/label/...
286 (default: parameters.DISPERSER_DIR)
287 verbose: bool
288 Set to True to increase the verbosity of the initialisation (default: False)
290 Examples
291 --------
292 >>> g = Grating(400)
293 >>> print(g.N_input)
294 400
295 >>> g = Grating(400, label="Ron400", data_dir=parameters.DISPERSER_DIR)
296 >>> print(f"{g.N_input:6f}")
297 400.869182
298 >>> assert g.D is parameters.DISTANCE2CCD
299 """
300 self.my_logger = set_logger(self.__class__.__name__)
301 self.N_input = N
302 self.N_err = 1
303 self.D = D
304 self.label = label
305 self.full_name = label
306 self.data_dir = data_dir
307 self.theta_tilt = 0
308 self.transmission = None
309 self.transmission_err = None
310 self.ratio_order_2over1 = None
311 self.flat_ratio_order_2over1 = True
312 self.load_files(verbose=verbose)
314 def N(self, x):
315 """Return the number of grooves per mm of the grating at position x.
317 Parameters
318 ----------
319 x: array
320 The [x,y] pixel position.
322 Returns
323 -------
324 N: float
325 The number of grooves per mm at position x
327 Examples
328 --------
329 >>> g = Grating(400)
330 >>> g.N((500,500))
331 400
332 """
333 return self.N_input
335 def load_files(self, verbose=False):
336 """If they exists, load the files in data_dir/label/ to set the main
337 characteristics of the grating. Overrides the N input at initialisation.
339 Parameters
340 ----------
341 verbose: bool
342 Set to True to get more verbosity.
344 Examples
345 --------
347 The files exist:
349 >>> g = Grating(400, label='Ron400')
350 >>> g.N_input
351 400.86918248709316
352 >>> print(g.theta_tilt)
353 -0.277
355 The files do not exist:
357 >>> g = Grating(400, label='XXX')
358 >>> g.N_input
359 400
360 >>> print(g.theta_tilt)
361 0
363 """
364 filename = self.data_dir + self.label + "/N.txt"
365 if os.path.isfile(filename):
366 a = np.loadtxt(filename)
367 self.N_input = a[0]
368 self.N_err = a[1]
369 else:
370 raise FileNotFoundError(f"Failed to load {filename} for {self.label}")
372 filename = self.data_dir + self.label + "/full_name.txt"
373 if os.path.isfile(filename):
374 with open(filename, 'r') as f:
375 for line in f: # MFL: you really just want the last line of the file?
376 self.full_name = line.rstrip('\n')
377 else:
378 raise FileNotFoundError(f"Failed to load {filename} for {self.label}")
380 filename = self.data_dir + self.label + "/transmission.txt"
381 if os.path.isfile(filename):
382 a = np.loadtxt(filename)
383 l, t, e = a.T
384 self.transmission = interpolate.interp1d(l, t, bounds_error=False, fill_value=0.)
385 self.transmission_err = interpolate.interp1d(l, e, bounds_error=False, fill_value=0.)
386 else:
387 self.transmission = lambda x: np.ones_like(x).astype(float)
388 self.transmission_err = lambda x: np.zeros_like(x).astype(float)
389 msg = f"Failed to load {filename} for {self.label}, using default (perfect) transmission"
390 self.my_logger.info(msg)
392 filename = self.data_dir + self.label + "/ratio_order_2over1.txt"
393 if os.path.isfile(filename):
394 a = np.loadtxt(filename)
395 if a.T.shape[0] == 2:
396 l, t = a.T
397 else:
398 l, t, e = a.T
399 self.ratio_order_2over1 = interpolate.interp1d(l, t, bounds_error=False, kind="linear",
400 fill_value="extrapolate") # "(0, t[-1]))
401 self.flat_ratio_order_2over1 = False
402 else:
403 self.ratio_order_2over1 = lambda x: parameters.GRATING_ORDER_2OVER1 * np.ones_like(x).astype(float)
404 self.flat_ratio_order_2over1 = True
405 filename = self.data_dir + self.label + "/hologram_center.txt"
406 if os.path.isfile(filename):
407 lines = [ll.rstrip('\n') for ll in open(filename)]
408 self.theta_tilt = float(lines[1].split(' ')[2])
409 else:
410 self.theta_tilt = 0
411 msg = f"Failed to load {filename} for {self.label}, using default tilt of {self.theta_tilt}"
412 self.my_logger.info(msg)
414 if verbose:
415 self.my_logger.info(f'\n\tGrating average tilt of {self.theta_tilt:.1f} degrees')
417 def refraction_angle(self, deltaX, x0):
418 """ Return the refraction angle with respect to the disperser normal, using geometrical consideration,
419 given the distance to order 0 in pixels.
421 Parameters
422 ----------
423 deltaX: float
424 The distance in pixels between the order 0 and a spectrum pixel in the rotated image.
425 x0: array
426 The order 0 position [x0,y0] in the full non-rotated image.
428 Returns
429 -------
430 theta: float
431 The refraction angle in radians.
433 Examples
434 --------
435 >>> g = Grating(400)
436 >>> theta = g.refraction_angle(500, [parameters.CCD_IMSIZE/2, parameters.CCD_IMSIZE/2])
437 >>> assert np.isclose(theta, np.arctan2(500*parameters.CCD_PIXEL2MM, parameters.DISTANCE2CCD))
438 """
439 theta = get_refraction_angle(deltaX, x0, D=self.D)
440 return theta
442 def refraction_angle_lambda(self, lambdas, x0, order=1):
443 """ Return the refraction angle with respect to the disperser normal, using geometrical consideration,
444 given the wavelength in nm and the order of the spectrum.
446 Parameters
447 ----------
448 lambdas: float, array
449 The distance in pixels between the order 0 and a spectrum pixel in the rotated image.
450 x0: float, array
451 The order 0 pixel position [x0,y0] in the full non-rotated image.
452 order: int
453 The order of the spectrum.
455 Returns
456 -------
457 theta: float
458 The refraction angle in radians.
460 Examples
461 --------
462 >>> g = Grating(400)
463 >>> theta = g.refraction_angle(500, [parameters.CCD_IMSIZE/2, parameters.CCD_IMSIZE/2])
464 >>> assert np.isclose(theta, np.arctan2(500*parameters.CCD_PIXEL2MM, parameters.DISTANCE2CCD))
465 """
466 theta0 = get_theta0(x0)
467 return np.arcsin(order * lambdas * 1e-6 * self.N(x0) + np.sin(theta0))
469 def grating_refraction_angle_to_lambda(self, thetas, x0, order=1):
470 """ Convert refraction angles into wavelengths (in nm) with.
472 Parameters
473 ----------
474 thetas: array, float
475 Refraction angles in radian.
476 x0: float or [float, float]
477 Order 0 position detected in the non-rotated image.
478 order: int
479 Order of the spectrum (default: 1)
481 Examples
482 --------
483 >>> disperser = Grating(N=300, D=55)
484 >>> x0 = [800,800]
485 >>> lambdas = np.arange(300, 900, 100)
486 >>> thetas = disperser.refraction_angle_lambda(lambdas, x0, order=1)
487 >>> print(thetas)
488 [0.0896847 0.11985125 0.15012783 0.18054376 0.21112957 0.24191729]
489 >>> lambdas = disperser.grating_refraction_angle_to_lambda(thetas, x0, order=1)
490 >>> print(lambdas)
491 [300. 400. 500. 600. 700. 800.]
492 """
493 theta0 = get_theta0(x0)
494 lambdas = (np.sin(thetas) - np.sin(theta0)) / (order * self.N(x0))
495 return lambdas * 1e6
497 def grating_pixel_to_lambda(self, deltaX, x0, order=1):
498 """ Convert pixels into wavelengths (in nm) with.
500 Parameters
501 ----------
502 deltaX: array, float
503 *Algebraic* pixel distances to order 0 along the dispersion axis.
504 x0: float or [float, float]
505 Order 0 position detected in the non-rotated image.
506 order: int
507 Order of the spectrum (default: 1).
509 Examples
510 --------
511 >>> disperser = Grating(N=300, D=55)
512 >>> x0 = [800,800]
513 >>> deltaX = np.arange(0,1000,1).astype(float)
514 >>> lambdas = disperser.grating_pixel_to_lambda(deltaX, x0, order=1)
515 >>> print(lambdas[:5])
516 [0. 1.45454532 2.90909063 4.36363511 5.81817793]
517 >>> pixels = disperser.grating_lambda_to_pixel(lambdas, x0, order=1)
518 >>> print(pixels[:5])
519 [0. 1. 2. 3. 4.]
520 """
521 theta = self.refraction_angle(deltaX, x0)
522 theta0 = get_theta0(x0)
523 lambdas = (np.sin(theta) - np.sin(theta0)) / (order * self.N(x0))
524 return lambdas * 1e6
526 def grating_lambda_to_pixel(self, lambdas, x0, order=1):
527 """ Convert wavelength in nm into pixel distance with order 0.
529 Parameters
530 ----------
531 lambdas: array, float
532 Wavelengths in nm.
533 x0: float or [float, float]
534 Order 0 position detected in the raw image.
535 order: int
536 Order of the spectrum (default: 1)
538 Examples
539 --------
540 >>> disperser = Grating(N=300, D=55)
541 >>> x0 = [800,800]
542 >>> deltaX = np.arange(0,1000,1).astype(float)
543 >>> lambdas = disperser.grating_pixel_to_lambda(deltaX, x0, order=1)
544 >>> print(lambdas[:5])
545 [0. 1.45454532 2.90909063 4.36363511 5.81817793]
546 >>> pixels = disperser.grating_lambda_to_pixel(lambdas, x0, order=1)
547 >>> print(pixels[:5])
548 [0. 1. 2. 3. 4.]
549 """
550 lambdas = np.copy(lambdas)
551 theta0 = get_theta0(x0)
552 theta = self.refraction_angle_lambda(lambdas, x0, order=order)
553 deltaX = self.D * (np.tan(theta) - np.tan(theta0)) / parameters.CCD_PIXEL2MM
554 return deltaX
556 def grating_resolution(self, deltaX, x0, order=1):
557 """ Return wavelength resolution in nm per pixel.
558 See mathematica notebook: derivative of the grating formula.
559 x0: the order 0 position on the full raw image.
560 deltaX: the distance in pixels between order 0 and signal point
561 in the rotated image."""
562 delta = get_delta_pix_ortho(deltaX, x0, D=self.D) * parameters.CCD_PIXEL2MM
563 # theta = self.refraction_angle(x,x0,order=order)
564 # res = (np.cos(theta)**3*CCD_PIXEL2MM*1e6)/(order*self.N(x0)*self.D)
565 res = (self.D ** 2 / pow(self.D ** 2 + delta ** 2, 1.5)) * parameters.CCD_PIXEL2MM * 1e6 / (order * self.N(x0))
566 return res
568 def plot_transmission(self, xlim=None):
569 """Plot the transmission of the grating with respect to the wavelength (in nm).
571 Parameters
572 ----------
573 xlim: [xmin,xmax], optional
574 List of the X axis extrema (default: None).
576 Examples
577 --------
578 >>> g = Grating(400, label='Ron400')
579 >>> g.plot_transmission(xlim=(400,800))
580 """
581 wavelengths = np.linspace(parameters.LAMBDA_MIN, parameters.LAMBDA_MAX, 100)
582 if xlim is not None:
583 wavelengths = np.linspace(xlim[0], xlim[1], 100)
584 plt.plot(wavelengths, self.transmission(wavelengths), 'b-', label=self.label)
585 plt.plot(wavelengths, self.ratio_order_2over1(wavelengths), 'r-', label="Ratio 2/1")
586 plt.xlabel(r"$\lambda$ [nm]")
587 plt.ylabel(r"Transmission")
588 plt.grid()
589 plt.legend(loc='best')
590 if parameters.DISPLAY:
591 plt.show()
592 if parameters.PdfPages:
593 parameters.PdfPages.savefig()
596class Hologram(Grating):
598 def __init__(self, label, D=parameters.DISTANCE2CCD, data_dir=parameters.DISPERSER_DIR,
599 lambda_plot=256000, verbose=False):
600 """Initialize an Hologram object, given its label. Specification are loaded from text files
601 in data_dir/label/... Inherit from the Grating class.
603 Parameters
604 ----------
605 label: str
606 String label for the grating (default: '')
607 D: float
608 The distance between the CCD and the disperser in mm.
609 data_dir: str
610 The directory where information about this disperser is stored. Must be in the form data_dir/label/...
611 (default: parameters.DISPERSER_DIR)
612 lambda_plot: float, optional
613 Wavelength to plot the hologram pattern (default: 256000).
614 verbose: bool
615 Set to True to increase the verbosity of the initialisation (default: False)
617 Examples
618 --------
619 >>> h = Hologram(label="HoloPhP", data_dir=parameters.DISPERSER_DIR)
620 >>> h.label
621 'HoloPhP'
622 >>> h.N((500,500))
623 345.4794168822986
625 """
626 Grating.__init__(self, 350, D=D, label=label, data_dir=data_dir, verbose=False)
627 self.holo_center = None # center of symmetry of the hologram interferences in pixels
628 self.theta = None # interpolated rotation angle map of the hologram from data in degrees
629 self.theta_data = None # rotation angle map data of the hologram from data in degrees
630 self.theta_x = None # x coordinates for the interpolated rotation angle map
631 self.theta_y = None # y coordinates for the interpolated rotation angle map
632 self.x_lines = None
633 self.line1 = None
634 self.line2 = None
635 self.order0_position = None
636 self.order1_position = None
637 self.AB = None
638 self.N_x = None
639 self.N_y = None
640 self.N_data = None
641 self.N_interp = None
642 self.N_fit = None
643 self.lambda_plot = lambda_plot
644 self.is_hologram = True
645 self.load_specs(verbose=verbose)
647 def N(self, x):
648 """Return the number of grooves per mm of the grating at position x. If the position is inside
649 the data provided by the text files, this number is computed from an interpolation. If it lies outside,
650 it is computed from a 2D polynomial fit.
652 Parameters
653 ----------
654 x: float, array
655 The [x,y] pixel position on the CCD.
657 Returns
658 -------
659 N: float
660 The number of grooves per mm at position x
662 Examples
663 --------
664 >>> h = Hologram('HoloPhP')
665 >>> h.N((500,500))
666 345.4794168822986
667 >>> h.N((0,0))
668 283.56876727310373
669 """
671 if x[0] < np.min(self.N_x) or x[0] > np.max(self.N_x) \
672 or x[1] < np.min(self.N_y) or x[1] > np.max(self.N_y):
673 N = self.N_fit(x[0], x[1])
674 else:
675 N = int(self.N_interp(x))
676 return N
678 def load_specs(self, verbose=True):
679 """Load the files in data_dir/label/ to set the main
680 characteristics of the hologram. If they do not exist, default values are used.
682 Parameters
683 ----------
684 verbose: bool
685 Set to True to get more verbosity.
687 Examples
688 --------
690 The files exist:
692 >>> h = Hologram(label='HoloPhP')
693 >>> h.N((500,500))
694 345.4794168822986
695 >>> h.theta((500,500))
696 -1.3393287109201792
697 >>> h.holo_center
698 [856.004, 562.34]
700 The files do not exist:
702 >>> h = Hologram(label='XXX')
703 >>> h.N((500,500))
704 350
705 >>> h.theta((500,500))
706 0
707 >>> h.holo_center
708 [1024.0, 1024.0]
710 """
711 if verbose:
712 self.my_logger.info(f'\n\tLoad disperser {self.label}:\n\tfrom {os.path.join(self.data_dir, self.label)}')
713 filename = self.data_dir + self.label + "/hologram_grooves_per_mm.txt"
714 if os.path.isfile(filename):
715 a = np.loadtxt(filename)
716 self.N_x, self.N_y, self.N_data = a.T
717 if parameters.CCD_REBIN > 1:
718 self.N_x /= parameters.CCD_REBIN
719 self.N_y /= parameters.CCD_REBIN
720 N_interp = interpolate.interp2d(self.N_x, self.N_y, self.N_data, kind='cubic')
721 self.N_fit = fit_poly2d(self.N_x, self.N_y, self.N_data, order=2)
722 self.N_interp = lambda x: float(N_interp(x[0], x[1]))
723 else:
724 self.is_hologram = False
725 self.N_x = np.arange(0, parameters.CCD_IMSIZE)
726 self.N_y = np.arange(0, parameters.CCD_IMSIZE)
727 filename = self.data_dir + self.label + "/N.txt"
728 if os.path.isfile(filename):
729 a = np.loadtxt(filename)
730 self.N_interp = lambda x: a[0]
731 self.N_fit = lambda x, y: a[0]
732 else:
733 raise ValueError("To define an hologram, you must provide hologram_grooves_per_mm.txt or N.txt files.")
734 filename = self.data_dir + self.label + "/hologram_center.txt"
735 if os.path.isfile(filename):
736 lines = [ll.rstrip('\n') for ll in open(filename)]
737 self.holo_center = list(map(float, lines[1].split(' ')[:2]))
738 self.theta_tilt = float(lines[1].split(' ')[2])
739 else:
740 self.holo_center = [0.5 * parameters.CCD_IMSIZE, 0.5 * parameters.CCD_IMSIZE]
741 self.theta_tilt = 0
742 filename = self.data_dir + self.label + "/hologram_rotation_angles.txt"
743 if os.path.isfile(filename):
744 a = np.loadtxt(filename)
745 self.theta_x, self.theta_y, self.theta_data = a.T
746 if parameters.CCD_REBIN > 1:
747 self.theta_x /= parameters.CCD_REBIN
748 self.theta_y /= parameters.CCD_REBIN
749 theta_interp = interpolate.interp2d(self.theta_x, self.theta_y, self.theta_data, kind='cubic')
750 self.theta = lambda x: float(theta_interp(x[0], x[1]))
751 else:
752 self.theta = lambda x: self.theta_tilt
753 self.x_lines, self.line1, self.line2 = neutral_lines(self.holo_center[0], self.holo_center[1], self.theta_tilt)
754 if verbose:
755 if self.is_hologram:
756 self.my_logger.info(f'\n\tHologram characteristics:'
757 f'\n\tN = {self.N(self.holo_center):.2f} +/- {self.N_err:.2f} '
758 f'grooves/mm at hologram center'
759 f'\n\tHologram center at x0 = {self.holo_center[0]:.1f} '
760 f'and y0 = {self.holo_center[1]:.1f} with average tilt of {self.theta_tilt:.1f} '
761 f'degrees')
762 else:
763 self.my_logger.info(f'\n\tGrating characteristics:'
764 f'\n\tN = {self.N([0, 0]):.2f} +/- {self.N_err:.2f} grooves/mm'
765 f'\n\tAverage tilt of {self.theta_tilt:.1f} degrees')
768if __name__ == "__main__": 768 ↛ 769line 768 didn't jump to line 769, because the condition on line 768 was never true
769 import doctest
771 doctest.testmod()