-
Notifications
You must be signed in to change notification settings - Fork 0
/
classes.py
3682 lines (3200 loc) · 159 KB
/
classes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
import ctypes
from typing import Callable
import numpy as np
from ctypes import (Union, Structure, c_int, c_double, c_uint32, c_int32, POINTER, c_void_p, cast, c_ulong,
create_string_buffer, c_int64, pointer)
from ctypes.wintypes import BYTE, INT, HMODULE, LPCSTR, HANDLE, DOUBLE, UINT
from .mcpl import PyOptixMCPLWriter
from .exposed_functions import (get_parameter, set_parameter, align, generate, radiate, enumerate_parameters,
get_element_name, set_recording, get_next_element, get_previous_element,
get_spot_diagram, chain_element_by_id, create_element, clear_impacts, get_impacts_data,
set_transmissive, get_transmissive, get_hologram_pattern, fit_surface_to_slopes,
fit_surface_to_heights, get_array_parameter, get_array_parameter_size,
get_array_parameter_dims, dump_parameter, dump_arg_parameter,
get_parameter_flags, Bounds, Parameter, ParamArray, FrameID, RecordingMode, Diagram,
GratingPatternInformation, save_as_xml, generate_polarized, load_from_xml,
enumerate_stops, set_aperture_activity, get_aperture_activity,
add_rectangular_stop, get_polygon_parameters, add_polygonal_stop, insert_polygonal_stop,
replace_stop_by_polygon, insert_rectangular_stop, replace_stop_by_rectangle,
get_ellipse_parameters, add_elliptical_stop, insert_elliptical_stop,
replace_stop_by_ellipse, add_circular_stop, insert_circular_stop,
replace_stop_by_circle, get_surface_frame, find_element_id, get_exit_frame,
set_error_generator, unset_error_generator, generate_surface_errors, set_surface_errors,
get_surface_errors, set_error_method, ErrMethod, get_error_method)
from scipy.constants import degree, milli
from lxml import etree
import pandas as pd
from .ui_objects import show, figure, PolyAnnotation, ColumnDataSource, LabelSet, display_parameter_sheet, \
plot_beamline, plot_aperture, general_FWHM, show_image_plotly
from .ui_objects import plot_spd as plot_spd_bokeh
from .ui_objects import plot_spd_plotly
from numpy import pi, cos, sin, tan, arccos, arcsin, arctan
from scipy.signal import find_peaks, peak_widths
from scipy.optimize import minimize
from scipy.spatial.transform import Rotation
import pickle
import xarray
# dictionnary for optix to pyoptix attribute import
optix_dictionnary = {
"DX": "d_x",
"DY": "d_y",
"DZ": "d_z",
"Dphi": "d_phi",
"Dpsi": "d_psi",
"Dtheta": "d_theta",
"distance": "distance_from_previous",
"sigmaX": "sigma_x",
"sigmaY": "sigma_y",
"sigmaXdiv": "sigma_x_div",
"sigmaYdiv": "sigma_y_div",
"nRays": "nrays",
"azimuthAngle1": "azimuth_angle1",
"azimuthAngle2": "azimuth_angle2",
"elevationAngle1": "elevation_angle1",
"inverseDist1": "inverse_distance1",
"inverseDist2": "inverse_distance2",
"recordingWavelength": "recording_wavelength",
"lineDensity": "line_density",
"invp": "inverse_p",
"invq": "inverse_q",
"waistX": "waist_x",
"waistY": "waist_y",
"surfaceLimits": "surface_limits",
"apertureX": "aperture_x",
"trajectoryRadius": "trajectory_radius",
}
global plot_spd
global backend
global show_image
def raise_not_implemented():
raise NotImplementedError
def set_backend(bckend="bokeh"):
"""
Toggles between a bokeh backend for the spot diagrams and a plotly one (preferred)
:param bckend: backend to be chosen can be 'bokeh' or 'plotly'
:type bckend: str
"""
global plot_spd
global backend
global show_image
backend = bckend
if backend == "bokeh":
plot_spd = plot_spd_bokeh
show_image = raise_not_implemented # TODO ?
elif backend == "plotly":
plot_spd = plot_spd_plotly
show_image = show_image_plotly
else:
raise ValueError(f"Unknown backend {backend}, should be either bokeh or plotly")
set_backend("plotly")
class PostInitMeta(type):
"""
Metaclass for freezing definition of attributes outside init
"""
def __call__(cls, *args, **kw):
instance = super().__call__(*args, **kw) # < runs __new__ and __init__
instance.__post_init__()
return instance
array_parameter_list = ['coefficients', "surfaceLimits", "low_Zernike", "detrending", "fractal_frequency_x",
"fractal_exponent_x", "fractal_frequency_y", "fractal_exponent_y", "sampling",
"error_limits"]
class ChainList(list):
"""
Class inheriting list allowing clear and concise text prints of beamlines
"""
def __repr__(self):
ret_str = ''
for oe in self:
ret_str += f"{oe.name} -> "
ret_str += "\n"
return ret_str[:-4]
class Point(object):
def __init__(self, x=None, y=None, z=None):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f"\t{self.x}\n\t{self.y}\n\t{self.z}"
def get_spherical_coord(self):
r = np.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
theta = arccos(self.z / r)
if self.y >= 0:
phi = arccos(self.x / np.sqrt(self.x ** 2 + self.y ** 2))
else:
phi = 2 * pi - arccos(self.x / np.sqrt(self.x ** 2 + self.y ** 2))
return r, theta, phi
def __add__(self, point2):
return Point(self.x + point2.x, self.y + point2.y, self.z + point2.z)
def __sub__(self, point2):
return Point(self.x - point2.x, self.y - point2.y, self.z - point2.z)
def get_coord_horiba(self):
r, theta, phi = self.get_spherical_coord()
return r, theta / degree, phi / degree
def get_coord_solemio(self, point1=None):
r, theta, phi = self.get_spherical_coord()
if point1:
r1, theta1, phi1 = point1.get_spherical_coord()
return 1 / r, cos(pi / 2 - theta) - cos(pi / 2 - theta1), phi
else:
return 1 / r, cos(pi / 2 - theta), phi
def get_coord_pyoptix(self):
r, theta, phi = self.get_spherical_coord()
return 1 / r, pi / 2 - theta, phi
class SphericalPoint(Point):
def __init__(self, r, elevation, azimuth):
super().__init__()
# from convention elevation is 90-\theta and azimuth is \phi
self.x = np.longdouble(r * cos(azimuth) * sin(90 * degree - elevation))
self.y = np.longdouble(r * sin(azimuth) * sin(90 * degree - elevation))
self.z = np.longdouble(r * cos(90 * degree - elevation))
class BeamlineChainDict(dict):
"""
Class inheriting from dict for holding and representing all possible optical elements chains in a beamline.
Allows for convenient commutations between chains.
"""
def __setitem__(self, key, value):
assert isinstance(value, list)
super(BeamlineChainDict, self).__setitem__(key, ChainList(value))
def __repr__(self):
ret_str = ""
for key in self.keys():
ret_str += f"Chaîne {key}:\n\t"
chain = self.__getitem__(key)
ret_str += chain.__repr__() + "\n"
return ret_str
class Beamline(object):
"""
Class for describing a beamline in optix
"""
def __init__(self, name="Beamline"):
"""
Constructor of the class Beamline which holds the name of the beamline and all configurations of it called
chains.
:param name: Name of the beamline
:type name: str
"""
super().__init__()
self._elements = []
self._chains = BeamlineChainDict({})
self._active_chain = None
self.active_chain_name = None
self.name = name
self.optical_distances = None
self.align_steps = lambda lambda_align, lambda_radiate: None
self.n_generated_rays = 0
def save_configuration(self, filename=None):
"""
Saves all the parameters of a beamline active chain and returns them as a list of dictionaries.
If filename is supplied, saves the configuration object returned in a file using pickle
:param filename: name of the file where to save configuration, default: None
:type filename: str
:return: list of parameters as dict
:rtype: list of dict
"""
config = []
for oe in self.active_chain:
config.append(oe.dump_properties(verbose=0))
if filename is not None:
with open(filename, "wb") as filout:
pickle.dump(config, filout)
return config
def load_configuration(self, configuration=None, filename=None):
"""
Loads all the parameters of a beamline active chain as a list of dictionaries.
If filename is supplied, loads the configuration object from pickle file and ignores configuration param.
:param configuration: list of dictionnaries containing the parameters of the optical element. See output
of save_configuration for more details.
:type configuration: list of dict
:param filename: name of the file from which to load configuration, default: None
:type filename: str
:return: None
:rtype: Nonetype
"""
if filename is not None:
with open(filename, "rb") as filin:
configuration = pickle.load(filin)
for oe in self.active_chain:
for description in configuration:
if oe.name == description["oe_name"]:
params = description["oe_params"]
for param in params:
oe._set_parameter(param, params[param])
def save_beamline(self, filename=None):
if filename:
save_as_xml(filename)
def load_beamline(self, filename=None):
if filename:
load_from_xml(filename)
@property
def chains(self):
"""
:return: all the beamline chains as BeamlineChainDict
"""
return self._chains
@property
def active_chain(self):
"""
:return: the chain along which rays will be propagated
"""
return self._active_chain
@active_chain.setter
def active_chain(self, chain_name):
"""
Sets the chain whose key is `chain_name` as the active chain and links all optical elements accordingly.
:param chain_name: name of the chain to become active
:type chain_name: str
:return: None
"""
assert chain_name in self._chains
self.active_chain_name = chain_name
self.optical_distances = None
self._active_chain = self.chains[chain_name]
for i, oe in enumerate(self._active_chain):
oe.beamline = self
try:
oe.next = self._active_chain[i + 1]
except IndexError:
pass
if i:
oe.previous = self._active_chain[i - 1]
self._active_chain[-1].next = None
ret_str = f"Chaîne {chain_name}:\n\t"
ret_str += self._active_chain.__repr__()
print(ret_str)
def align(self, lambda_align, lambda_radiate=None, from_element=None, export=None, **kwargs):
"""
Computes the absolute positions of the optics using the optics parameters. To be called before radiate.
:param lambda_align: Wavelength to be used for coordinate calculations in m. Can be different from actual
radiated wavelength
:type lambda_align: float
:param lambda_radiate: Wavelength to be used for setting source in m. Can be different from
alignment wavelength
:type lambda_align: float
:param from_element: Source element from which to compute the coordinates. Default is first element of
active_chain
:type from_element: OpticalElement or inherited
:param kwargs: Keyword arguments passed to beamline.align_steps
:type kwargs: Keyword arguments
:return: code result from relative optix function
"""
if lambda_radiate is None:
lambda_radiate = lambda_align
self.get_distance_between_oe(None, None)
try:
self.align_steps(lambda_align, lambda_radiate, **kwargs)
except AttributeError:
raise AttributeError("Beamline's method align_steps must have two positional arguments which are the "
"wavelength of alignment and radiation and can have as many keyword argument as "
"needed.")
if from_element is not None:
ret = align(from_element.element_id, lambda_align)
else:
ret = align(self.active_chain[0].element_id, lambda_align)
if export is not None:
align_dict = dict()
for oe in self.active_chain:
loc_fr = oe.get_local_frame()
align_dict[oe.name, "center"] = loc_fr["Center_soleil"]
align_dict[oe.name, "normal_vector"] = loc_fr["Z_soleil"]
align_df = pd.DataFrame(align_dict.values(), index=align_dict.keys(), columns=["S", "X", "Z"])
align_df.to_csv(export)
return ret
def get_distance_between_oe(self, oe1, oe2):
"""
Returns the optical distance traveled by the chief ray between oe1 and oe2 if oe1 and oe2 are not None.
:param oe1: First optical element
:type oe1: pyoptix.OpticalElement instance or inherited class
:param oe2: Second optical element
:type oe2: pyoptix.OpticalElement instance or inherited class
:return: None if oe1 or oe2 is None, distance between oe1 and oe2 otherwise.
:rtype: float
"""
totdist = 0
self.optical_distances = {}
for oe in self.active_chain:
totdist += oe.distance_from_previous
self.optical_distances[oe.name] = totdist
if oe1 is None:
return
if oe2 is None:
return
try:
assert oe1 in self.active_chain
assert oe2 in self.active_chain
except AssertionError:
raise AssertionError(f"Both {oe1.name} ({oe1 in self.active_chain}) and "
f"{oe2.name} ({oe2 in self.active_chain}) must be in active chain or be None")
return self.optical_distances[oe1.name] - self.optical_distances[oe2.name]
def clear_impacts(self, clear_source=False):
"""
Removes any impact on the spot diagrams computed on all element following the source object at the exception
of the source itself, as it needs its impact to repropagate rays from the previous distribution.
:param clear_source: also clears the source
:type clear_source: bool
:return: code result from the optix function
"""
from_element = 1
if clear_source:
from_element = 0
self.n_generated_rays = 0
return clear_impacts(self.active_chain[from_element].element_id)
def radiate(self, from_element=None):
"""
Propagates rays from a source element.
:param from_element: Source element from which to propagate rays
:type from_element: Source element or inherited
:return:
"""
if from_element is not None:
return radiate(from_element.element_id)
else:
return radiate(self.active_chain[0].element_id)
def generate(self, lambda_radiate, polarization=None):
"""
Generates rays at `lambda_radiate` wavelength.
:param lambda_radiate: Wavelength of the rays in m
:param polarization: Polarization of the generated rays which can be 'S', 'P', 'R' (circular right),
'L'(circular left)
:return:
"""
if polarization:
n_generated_rays = generate_polarized(self.active_chain[0].element_id, lambda_radiate, polarization)
else:
n_generated_rays = generate(self.active_chain[0].element_id, lambda_radiate)
self.n_generated_rays += n_generated_rays
def _add_element(self, new_element):
if new_element not in self._elements:
self._elements.append(new_element)
def show_active_chain_orientation(self):
"""
Prints the optical element in the active chain with the orientation of their local vertical axis.
For example :
- a vertical deflecting mirror with a reflective surface pointed up (deflection towards +Z) will
appear will an "up" arrow,
- a screen should appear with an "up" arrow, meaning that its "y" axis is vertical and pointed upwards,
- an horizontal deflecting mirror with a reflective surface on the left side (deflection towards +X) will
appear with a "left" arrow.
:return: None
:rtype: Nonetype
"""
phi = 0
arrows = {"up": "\u2191", "left": "\u2190", "right": "\u2192", "down": "\u2193"}
for oe in self.active_chain:
phi += oe.phi
local_phi = (phi + 2 * pi) % (2 * pi)
if local_phi < pi / 4:
arrow = arrows["up"]
elif local_phi < 3 * pi / 4:
arrow = arrows["left"]
elif local_phi < 5 * pi / 4:
arrow = arrows["down"]
elif local_phi < 7 * pi / 4:
arrow = arrows["right"]
else:
arrow = arrows["up"]
print(oe.name, arrow)
def draw_active_chain(self, top_only=False, side_only=False):
"""
Draws a *not to scale* diagram of the beamline top and side views for debug purposes.
:param top_only: If True only draws the beamline viewed from the top
:type top_only: bool
:param side_only: If True only draws the beamline viewed from the side
:type side_only: bool
:return: None
"""
def rotate(x, y, theta=0):
xp = x * np.cos(theta) + y * np.sin(theta)
yp = -x * np.sin(theta) + y * np.cos(theta)
return xp, yp
def make_box(oe_type="film", center=(0, 0), angle=0, fig=None, direction="straight", height=10,
color="blue"):
if oe_type == "film":
width = 1
else:
width = 10
direction_offset = 0
if direction == "up":
direction_offset = -height / 2
if direction == "down":
direction_offset = height / 2
x1, x2 = -width / 2, -width / 2
x3, x4 = width / 2, width / 2
y2, y3 = -height / 2 + direction_offset, -height / 2 + direction_offset
y1, y4 = height / 2 + direction_offset, height / 2 + direction_offset
x1, y1 = rotate(x1, y1, angle)
x2, y2 = rotate(x2, y2, angle)
x3, y3 = rotate(x3, y3, angle)
x4, y4 = rotate(x4, y4, angle)
polygon = PolyAnnotation(
fill_color=color,
fill_alpha=0.3,
xs=[x1 + center[0], x2 + center[0], x3 + center[0], x4 + center[0]],
ys=[y1 + center[1], y2 + center[1], y3 + center[1], y4 + center[1]],
)
fig.add_layout(polygon)
print(self.active_chain)
total_phi = 0
total_theta_side = 0
total_theta_top = 0
top_points = [(0, 0)]
side_points = [(0, +50)]
length = 25
p = figure()
for oe in self.active_chain:
total_phi += oe.phi
if oe.theta == 0:
make_box(oe_type="film", center=top_points[-1], angle=-total_theta_top * pi / 180, fig=p,
direction="straight", height=10)
make_box(oe_type="film", center=side_points[-1], angle=-total_theta_side * pi / 180, fig=p,
direction="straight", height=10)
elif abs(abs(total_phi) % pi) < 1e-5:
if abs(total_phi % (2 * pi) - pi) < 1e-5:
make_box(oe_type="mirror", center=side_points[-1], angle=-(total_theta_side - 15) * pi / 180,
fig=p, direction="down", height=10)
total_theta_side -= 30
else:
make_box(oe_type="mirror", center=side_points[-1], angle=-(total_theta_side + 15) * pi / 180,
fig=p, direction="up", height=10)
total_theta_side += 30
make_box(oe_type="mirror", center=top_points[-1], angle=-total_theta_top * pi / 180, fig=p,
direction="straight", height=10)
elif abs(abs(total_phi) % (pi / 2)) < 1e-5:
if abs(total_phi % (pi * 2) - pi / 2) < 1e-5:
make_box(oe_type="mirror", center=top_points[-1], angle=-(total_theta_top + 15) * pi / 180,
fig=p, direction="up", height=10)
total_theta_top += 30
else:
make_box(oe_type="mirror", center=top_points[-1], angle=-(total_theta_top - 15) * pi / 180,
fig=p, direction="down", height=10)
total_theta_top -= 30
make_box(oe_type="mirror", center=side_points[-1], angle=-total_theta_side * pi / 180, fig=p,
direction="straight", height=10)
else:
raise Exception("unable to parse oe", oe.name)
top_points.append((top_points[-1][0] + length,
top_points[-1][1] + length * np.tan(total_theta_top * pi / 180)))
side_points.append((side_points[-1][0] + length,
side_points[-1][1] + length * np.tan(total_theta_side * pi / 180)))
side_points = np.array(side_points)
top_points = np.array(top_points)
source_top = ColumnDataSource(data=dict(X=top_points[:-1, 0],
Y=top_points[:-1, 1],
names=[element.name for element in self.active_chain]))
source_side = ColumnDataSource(data=dict(X=side_points[:-1, 0],
Y=side_points[:-1, 1],
names=[element.name for element in self.active_chain]))
if not side_only:
p.line(top_points[:-1, 0], top_points[:-1, 1], color="blue", legend_label="top view")
labels_top = LabelSet(x='X', y='Y', text='names', angle=30,
x_offset=0, y_offset=-15, source=source_top) # , render_mode='canvas')
p.add_layout(labels_top)
if not top_only:
p.line(side_points[:-1, 0], side_points[:-1, 1], color="red", legend_label="side view")
labels_side = LabelSet(x='X', y='Y', text='names', angle=-30,
x_offset=0, y_offset=15, source=source_side) # , render_mode='canvas')
p.add_layout(labels_side)
show(p)
def get_resolution(self, mono_slit=None, wavelength=None, orientation="vertical", dlambda_over_lambda=1 / 5000,
show_spd=False, verbose=0, nrays=5000, criterion="fwhm", return_all=False, distance_from_slit=0,
**kwargs):
"""
Computes the resolution of a beamline in its `mono_slit` plane at a given `wavelength`. An a priori resolution
must be given as `dlambda_over_lambda` for calculation purposes and the orientation of deviation relative
to the slit plane must also be given. THe computation is as follows : two lambdas are genreated and propagated,
their distance in the slit plane is computed and their width (either 2.35*rms or fwhm from histogram
depending on parameter criterion).
Resolution is then the lambda/dlambda such as the two spots don't overlap.
:param distance_from_slit: offset along incoming beam at which to measure resolution from mono_slit position
:type distance_from_slit: float
:param criterion: Criterion for resolution computation either rms or fwhm.
:type criterion: str
:param mono_slit: Slit plane
:type mono_slit: pyoptix.OpticalElement
:param wavelength: wavelength at which to compute resolution
:type wavelength: float
:param orientation: Orientation of the grating deviation "vertical" or "horizontal"
:type orientation: str
:param dlambda_over_lambda: estimation of inverse of resolution
:type dlambda_over_lambda: float
:param show_spd: If True displays the calculated spots and the Y projection of spot at wavelength.
Default: False
:type show_spd: bool
:param verbose: If > 0, prints details of the resolution calculations. Default: 0
:type verbose: int
:param nrays: Number of rays per spot to be propagated in order to compute the resolution. Default: 5000
:type nrays: int
:param return_all: If True returns a dictionary containing spot size according to criterion, dispersion (defined
as the distance between spots at lambda and at lambda+dlambda in µm), lambda (in m),
dlambda, if False returns the resolution in lambda/dlambda
:return: Resolution in lambda/dlambda of dict (see return_all)
:rtype: float
"""
if mono_slit.get_aperture_activity():
print("Warning apertures are active and results might be inconsistent")
self.clear_impacts(clear_source=True)
stored_nrays = self.active_chain[0].nrays
slit_next_OE = mono_slit.next
mono_slit.next = None
self.active_chain[0].nrays = nrays
self.align(wavelength, wavelength, verbose=verbose, **kwargs)
self.generate(wavelength)
self.generate(wavelength + wavelength * dlambda_over_lambda)
self.radiate()
if orientation == "vertical":
dim = "Y"
elif orientation == "horizontal":
dim = "X"
else:
raise AttributeError("Unknown orientation")
spd = mono_slit.get_diagram(distance_from_slit)
spd = spd[spd["Intensity"] != 0]
if show_spd:
print(spd)
mono_slit.show_diagram(distance_from_slit)
projection = np.array(spd.where(spd["Lambda"] == wavelength).dropna()[dim])
projection_dl = np.array(
spd.where(spd["Lambda"] == (wavelength + wavelength * dlambda_over_lambda)).dropna()[dim])
if criterion == "fwhm":
# vhist, vedges = np.histogram(spd.where(spd["Lambda"] == wavelength).dropna()[dim], bins=100)
# peaks, _ = find_peaks(vhist, height=vhist.max())
# res_half = peak_widths(vhist, peaks, rel_height=0.5)
# mono_chr_fwhm = (res_half[0] * (vedges[1] - vedges[0]))[0]
mono_chr_fwhm = general_FWHM(spd.where(spd["Lambda"] == wavelength).dropna()[dim])
else:
mono_chr_fwhm = np.array(spd.where(spd["Lambda"] == wavelength).dropna()[dim]).std()
if show_spd and criterion == "fwhm":
import matplotlib.pyplot as plt
vhist, vedges = np.histogram(spd.where(spd["Lambda"] == wavelength).dropna()[dim], bins="auto")
plt.plot(vedges[:-1], vhist)
# plt.plot(vedges[1:], vhist)
# plt.plot(vedges[peaks], vhist[peaks], "x")
# h, left, right = res_half[1:]
# widths = (h, vedges[int(left[0])], vedges[int(right[0])])
# plt.hlines(*widths, color="C2")
plt.show()
distance = abs(np.mean(projection) - np.mean(projection_dl))
resolution = (1 / dlambda_over_lambda) * distance / mono_chr_fwhm
if verbose:
if verbose > 1:
print(f"FWHM monochromatique : {mono_chr_fwhm * 1e6:.2f} µm")
print(f"dispersion dans le plan (m) : {distance * 1e6:.2f} µm")
print(f"Lambda = {wavelength * 1e9:.5f} nm")
print("lambda_over_dlambda for calculation :", 1 / dlambda_over_lambda)
print("calculated resolution :", resolution)
else:
print(f"FWHM @ {1239.842e-9 / wavelength:.2f} eV : {mono_chr_fwhm * 1e6:.2f} µm, dispersion :"
f"{distance * 1e6:.2f} µm, resolution : {resolution}")
self.active_chain[0].nrays = stored_nrays
mono_slit.next = slit_next_OE
if return_all:
return {criterion: mono_chr_fwhm * 1e6, "dispersion_on_screen": distance * 1e6, "wavelength": wavelength,
"dlambda": wavelength * dlambda_over_lambda}
else:
return resolution
def draw_to_scale(self, wavelength=300e-9, radiate=False, configurations=[], plot3D=False, beamline_walls=None,
orthonorm=False, **kwargs):
"""
Generate and plot the beamline spot diagram to scale for each recording optical element
for the specified wavelength(s) and configurations.
Parameters
----------
orthonorm : bool
If True, the drawing will be done with othonormal axes
wavelength : float or list of floats, optional
Wavelength(s) for which to generate the beamline diagram (default is 300e-9). If list, length must match
the number of configuration.
radiate : bool, optional
If True, radiate the beamline for each configuration (default is False).
Set to True if multiple configurations are provided
configurations : list of str, optional
Configurations to be plotted (default is []). If [], the current configuration of the beamline is used
plot3D : bool
If True, the spots are plotted in 3 dimensions. Beware if the beamline is long,
the plot is hard to navigate
beamline_walls : numpy.array
Array of (X,S) pair of coordinates representing the physical beamline corners that gets plotted in the top
view diagram
kwargs : keyword arguments, optional
Keyword arguments passed to beamline align_steps method
Returns
-------
pandas DataFrame
DataFrame containing the recorded impact data for the plotted configurations
Notes
-----
- If configurations is provided, the beamline will be modified and radiated, regardless of the radiate flag.
- If radiate is True or multiple configurations are specified, a warning will be printed.
- If wavelength is a list, it must have the same length as configurations.
- The beamline diagram is generated to scale for the specified wavelength and configurations.
- The recorded impact data for each configuration is collected and returned as a DataFrame.
- The X-coordinate values in the impact data are flipped (multiplied by -1) to match the plotting convention.
- The beamline diagram is plotted using the plot_beamline function.
- The PyOptix reference frame (X,Y,Z) translates in the SOLEIL frame as (-X, Z, S)
"""
if configurations:
radiate = True
else:
configurations = [self.active_chain_name]
if radiate:
print("WARNING : for radiate = True or multiple configurations, beamline will be modified after plot")
if isinstance(wavelength, list):
assert len(wavelength) == len(configurations)
else:
wavelength = [wavelength] * len(configurations)
diags = []
for config, lamda in zip(configurations, wavelength):
if radiate:
self.active_chain = config
for oe in self.active_chain:
oe.recording_mode = RecordingMode.recording_output
self.clear_impacts(clear_source=True)
self.align(lamda, lamda, **kwargs)
self.generate(lamda)
self.radiate()
for oe in self.active_chain:
if oe.recording_mode != RecordingMode.recording_none:
impacts = oe.get_impacts(reference_frame="general_frame")
center = oe.get_local_frame()["Center_pyoptix"]
impacts["name"] = oe.name
impacts["center_x"] = -center[0]
impacts["center_z"] = center[1]
impacts["center_s"] = center[2]
impacts["configuration"] = config
impacts["X"] *= -1
diags.append(impacts)
spots = pd.concat(diags)
plot_beamline(spots, plot_3D=plot3D, beamline_walls=beamline_walls, orthonorm=orthonorm)
return spots
class OpticalElement(metaclass=PostInitMeta):
"""
Base class for all pyoptix optical element
"""
_frozen = False
def __init__(self, name="", phi=0, psi=0, theta=0, d_phi=0, d_psi=0, d_theta=0,
d_x=0, d_y=0, d_z=0, next_element=None, previous=None, distance_from_previous=0, element_id=None,
element_type="", beamline=None):
"""
Constructor for all optical elements. Parameters can be set in constructor or at a later time.
Underlying OpticalElement parameters are complex c structure for optimization ond different magic handling.
See class Parameter docstring.
Two methods of setting parameters are provided: implicit and explicit. Implicit method
`OpticalElement.parameter = value` only sets the value of the parameter without changing any other field.
Explicit method `OpticalElement.parameter = {"key":value,...}` sets any parameter field without changing those
not in the provided dictionary keys.
Positioning referential of OpticalElement is linked to its surface : Y is normal to the surface,
X is along it width, Z along its length. For optical elements in normal incidence such as films usually, this
convention makes Y vertical in absence of phi modifier. Warning : referentials are inherited from an element
to the next. A horizontally deflecting mirror should have phi=pi/2, but the next mirror if deflecting
horizontally towards the other side should have phi=pi. See provided examples and use method
Beamline.draw_active_chain profusely.
If parameter `element_id` is set to an preexisting pyoptix object, all parameters will be imported from
pyoptix
:param name: Name of the OpticalElement as will be stored in optix and displayed by Beamline
:type name: str (32 char long max)
:param phi: Angle of rotation around Y (rad) (roll)
:type phi: float
:param psi: Angle of rotation around Z (rad) (yaw)
:type psi: float
:param theta: Angle of rotation around X (rad) (incidence or pitch)
:type theta: float
:param d_phi: Misalignment of angle of rotation around Y (rad) (roll), not transferred to the next element
:type d_phi: float
:param d_psi: Misalignment of angle of rotation around Z (rad) (yaw), not transferred to the next element
:type d_psi: float
:param d_theta: Misalignment of angle of rotation around X (rad) (pitch), not transferred to the next element
:type d_theta: float
:param d_x: Misalignment of the position along X (not transferred to the next element) in m
:type d_x: float
:param d_y: Misalignment of the position along Y (not transferred to the next element) in m
:type d_y: float
:param d_z: Misalignment of the position along Z (not transferred to the next element) in m
:type d_z: float
:param next_element: Next element in the active chain
:type next_element: OpticalElement or inherited
:param previous: Previous element in the chain
:type previous: OpticalElement or inherited
:param distance_from_previous: distance from the previous optical element in m
:type distance_from_previous: float
:param element_id: Handle of underlying optix object if object already exists
:type element_id: wintypes.INT
:param element_type: class of the OpticalElement (if unsure of which to chose, use an inherited class)
:type element_type: str
:param beamline: Beamline of the element
:type beamline: pyoptix.Beamline
"""
super().__init__()
self._surface_error_dims = None
self._recording_mode = RecordingMode.recording_none
self._element_id = find_element_id(name)
self._element_type = element_type
if element_id is not None:
self.from_element_id(element_id)
self._element_id = element_id
elif self._element_id is not None: # the element already exists
pass
elif element_type != "" and name != "":
self._element_id = create_element(element_type, name)
self._name = name
else:
raise AttributeError("please provide either element_type and name or element_id")
self._name = name
self.phi = phi
self.psi = psi
self.theta = theta
self.d_phi = d_phi
self.d_psi = d_psi
self.d_theta = d_theta
self.d_x = d_x
self.d_y = d_y
self.d_z = d_z
self.next = next_element
self.previous = previous
self.distance_from_previous = distance_from_previous
self.beamline = beamline
self.set_error_generator(True) # needed temporarily to create the attributes
self.error_limits = [[-1, 1], [-1, 1]]
self.sampling = [0.1, 0.1]
self.low_Zernike = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
self.fractal_exponent_x = [-1, -1]
self.fractal_exponent_y = [-1, -1]
self.fractal_frequency_x = [500, ]
self.fractal_frequency_y = [500, ]
self.residual_sigma = 0
self.detrending = [[1, 1, 1], [1, 1, 0], [1, 0, 0]]
self.set_error_generator(False)
def __setattr__(self, name, value): # enable the frozen decorator for child classes
if not self._frozen or hasattr(self, name):
super().__setattr__(name, value)
else:
raise AttributeError(f"Forbidden attempt to define new attribute {name} of a frozen object")
def __post_init__(self):
self._frozen = True
def get_whole_parameter(self, param_name):
param = Parameter()
inv_dict_optix = {v: k for k, v in optix_dictionnary.items()}
if param_name in inv_dict_optix:
param_name = inv_dict_optix[param_name]
get_parameter(self._element_id, param_name, param)
# return {"value": param.value, "bounds": (param.bounds.min, param.bounds.max),
# "multiplier": param.multiplier, "type": param.type, "group": param.group, "flags": param.flags}
return {"value": param.value, "bounds": (param.bounds.min, param.bounds.max),
"multiplier": param.multiplier, "type": param.type, "group": param.group, "flags": param.flags}
def _get_parameter(self, param_name):
param = self._get_c_parameter(param_name)
if param.flags & 0x8:
return param.array
else:
return param.value
def _get_c_parameter(self, param_name):
param = Parameter()
flags = c_uint32()
get_parameter_flags(self.element_id, param_name, flags)
if flags.value & 0x8:
# the paracmeter contains an array
dims = (c_int64 * 2)()
if get_array_parameter_dims(self.element_id, param_name, dims) != 0:
param.array = np.empty([dims[1], dims[0]])
get_array_parameter(self.element_id, param_name, param, dims[0] * dims[1])
else:
# release the array data and unset flags array bit, if needed
param.flags &= ~(1 << 3)
get_parameter(self.element_id, param_name, param)
return param
def _set_parameter(self, param_name, value):
if param_name in optix_dictionnary:
pyoptix_param_name = optix_dictionnary[param_name]
else:
pyoptix_param_name = param_name
param = self._get_c_parameter(param_name)
# if isinstance(value, np.ndarray): # TODO : maybe remove this section if not needed anymore
# if value.ndim == 1 and value.shape[0] == 1:
# value = value[0]
if isinstance(value, dict): # value is a dictionnary
for key in value:
assert key in ("value", "bounds", "multiplier", "type", "group", "flags")
if key == "value":
param.value = DOUBLE(value[key])
elif key == "multiplier":
param.multiplier = DOUBLE(value[key])
elif key == "type":
param.type = INT(value[key])
elif key == "group":
param.group = INT(value[key])
elif key == "flags":
param.flags = c_ulong(value[key])
else:
bounds = Bounds()
bounds.min = DOUBLE(value[key][0])
bounds.max = DOUBLE(value[key][1])
param.bounds = bounds
set_parameter(self._element_id, param_name, param)
elif isinstance(value, (np.ndarray, list)): # value is an array
value = np.array(value)
assert param_name in array_parameter_list, (f"{param_name} is not an array attribute of {self.name}, "
f"array attributes are {array_parameter_list}")
param.array = value
elif isinstance(value, (float, int)): # value is a float
try:
value = float(value)
param.value = DOUBLE(value)
except TypeError:
raise AttributeError(
"value of parameter must be castable in a float, an numpy.ndarray or a dictionnary")
else:
raise AttributeError(f"value of parameter must be castable in a float, an numpy.ndarray or a dictionnary"
f" type found {type(value)}")
if param_name in array_parameter_list:
# print(f"Setting in _set_parameter {param_name} with {param} ")
pass
set_parameter(self._element_id, param_name, param)
if "lineDensityCoeff_" in pyoptix_param_name: # cas particulier des classes filles de Poly1D
deg = int(pyoptix_param_name.split("_")[-1])
max_deg = max(len(self._line_density_coeffs), deg)
if max_deg > self.degree:
self.degree = max_deg
get_parameter(self._element_id, param_name, param)
else:
self.__getattribute__(pyoptix_param_name) # update of internal variable
updated_parameter = self._get_c_parameter(param_name)
if updated_parameter.flags & (1 << 3): # parameter is an array parameter
# print(f"updated {param_name}:\n", updated_parameter)
return updated_parameter.array
else:
return updated_parameter.value
@property
def element_id(self):
return self._element_id
@property
def name(self):
element_name = create_string_buffer(32)
get_element_name(self._element_id, element_name)
self._name = element_name.value.decode()
return self._name
@property
def phi(self):
self._phi = self._get_parameter("phi")
return self._phi
@phi.setter
def phi(self, value):
self._phi = self._set_parameter("phi", value)
@property
def psi(self):
self._psi = self._get_parameter("psi")
return self._psi
@psi.setter
def psi(self, value):
self._psi = self._set_parameter("psi", value)
@property
def theta(self):
self._theta = self._get_parameter("theta")
return self._theta
@theta.setter
def theta(self, value):
self._theta = self._set_parameter("theta", value)
@property
def d_phi(self):
self._d_phi = self._get_parameter("Dphi")
return self._d_phi
@d_phi.setter
def d_phi(self, value):
self._d_phi = self._set_parameter("Dphi", value)