Coverage for spectractor/extractor/dispersers.py: 11%

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

252 statements  

1from scipy import interpolate 

2from scipy import ndimage 

3import matplotlib.pyplot as plt 

4import numpy as np 

5import os 

6 

7from spectractor import parameters 

8from spectractor.tools import fit_poly2d 

9from spectractor.logbook import set_logger 

10 

11 

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. 

17 

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) 

28 

29 Returns 

30 ------- 

31 hologram: 2D-array, 

32 The hologram figure, of shape (CCD_IMSIZE,CCD_IMSIZE) 

33 

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 

55 

56 

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. 

61 

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) 

70 

71 Returns 

72 ------- 

73 hologram: 2D-array, 

74 The hologram figure, of shape (CCD_IMSIZE,CCD_IMSIZE) 

75 

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]] 

85 

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 

95 

96 

97def get_theta0(x0): 

98 """ Return the incident angle on the disperser in radians, with respect to the disperser normal and the X axis. 

99 

100 Parameters 

101 ---------- 

102 x0: float, tuple, list 

103 The order 0 position in the full non-rotated image. 

104 

105 Returns 

106 ------- 

107 theta0: float 

108 The incident angle in radians 

109 

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 

121 

122 

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. 

127 

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. 

136 

137 Returns 

138 ------- 

139 distance: float 

140 The projected distance in pixels 

141 

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 

153 

154 

155def get_refraction_angle(deltaX, x0, D=parameters.DISTANCE2CCD): 

156 """ Return the refraction angle with respect to the disperser normal, using geometrical consideration. 

157 

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. 

166 

167 Returns 

168 ------- 

169 theta: float 

170 The refraction angle in radians. 

171 

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 

184 

185 

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. 

190 

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). 

203 

204 Returns 

205 ------- 

206 theta: float 

207 The number of grooves per mm. 

208 

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 

220 

221 

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 

228 

229 

230def order01_positions(holo_center, N, theta_tilt, theta0=0, verbose=True): 

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 * parameters.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 

250 

251 

252def find_order01_positions(holo_center, N_interp, theta_interp, verbose=True): 

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, verbose=False) 

260 convergence = np.copy(N) 

261 N = N_interp(order0_position) 

262 theta_tilt = theta_interp(order0_position) 

263 theta0 = get_theta0(order0_position) 

264 order0_position, order1_position, AB = order01_positions(holo_center, N, theta_tilt, theta0, verbose=verbose) 

265 return order0_position, order1_position, AB 

266 

267 

268class Grating: 

269 """Generic class for dispersers.""" 

270 

271 def __init__(self, N, label="", D=parameters.DISTANCE2CCD, data_dir=parameters.DISPERSER_DIR, verbose=False): 

272 """Initialize a standard grating object. 

273 

274 Parameters 

275 ---------- 

276 N: float 

277 The number of grooves per mm of the grating 

278 label: str 

279 String label for the grating (default: '') 

280 D: float 

281 The distance between the CCD and the disperser in mm. 

282 data_dir: str 

283 The directory where information about this disperser is stored. Must be in the form data_dir/label/... 

284 (default: parameters.DISPERSER_DIR) 

285 verbose: bool 

286 Set to True to increase the verbosity of the initialisation (default: False) 

287 

288 Examples 

289 -------- 

290 >>> g = Grating(400) 

291 >>> print(g.N_input) 

292 400 

293 >>> g = Grating(400, label="Ron400", data_dir=parameters.DISPERSER_DIR) 

294 >>> print(f"{g.N_input:6f}") 

295 400.869182 

296 >>> assert g.D is parameters.DISTANCE2CCD 

297 """ 

298 self.my_logger = set_logger(self.__class__.__name__) 

299 self.N_input = N 

300 self.N_err = 1 

301 self.D = D 

302 self.label = label 

303 self.full_name = label 

304 self.data_dir = data_dir 

305 self.plate_center = [0.5 * parameters.CCD_IMSIZE, 0.5 * parameters.CCD_IMSIZE] 

306 self.theta_tilt = 0 

307 self.transmission = None 

308 self.transmission_err = None 

309 self.ratio_order_2over1 = None 

310 self.flat_ratio_order_2over1 = True 

311 self.load_files(verbose=verbose) 

312 

313 def N(self, x): 

314 """Return the number of grooves per mm of the grating at position x. 

315 

316 Parameters 

317 ---------- 

318 x: array 

319 The [x,y] pixel position. 

320 

321 Returns 

322 ------- 

323 N: float 

324 The number of grooves per mm at position x 

325 

326 Examples 

327 -------- 

328 >>> g = Grating(400) 

329 >>> g.N((500,500)) 

330 400 

331 """ 

332 return self.N_input 

333 

334 def load_files(self, verbose=False): 

335 """If they exists, load the files in data_dir/label/ to set the main 

336 characteristics of the grating. Overrides the N input at initialisation. 

337 

338 Parameters 

339 ---------- 

340 verbose: bool 

341 Set to True to get more verbosity. 

342 

343 Examples 

344 -------- 

345 

346 The files exist: 

347 

348 >>> g = Grating(400, label='Ron400') 

349 >>> g.N_input 

350 400.86918248709316 

351 >>> print(g.theta_tilt) 

352 -0.277 

353 

354 The files do not exist: 

355 

356 >>> g = Grating(400, label='XXX') 

357 >>> g.N_input 

358 400 

359 >>> print(g.theta_tilt) 

360 0 

361 

362 """ 

363 filename = self.data_dir + self.label + "/N.txt" 

364 if os.path.isfile(filename): 

365 a = np.loadtxt(filename) 

366 self.N_input = a[0] 

367 self.N_err = a[1] 

368 else: # MFL this changes the behaviour, but I think in a good way. Lets talk 

369 raise FileNotFoundError(f"Failed to load {filename} for {self.label}") 

370 

371 filename = self.data_dir + self.label + "/full_name.txt" 

372 if os.path.isfile(filename): 

373 with open(filename, 'r') as f: 

374 for line in f: # MFL: you really just want the last line of the file? 

375 self.full_name = line.rstrip('\n') 

376 else: # MFL this changes the behaviour, but I think in a good way. Lets talk 

377 raise FileNotFoundError(f"Failed to load {filename} for {self.label}") 

378 

379 filename = self.data_dir + self.label + "/transmission.txt" 

380 if os.path.isfile(filename): 

381 a = np.loadtxt(filename) 

382 l, t, e = a.T 

383 self.transmission = interpolate.interp1d(l, t, bounds_error=False, fill_value=0.) 

384 self.transmission_err = interpolate.interp1d(l, e, bounds_error=False, fill_value=0.) 

385 else: 

386 self.transmission = lambda x: np.ones_like(x).astype(float) 

387 self.transmission_err = lambda x: np.zeros_like(x).astype(float) 

388 msg = f"Failed to load {filename} for {self.label}, using default (perfect) transmission" 

389 self.my_logger.info(msg) 

390 

391 filename = self.data_dir + self.label + "/ratio_order_2over1.txt" 

392 if os.path.isfile(filename): 

393 a = np.loadtxt(filename) 

394 if a.T.shape[0] == 2: 

395 l, t = a.T 

396 else: 

397 l, t, e = a.T 

398 self.ratio_order_2over1 = interpolate.interp1d(l, t, bounds_error=False, kind="linear", 

399 fill_value="extrapolate") # "(0, t[-1])) 

400 self.flat_ratio_order_2over1 = False 

401 else: 

402 self.ratio_order_2over1 = lambda x: parameters.GRATING_ORDER_2OVER1 * np.ones_like(x).astype(float) 

403 self.flat_ratio_order_2over1 = True 

404 filename = self.data_dir + self.label + "/hologram_center.txt" 

405 if os.path.isfile(filename): 

406 lines = [ll.rstrip('\n') for ll in open(filename)] 

407 self.theta_tilt = float(lines[1].split(' ')[2]) 

408 else: 

409 self.theta_tilt = 0 

410 msg = f"Failed to load {filename} for {self.label}, using default tilt of {self.theta_tilt}" 

411 self.my_logger.info(msg) 

412 

413 if verbose: 

414 self.my_logger.info(f'\n\tGrating plate center at x0 = {self.plate_center[0]:.1f} ' 

415 f'and y0 = {self.plate_center[1]:.1f} ' 

416 f'with average tilt of {self.theta_tilt:.1f} degrees') 

417 

418 def refraction_angle(self, deltaX, x0): 

419 """ Return the refraction angle with respect to the disperser normal, using geometrical consideration, 

420 given the distance to order 0 in pixels. 

421 

422 Parameters 

423 ---------- 

424 deltaX: float 

425 The distance in pixels between the order 0 and a spectrum pixel in the rotated image. 

426 x0: array 

427 The order 0 position [x0,y0] in the full non-rotated image. 

428 

429 Returns 

430 ------- 

431 theta: float 

432 The refraction angle in radians. 

433 

434 Examples 

435 -------- 

436 >>> g = Grating(400) 

437 >>> theta = g.refraction_angle(500, [parameters.CCD_IMSIZE/2, parameters.CCD_IMSIZE/2]) 

438 >>> assert np.isclose(theta, np.arctan2(500*parameters.CCD_PIXEL2MM, parameters.DISTANCE2CCD)) 

439 """ 

440 theta = get_refraction_angle(deltaX, x0, D=self.D) 

441 return theta 

442 

443 def refraction_angle_lambda(self, lambdas, x0, order=1): 

444 """ Return the refraction angle with respect to the disperser normal, using geometrical consideration, 

445 given the wavelength in nm and the order of the spectrum. 

446 

447 Parameters 

448 ---------- 

449 lambdas: float, array 

450 The distance in pixels between the order 0 and a spectrum pixel in the rotated image. 

451 x0: float, array 

452 The order 0 pixel position [x0,y0] in the full non-rotated image. 

453 order: int 

454 The order of the spectrum. 

455 

456 Returns 

457 ------- 

458 theta: float 

459 The refraction angle in radians. 

460 

461 Examples 

462 -------- 

463 >>> g = Grating(400) 

464 >>> theta = g.refraction_angle(500, [parameters.CCD_IMSIZE/2, parameters.CCD_IMSIZE/2]) 

465 >>> assert np.isclose(theta, np.arctan2(500*parameters.CCD_PIXEL2MM, parameters.DISTANCE2CCD)) 

466 """ 

467 theta0 = get_theta0(x0) 

468 return np.arcsin(order * lambdas * 1e-6 * self.N(x0) + np.sin(theta0)) 

469 

470 def grating_refraction_angle_to_lambda(self, thetas, x0, order=1): 

471 """ Convert refraction angles into wavelengths (in nm) with. 

472 

473 Parameters 

474 ---------- 

475 thetas: array, float 

476 Refraction angles in radian. 

477 x0: float or [float, float] 

478 Order 0 position detected in the non-rotated image. 

479 order: int 

480 Order of the spectrum (default: 1) 

481 

482 Examples 

483 -------- 

484 >>> disperser = Grating(N=300, D=55) 

485 >>> x0 = [800,800] 

486 >>> lambdas = np.arange(300, 900, 100) 

487 >>> thetas = disperser.refraction_angle_lambda(lambdas, x0, order=1) 

488 >>> print(thetas) 

489 [0.0896847 0.11985125 0.15012783 0.18054376 0.21112957 0.24191729] 

490 >>> lambdas = disperser.grating_refraction_angle_to_lambda(thetas, x0, order=1) 

491 >>> print(lambdas) 

492 [300. 400. 500. 600. 700. 800.] 

493 """ 

494 theta0 = get_theta0(x0) 

495 lambdas = (np.sin(thetas) - np.sin(theta0)) / (order * self.N(x0)) 

496 return lambdas * 1e6 

497 

498 def grating_pixel_to_lambda(self, deltaX, x0, order=1): 

499 """ Convert pixels into wavelengths (in nm) with. 

500 

501 Parameters 

502 ---------- 

503 deltaX: array, float 

504 *Algebraic* pixel distances to order 0 along the dispersion axis. 

505 x0: float or [float, float] 

506 Order 0 position detected in the non-rotated image. 

507 order: int 

508 Order of the spectrum (default: 1). 

509 

510 Examples 

511 -------- 

512 >>> disperser = Grating(N=300, D=55) 

513 >>> x0 = [800,800] 

514 >>> deltaX = np.arange(0,1000,1).astype(float) 

515 >>> lambdas = disperser.grating_pixel_to_lambda(deltaX, x0, order=1) 

516 >>> print(lambdas[:5]) 

517 [0. 1.45454532 2.90909063 4.36363511 5.81817793] 

518 >>> pixels = disperser.grating_lambda_to_pixel(lambdas, x0, order=1) 

519 >>> print(pixels[:5]) 

520 [0. 1. 2. 3. 4.] 

521 """ 

522 theta = self.refraction_angle(deltaX, x0) 

523 theta0 = get_theta0(x0) 

524 lambdas = (np.sin(theta) - np.sin(theta0)) / (order * self.N(x0)) 

525 return lambdas * 1e6 

526 

527 def grating_lambda_to_pixel(self, lambdas, x0, order=1): 

528 """ Convert wavelength in nm into pixel distance with order 0. 

529 

530 Parameters 

531 ---------- 

532 lambdas: array, float 

533 Wavelengths in nm. 

534 x0: float or [float, float] 

535 Order 0 position detected in the raw image. 

536 order: int 

537 Order of the spectrum (default: 1) 

538 

539 Examples 

540 -------- 

541 >>> disperser = Grating(N=300, D=55) 

542 >>> x0 = [800,800] 

543 >>> deltaX = np.arange(0,1000,1).astype(float) 

544 >>> lambdas = disperser.grating_pixel_to_lambda(deltaX, x0, order=1) 

545 >>> print(lambdas[:5]) 

546 [0. 1.45454532 2.90909063 4.36363511 5.81817793] 

547 >>> pixels = disperser.grating_lambda_to_pixel(lambdas, x0, order=1) 

548 >>> print(pixels[:5]) 

549 [0. 1. 2. 3. 4.] 

550 """ 

551 lambdas = np.copy(lambdas) 

552 theta0 = get_theta0(x0) 

553 theta = self.refraction_angle_lambda(lambdas, x0, order=order) 

554 deltaX = self.D * (np.tan(theta) - np.tan(theta0)) / parameters.CCD_PIXEL2MM 

555 return deltaX 

556 

557 def grating_resolution(self, deltaX, x0, order=1): 

558 """ Return wavelength resolution in nm per pixel. 

559 See mathematica notebook: derivative of the grating formula. 

560 x0: the order 0 position on the full raw image. 

561 deltaX: the distance in pixels between order 0 and signal point  

562 in the rotated image.""" 

563 delta = get_delta_pix_ortho(deltaX, x0, D=self.D) * parameters.CCD_PIXEL2MM 

564 # theta = self.refraction_angle(x,x0,order=order) 

565 # res = (np.cos(theta)**3*CCD_PIXEL2MM*1e6)/(order*self.N(x0)*self.D) 

566 res = (self.D ** 2 / pow(self.D ** 2 + delta ** 2, 1.5)) * parameters.CCD_PIXEL2MM * 1e6 / (order * self.N(x0)) 

567 return res 

568 

569 def plot_transmission(self, xlim=None): 

570 """Plot the transmission of the grating with respect to the wavelength (in nm). 

571 

572 Parameters 

573 ---------- 

574 xlim: [xmin,xmax], optional 

575 List of the X axis extrema (default: None). 

576 

577 Examples 

578 -------- 

579 >>> g = Grating(400, label='Ron400') 

580 >>> g.plot_transmission(xlim=(400,800)) 

581 """ 

582 wavelengths = np.linspace(parameters.LAMBDA_MIN, parameters.LAMBDA_MAX, 100) 

583 if xlim is not None: 

584 wavelengths = np.linspace(xlim[0], xlim[1], 100) 

585 plt.plot(wavelengths, self.transmission(wavelengths), 'b-', label=self.label) 

586 plt.plot(wavelengths, self.ratio_order_2over1(wavelengths), 'r-', label="Ratio 2/1") 

587 plt.xlabel(r"$\lambda$ [nm]") 

588 plt.ylabel(r"Transmission") 

589 plt.grid() 

590 plt.legend(loc='best') 

591 if parameters.DISPLAY: 

592 plt.show() 

593 if parameters.PdfPages: 

594 parameters.PdfPages.savefig() 

595 

596 

597class Hologram(Grating): 

598 

599 def __init__(self, label, D=parameters.DISTANCE2CCD, data_dir=parameters.DISPERSER_DIR, 

600 lambda_plot=256000, verbose=False): 

601 """Initialize an Hologram object, given its label. Specification are loaded from text files 

602 in data_dir/label/... Inherit from the Grating class. 

603 

604 Parameters 

605 ---------- 

606 label: str 

607 String label for the grating (default: '') 

608 D: float 

609 The distance between the CCD and the disperser in mm. 

610 data_dir: str 

611 The directory where information about this disperser is stored. Must be in the form data_dir/label/... 

612 (default: parameters.DISPERSER_DIR) 

613 lambda_plot: float, optional 

614 Wavelength to plot the hologram pattern (default: 256000). 

615 verbose: bool 

616 Set to True to increase the verbosity of the initialisation (default: False) 

617 

618 Examples 

619 -------- 

620 >>> h = Hologram(label="HoloPhP", data_dir=parameters.DISPERSER_DIR) 

621 >>> h.label 

622 'HoloPhP' 

623 >>> h.N((500,500)) 

624 345.4794168822986 

625 

626 """ 

627 Grating.__init__(self, parameters.GROOVES_PER_MM, D=D, label=label, data_dir=data_dir, verbose=False) 

628 self.holo_center = None # center of symmetry of the hologram interferences in pixels 

629 self.plate_center = None # center of the hologram plate 

630 self.theta = None # interpolated rotation angle map of the hologram from data in degrees 

631 self.theta_data = None # rotation angle map data of the hologram from data in degrees 

632 self.theta_x = None # x coordinates for the interpolated rotation angle map 

633 self.theta_y = None # y coordinates for the interpolated rotation angle map 

634 self.x_lines = None 

635 self.line1 = None 

636 self.line2 = None 

637 self.order0_position = None 

638 self.order1_position = None 

639 self.AB = None 

640 self.N_x = None 

641 self.N_y = None 

642 self.N_data = None 

643 self.N_interp = None 

644 self.N_fit = None 

645 self.lambda_plot = lambda_plot 

646 self.is_hologram = True 

647 self.load_specs(verbose=verbose) 

648 

649 def N(self, x): 

650 """Return the number of grooves per mm of the grating at position x. If the position is inside 

651 the data provided by the text files, this number is computed from an interpolation. If it lies outside, 

652 it is computed from a 2D polynomial fit. 

653 

654 Parameters 

655 ---------- 

656 x: float, array 

657 The [x,y] pixel position on the CCD. 

658 

659 Returns 

660 ------- 

661 N: float 

662 The number of grooves per mm at position x 

663 

664 Examples 

665 -------- 

666 >>> h = Hologram('HoloPhP') 

667 >>> h.N((500,500)) 

668 345.4794168822986 

669 >>> h.N((0,0)) 

670 283.56876727310373 

671 """ 

672 

673 if x[0] < np.min(self.N_x) or x[0] > np.max(self.N_x) \ 

674 or x[1] < np.min(self.N_y) or x[1] > np.max(self.N_y): 

675 N = self.N_fit(x[0], x[1]) 

676 else: 

677 N = int(self.N_interp(x)) 

678 return N 

679 

680 def load_specs(self, verbose=True): 

681 """Load the files in data_dir/label/ to set the main 

682 characteristics of the hologram. If they do not exist, default values are used. 

683 

684 Parameters 

685 ---------- 

686 verbose: bool 

687 Set to True to get more verbosity. 

688 

689 Examples 

690 -------- 

691 

692 The files exist: 

693 

694 >>> h = Hologram(label='HoloPhP') 

695 >>> h.N((500,500)) 

696 345.4794168822986 

697 >>> h.theta((500,500)) 

698 -1.3393287109201792 

699 >>> h.holo_center 

700 [856.004, 562.34] 

701 

702 The files do not exist: 

703 

704 >>> h = Hologram(label='XXX') 

705 >>> h.N((500,500)) 

706 350 

707 >>> h.theta((500,500)) 

708 0 

709 >>> h.holo_center 

710 [1024.0, 1024.0] 

711 

712 """ 

713 if verbose: 

714 self.my_logger.info(f'\n\tLoad disperser {self.label}:\n\tfrom {os.path.join(self.data_dir, self.label)}') 

715 filename = self.data_dir + self.label + "/hologram_grooves_per_mm.txt" 

716 if os.path.isfile(filename): 

717 a = np.loadtxt(filename) 

718 self.N_x, self.N_y, self.N_data = a.T 

719 if parameters.CCD_REBIN > 1: 

720 self.N_x /= parameters.CCD_REBIN 

721 self.N_y /= parameters.CCD_REBIN 

722 N_interp = interpolate.interp2d(self.N_x, self.N_y, self.N_data, kind='cubic') 

723 self.N_fit = fit_poly2d(self.N_x, self.N_y, self.N_data, order=2) 

724 self.N_interp = lambda x: float(N_interp(x[0], x[1])) 

725 else: 

726 self.is_hologram = False 

727 self.N_x = np.arange(0, parameters.CCD_IMSIZE) 

728 self.N_y = np.arange(0, parameters.CCD_IMSIZE) 

729 filename = self.data_dir + self.label + "/N.txt" 

730 if os.path.isfile(filename): 

731 a = np.loadtxt(filename) 

732 self.N_interp = lambda x: a[0] 

733 self.N_fit = lambda x, y: a[0] 

734 else: 

735 self.N_interp = lambda x: parameters.GROOVES_PER_MM 

736 self.N_fit = lambda x, y: parameters.GROOVES_PER_MM 

737 filename = self.data_dir + self.label + "/hologram_center.txt" 

738 if os.path.isfile(filename): 

739 lines = [ll.rstrip('\n') for ll in open(filename)] 

740 self.holo_center = list(map(float, lines[1].split(' ')[:2])) 

741 self.theta_tilt = float(lines[1].split(' ')[2]) 

742 else: 

743 self.holo_center = [0.5 * parameters.CCD_IMSIZE, 0.5 * parameters.CCD_IMSIZE] 

744 self.theta_tilt = 0 

745 filename = self.data_dir + self.label + "/hologram_rotation_angles.txt" 

746 if os.path.isfile(filename): 

747 a = np.loadtxt(filename) 

748 self.theta_x, self.theta_y, self.theta_data = a.T 

749 if parameters.CCD_REBIN > 1: 

750 self.theta_x /= parameters.CCD_REBIN 

751 self.theta_y /= parameters.CCD_REBIN 

752 theta_interp = interpolate.interp2d(self.theta_x, self.theta_y, self.theta_data, kind='cubic') 

753 self.theta = lambda x: float(theta_interp(x[0], x[1])) 

754 else: 

755 self.theta = lambda x: self.theta_tilt 

756 self.plate_center = [0.5 * parameters.CCD_IMSIZE + parameters.PLATE_CENTER_SHIFT_X / parameters.CCD_PIXEL2MM, 

757 0.5 * parameters.CCD_IMSIZE + parameters.PLATE_CENTER_SHIFT_Y / parameters.CCD_PIXEL2MM] 

758 self.x_lines, self.line1, self.line2 = neutral_lines(self.holo_center[0], self.holo_center[1], self.theta_tilt) 

759 if verbose: 

760 if self.is_hologram: 

761 self.my_logger.info(f'\n\tHologram characteristics:' 

762 f'\n\tN = {self.N(self.plate_center):.2f} +/- {self.N_err:.2f} ' 

763 f'grooves/mm at plate center' 

764 f'\n\tPlate center at x0 = {self.plate_center[0]:.1f} and ' 

765 f'y0 = {self.plate_center[1]:.1f} with average tilt of {self.theta_tilt:.1f} ' 

766 f'degrees' 

767 f'\n\tHologram center at x0 = {self.holo_center[0]:.1f} ' 

768 f'and y0 = {self.holo_center[1]:.1f} with average tilt of {self.theta_tilt:.1f} ' 

769 f'degrees') 

770 else: 

771 self.my_logger.info(f'\n\tGrating characteristics:' 

772 f'\n\tN = {self.N([0, 0]):.2f} +/- {self.N_err:.2f} grooves/mm' 

773 f'\n\tAverage tilt of {self.theta_tilt:.1f} degrees') 

774 if self.is_hologram: 

775 self.order0_position, self.order1_position, self.AB = find_order01_positions(self.holo_center, 

776 self.N_interp, self.theta, 

777 verbose=verbose) 

778 

779 

780if __name__ == "__main__": 780 ↛ 781line 780 didn't jump to line 781, because the condition on line 780 was never true

781 import doctest 

782 

783 doctest.testmod()