-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdscan.py
1524 lines (1335 loc) · 50.2 KB
/
dscan.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
from __future__ import annotations
import copy
import dataclasses
import logging
import pathlib
import time
from collections import deque
from typing import (
Any,
Dict,
Generator,
List,
Optional,
Protocol,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
import matplotlib.pyplot as plt
import numpy as np
import pypret
import pypret.frequencies
import scipy.interpolate
from matplotlib.ticker import EngFormatter
from scipy.ndimage import gaussian_filter
from . import devices, motion, plotting
from .options import Material, NonlinearProcess, PulseAnalysisMethod, RetrieverSolver
from .plotting import RetrievalResultPlot
from .utils import RetrievalResultStandin, get_pulse_spectrum, preprocess
logger = logging.getLogger(__name__)
def _default_ndarray():
"""Helper for optional ndarray values in dataclass fields."""
return np.zeros(0)
def get_fundamental_spectrum(
wavelengths: np.ndarray,
intensities: np.ndarray,
range_low: float,
range_high: float,
) -> np.ndarray:
"""
Column-stack the wavelengths/intensities for the fundamental spectrum.
Parameters
----------
wavelengths : np.ndarray
Fundamental wavelengths.
intensities : np.ndarray
Fundamental intensities.
range_low : float
Wavelength lower limit.
range_high : float
Wavelength upper limit.
Returns
-------
np.ndarray
Column-stacked wavelengths/intensities with the range applied.
"""
assert wavelengths.shape == intensities.shape
wavelength_fund = wavelengths[
(wavelengths > range_low) & (wavelengths < range_high)
]
intensities_fund = intensities[
(wavelengths > range_low) & (wavelengths < range_high)
]
return np.column_stack((wavelength_fund, intensities_fund))
@dataclasses.dataclass
class SpectrumData:
wavelengths: np.ndarray = dataclasses.field(default_factory=_default_ndarray)
intensities: np.ndarray = dataclasses.field(default_factory=_default_ndarray)
def _get_pulse(self, ft: pypret.FourierTransform) -> Tuple[pypret.Pulse, float]:
"""
Get a pypret.Pulse instance for this SpectrumData.
Parameters
----------
ft : pypret.FourierTransform
The fourier transform used for the retrieval process, based on the
scan data.
Returns
-------
pypret.Pulse
The pulse instance.
float
The fourier transform limit.
"""
pulse = pypret.Pulse(ft, self.raw_center)
_, fund_intensities_bkg_sub = self.subtract_background()
pulse.spectrum = get_pulse_spectrum(
wavelength=self.wavelengths,
spectrum=fund_intensities_bkg_sub,
pulse=pulse,
)
fourier_transform_limit = pulse.fwhm(dt=pulse.dt / 100)
logger.info(
f"Fourier Transform Limit (FTL): {fourier_transform_limit * 1e15:.1f} fs"
)
return pulse, fourier_transform_limit
@property
def raw_center(self) -> float:
"""Wavelength raw center."""
return sum(np.multiply(self.wavelengths, self.intensities)) / sum(
self.intensities
)
# wavelength_raw_center = self.wavelength_fund * 1E-9
def truncate_wavelength(
self, range_low: float, range_high: float
) -> Tuple[np.ndarray, np.ndarray]:
"""Truncating wavelength given the provided range."""
idx = (self.wavelengths > range_low) & (self.wavelengths < range_high)
return self.wavelengths[idx].copy(), self.intensities[idx].copy()
@classmethod
def from_device(cls, device: devices.Spectrometer) -> SpectrumData:
"""
Acquire spectra from the given device.
Parameters
----------
device : Spectrometer
Spectrometer device instance
Returns
-------
SpectrumData
The acquired data
"""
wavelengths = np.trim_zeros(
cast(Sequence[float], device.wavelengths.get()), "b"
)
intensities = np.array(
cast(Sequence[float], device.spectrum.get())[: len(wavelengths)]
)
return cls(
wavelengths=convert_to_meters(
wavelengths, getattr(device, "wavelength_units", "nm")
),
intensities=intensities,
)
def get_background(self, *, count: int = 15) -> Tuple[np.ndarray, np.ndarray]:
"""
Get the background, based on the first and last ``count`` items.
Parameters
----------
count : int, optional
The size of the slice.
Returns
-------
np.ndarray
Wavelength background
np.ndarray
Intensity background
"""
wavelength_bkg = np.hstack(
(self.wavelengths[:count], self.wavelengths[-count:])
)
intensities_bkg = np.hstack(
(self.intensities[:count], self.intensities[-count:])
)
return wavelength_bkg, intensities_bkg
def subtract_background(self, *, count: int = 15, threshold: float = 0.0025):
"""
Subtract the background from both
Parameters
----------
count : int, optional
The size of the slice to be used for background subtraction.
threshold : float, optional
Normalized intensities under ``threshold`` are zeroed.
Returns
-------
np.ndarray
Background-subtracted wavelengths based on a 1D polyfit
of wavelength/intensity background.
np.ndarray
Background-subtracted and normalized intensity. Intensities under
``threshold`` are zeroed.
"""
wavelength_bkg, intensities_bkg = self.get_background(count=count)
fit = np.polyfit(wavelength_bkg, intensities_bkg, 1)
wavelength_fit = self.wavelengths * fit[0] + fit[1]
intensities = self.intensities - wavelength_fit
intensities /= np.max(intensities)
intensities[intensities < threshold] = 0
return wavelength_fit, intensities
def plot(self, pulse: Optional[pypret.Pulse] = None):
"""
Plot the spectrum data.
Parameters
----------
pulse : pypret.Pulse or None, optional
Pulse, if available, to show FTL.
Returns
-------
matplotlib.pyplot.Figure
The plot figure.
matplotlib.pyplot.Axis
The plot axis.
"""
fig, ax = plt.subplots()
ax = cast(plt.Axes, ax)
wavelength_bkg, intensities_bkg = self.get_background(count=15)
intensities_bkg_fit, _ = self.subtract_background(count=15)
ax.plot(self.wavelengths * 1e9, self.intensities, "k", label="All data")
ax.plot(
wavelength_bkg * 1e9,
intensities_bkg,
"xb",
label="Points for fit",
)
ax.plot(
self.wavelengths * 1e9,
intensities_bkg_fit,
"r",
label="Background fit",
)
plt.legend()
ax.set_xlabel("Wavelength (nm)")
ax.set_ylabel("Counts (arb.)")
if pulse is not None:
ftl = pulse.fwhm(dt=pulse.dt / 100)
ax.set_title(f"Fundamental Spectrum (FTL) = {ftl * 1e15:.1f} fs")
return fig, ax
@dataclasses.dataclass
class ScanData:
#: Scan positions
positions: np.ndarray = dataclasses.field(default_factory=_default_ndarray)
#: Wavelengths
wavelengths: np.ndarray = dataclasses.field(default_factory=_default_ndarray)
#: Normalized intensities
intensities: np.ndarray = dataclasses.field(default_factory=_default_ndarray)
def subtract_background_for_all_positions(self, count: int = 15) -> None:
"""
Clean scan by subtracting linear background for each stage position.
Works in-place.
"""
wavelength_bkg = np.hstack(
(self.wavelengths[:count], self.wavelengths[-count:])
)
for i in range(len(self.positions)):
intensities_bkg = np.hstack(
(self.intensities[i, :count], self.intensities[i, -count:])
)
fit = np.polyfit(wavelength_bkg, intensities_bkg, 1)
self.intensities[i, :] -= self.wavelengths * fit[0] + fit[1]
def truncate_wavelength(
self, range_low: float, range_high: float
) -> Tuple[np.ndarray, np.ndarray]:
"""Truncating wavelength given the provided range."""
idx = (self.wavelengths > range_low) & (self.wavelengths < range_high)
return self.wavelengths[idx].copy(), self.intensities[:, idx].copy()
@classmethod
def from_multiple_scans(
cls,
scan_points: int,
num_average_scans: int,
positions: np.ndarray,
wavelengths: np.ndarray,
intensities: np.ndarray,
) -> ScanData:
"""Average the results from multiple scans into one."""
while (
num_average_scans > 1 and len(positions) < scan_points * num_average_scans
):
# If the scan was stopped early, average what we do have
num_average_scans -= 1
count = num_average_scans * scan_points
positions = positions[:count]
intensities = intensities[:count]
if num_average_scans == 0 or len(positions) < scan_points:
# Return whatever we have - it's not even one scan's worth
return ScanData(
positions=positions,
wavelengths=wavelengths,
intensities=intensities,
)
try:
positions = positions.reshape((num_average_scans, scan_points))
intensities = intensities.reshape(
(num_average_scans, scan_points, intensities.shape[-1])
)
except ValueError as ex:
raise RuntimeError(
f"Unable to reshape the acquired data: "
f"pos={positions.shape} intensity={intensities.shape} "
f"but expected points={scan_points} (averaged over "
f"{num_average_scans})"
) from ex
positions = np.average(positions, axis=0)
intensities = np.average(intensities, axis=0)
# Sanity check - can remove
if len(positions) != scan_points or len(intensities) != scan_points:
raise RuntimeError(
f"Reshaping the averaged scans didn't work as expected: "
f"Reshaped into pos={positions.shape} intensity={intensities.shape} "
f"but expected points={scan_points} (averaged over "
f"{num_average_scans})"
)
return ScanData(
positions=positions,
intensities=intensities,
wavelengths=wavelengths,
)
@dataclasses.dataclass
class Acquisition:
fundamental: SpectrumData = dataclasses.field(default_factory=SpectrumData)
scan: ScanData = dataclasses.field(default_factory=ScanData)
settings: Dict[str, Any] = dataclasses.field(default_factory=dict)
@classmethod
def from_path(cls, path: Union[pathlib.Path, str]) -> Acquisition:
"""
Load fundamental spectrum and scan data from a path.
Parameters
----------
path : str
Path to the numpy npz file.
Returns
-------
Acquisition
The data from the scan.
"""
path = pathlib.Path(path)
loaded = np.load(path, allow_pickle=True)
try:
settings = loaded["settings"][()]
except Exception:
settings = {}
logger.exception("Failed to unpickle settings from the file")
return cls(
fundamental=SpectrumData(
wavelengths=loaded["fund_wavelengths"],
intensities=loaded["fund_intensities"],
),
scan=ScanData(
positions=loaded["positions"],
wavelengths=loaded["wavelengths"],
intensities=loaded["intensities"],
),
settings=settings,
)
def save(self, path: Union[pathlib.Path, str], format: str = "npz") -> None:
"""
Save acquisition data to a single numpy 'npz' file.
Parameters
----------
path : str or pathlib.Path
Filename to save to, including the file extension.
format : str, optional
Save to this format. Currently, only 'npz' is supported.
"""
path = pathlib.Path(path)
if format == "npz":
self.settings.pop("fund", None)
self.settings.pop("scan", None)
np.savez_compressed(
str(path),
fund_wavelengths=self.fundamental.wavelengths,
fund_intensities=self.fundamental.intensities,
positions=self.scan.positions,
wavelengths=self.scan.wavelengths,
intensities=self.scan.intensities,
settings=np.array(self.settings, dtype=object),
)
return
raise ValueError(f"Unsupported format {format}")
class Callback(Protocol):
def __call__(self, data: List[np.ndarray]) -> None:
# mu: np.ndarray
# parameter: np.ndarray
# process_w: np.ndarray
# new_spectrum: np.ndarray
...
T = TypeVar("T", np.ndarray, float)
def convert_to_meters(value: T, units: str) -> T:
"""
Convert the provided value to meters.
Parameters
----------
value : float
The starting value with the units specified.
units : str
Units for ``value``.
Returns
-------
float
"""
factor = {
"m": 1.0,
"mm": 1.0e-3,
"um": 1.0e-6,
"nm": 1.0e-9,
}[units]
return cast(T, value * factor)
@dataclasses.dataclass
class ScanPointData:
index: int
setpoint: float
readback: float
wavelengths: List[float]
spectrum: List[float]
@classmethod
def from_devices(
cls,
index: int,
setpoint: float,
stage: devices.Stage,
spectrometer: devices.Spectrometer,
) -> ScanPointData:
spectrum = SpectrumData.from_device(spectrometer)
return ScanPointData(
index=index,
setpoint=convert_to_meters(setpoint, stage.egu),
readback=convert_to_meters(stage.user_readback.get(), stage.egu),
wavelengths=spectrum.wavelengths.tolist(),
spectrum=spectrum.intensities.tolist(),
)
class AcquisitionScan:
stage: devices.Stage
spectrometer: devices.Spectrometer
data: Optional[ScanData]
def __init__(
self,
stage: devices.Stage,
spectrometer: devices.Spectrometer,
):
self.stage = stage
self.spectrometer = spectrometer
self.data = None
self._stop = False
def stop(self):
"""Request to stop the scan."""
self._stop = True
self.stage.stop()
@property
def stopped(self) -> bool:
"""Was the scan interrupted?"""
return self._stop
def run(
self,
positions: List[float],
dwell_time: float,
num_average_scans: int = 1,
per_step_spectra: int = 1,
timeout: float = 30.0,
) -> Generator[ScanPointData, None, None]:
"""
Take a scan using the configured stage and spectrometer.
"""
# bluesky, what's that? *cough*
self._stop = False
def sleep_with_stop_check(period: float) -> None:
t0 = time.monotonic()
sleep_period = min((period / 10.0, 0.1))
while not self._stop and time.monotonic() - t0 < period:
# Busy loop so that we can monitor for user interruption.
time.sleep(sleep_period)
for dev in [self.stage, self.spectrometer]:
try:
dev.wait_for_connection()
except Exception as ex:
logger.exception(f"{dev.name} wait for connection failed")
raise RuntimeError(
f"{dev.name} communication or configuration incorrect; unable to perform "
f"scan. {ex.__class__.__name__} {ex}"
)
if self.stage.egu not in ("m", "mm", "um", "nm"):
raise ValueError(
f"Stage units {self.stage.egu} are not supported; please convert them to "
f"(for example) ``mm`` in the ophyd class"
)
initial_position = self.stage.user_readback.get()
remaining = deque(enumerate(tuple(positions) * num_average_scans))
all_data = []
while remaining and not self._stop:
idx, setpoint = remaining[0]
st = motion.move_with_retries(self.stage, setpoint)
try:
st.wait(timeout=timeout)
except TimeoutError:
logger.warning("Motion timed out; stopping the stage.")
self.stage.stop()
if self._stop:
logger.debug("Stop clicked; exiting the scan")
break
if not st.success:
logger.debug(
"Failed to move into position even after retries. "
"Will continue trying until the user stops us."
)
sleep_with_stop_check(0.1)
continue
data = ScanPointData.from_devices(
index=idx,
setpoint=setpoint,
stage=self.stage,
spectrometer=self.spectrometer,
)
spectra = [data.spectrum]
# Wait for a single dwell period for the motor to settle into its
# final position. (TODO: separate parameter?)
sleep_with_stop_check(dwell_time)
while not self._stop and len(spectra) < per_step_spectra:
spectrum = SpectrumData.from_device(
self.spectrometer
).intensities.tolist()
if spectrum == spectra[-1]:
sleep_with_stop_check(dwell_time)
continue
spectra.append(spectrum)
data.spectrum = np.average(np.asarray(spectra), axis=0).tolist()
if abs(np.sum(data.spectrum)) < 1e-6:
logger.warning(
"Retrying scan point %d (%g); spectra was all zero",
idx,
setpoint,
)
sleep_with_stop_check(0.1)
continue
if all_data and data.spectrum == all_data[-1].spectrum:
logger.warning(
"Retrying scan point %d (%g); spectra identical to previous "
"point",
idx,
setpoint,
)
sleep_with_stop_check(0.1)
continue
all_data.append(data)
remaining.popleft()
yield data
if all_data:
data_positions = np.asarray([data.readback for data in all_data])
wavelengths = np.asarray(all_data[-1].wavelengths)
intensities = np.asarray([data.spectrum for data in all_data])
if num_average_scans > 1:
self.data = ScanData.from_multiple_scans(
len(positions),
num_average_scans,
positions=data_positions,
wavelengths=wavelengths,
intensities=intensities,
)
else:
self.data = ScanData(
positions=data_positions,
wavelengths=wavelengths,
intensities=intensities,
)
self.stage.move(initial_position, wait=False)
@dataclasses.dataclass
class PypretResult:
#: The fundamental spectrum data.
fund: SpectrumData
#: The data acquired when performing the d-scan.
scan: ScanData
#: The material used in the d-scan.
material: Material
#: The pulse analysis method to use
method: PulseAnalysisMethod
#: The non-linear process to use
nlin_process: NonlinearProcess
#: The wedge angle (for traditional d-scan, not grating)
wedge_angle: float = 8.0
#: Strength of Gaussian blur applied to raw data (standard deviations).
blur_sigma: int = 0
#: Number of grid points in frequency and time axes.
num_grid_points: int = 3000
#: Bandwidth around center wavelength for frequency and time axes (nm).
freq_bandwidth_wl: int = 950
#: Maximum number of iterations
max_iter: int = 30
#: Grating stage position for pypret plot OR glass insertion stage position
#: (mm, use None for shortest duration)
plot_position: Optional[float] = None
#: The retriever solver to use. Defaults to "copra".
solver: RetrieverSolver = RetrieverSolver.copra
#: Fundamental spectrum window
spec_fund_range: Tuple[float, float] = (400, 600)
#: Scan spectrum window
spec_scan_range: Tuple[float, float] = (200, 300)
#: The plot instance that can be used to inspect the retrieval result.
plot: Optional[RetrievalResultPlot] = None
#: The result of the retrieval process.
retrieval: RetrievalResultStandin = dataclasses.field(
default_factory=RetrievalResultStandin
)
rms_error: float = 0.0
#: A model of the femtosecond pulses by their envelope
pulse: Optional[pypret.Pulse] = None
#: The raw (not pre-processed) mesh data.
trace_raw: Optional[pypret.MeshData] = None
#: The pre-processed mesh data.
trace: Optional[pypret.MeshData] = None
#: The per-parameter full-width half-max (FWHM).
fwhm: np.ndarray = dataclasses.field(default_factory=_default_ndarray)
#: The per-parameter resulting profile.
result_profile: np.ndarray = dataclasses.field(default_factory=_default_ndarray)
#: The fourier transform limit (FTL) of the pulse.
fourier_transform_limit: float = 0.0
def _get_fourier_transform(self) -> pypret.FourierTransform:
"""
Get the fourier transform helper from pypret.
This is based on:
* freq_bandwidth_wl: Bandwidth around center wavelength for frequency
and time axes (nm)
* fund.raw_center: The fundamental spectrum raw center position
* num_grid_points: the number of grid points in frequency and time
axes.
Returns
-------
pypret.FourierTransform
"""
# Create frequency-time grid
freq_bandwidth = (
self.freq_bandwidth_wl
* 1e-9
* 2
* np.pi
* 2.998e8
/ self.fund.raw_center**2
)
fund_frequency_step = np.round(freq_bandwidth / (self.num_grid_points - 1), 0)
return pypret.FourierTransform(
self.num_grid_points, dw=fund_frequency_step, w0=-freq_bandwidth / 2
)
def _get_mesh_data(self) -> pypret.MeshData:
"""
Get the MeshData instance based on:
* The selected material (and wedge angle)
* The scan positions
* The intensities/wavelengths acquired during the scan
Returns
-------
pypret.MeshData
"""
coef = self.material.get_coefficient(self.wedge_angle)
return pypret.MeshData(
self.scan.intensities,
coef * (self.scan.positions - min(self.scan.positions)),
self.scan.wavelengths,
labels=["Insertion", "Wavelength"],
units=["m", "m"],
)
def plot_mesh_data(
self, data: Optional[pypret.MeshData] = None, scan_padding_nm: int = 0
) -> pypret.MeshDataPlot:
"""
Plot the mesh scan data.
Parameters
----------
data : pypret.MeshData, optional
The mesh data to plot, if available. Re-calculated if not.
scan_padding_nm : int, optional
Padding around the scan range to use.
Returns
-------
pypret.MeshDataPlot
"""
if data is None:
data = self._get_mesh_data()
md = pypret.MeshDataPlot(data, show=False)
ax = cast(plt.Axes, md.ax)
ax.set_title("Cropped scan")
ax.set_xlim(
(self.spec_scan_range[0] + scan_padding_nm) * 1e-9,
(self.spec_scan_range[1] - scan_padding_nm) * 1e-9,
)
return md
def plot_processed_scan(
self, *, fig: Optional[plt.Figure] = None, scan_padding_nm: int = 0
) -> pypret.MeshDataPlot:
"""
Plot the processed mesh scan data from ``self.trace``.
Parameters
----------
scan_padding_nm : int, optional
Padding around the scan range to use.
Returns
-------
pypret.MeshDataPlot
"""
factor = 2 * np.pi * 2.99792 * 1e17
md = pypret.MeshDataPlot(self.trace, show=False)
ax = cast(plt.Axes, md.ax)
ax.set_title("Processed scan")
ax.set_xlabel("Frequency")
ax.set_xlim(
factor / (self.spec_scan_range[1] - scan_padding_nm),
factor / (self.spec_scan_range[0] + scan_padding_nm),
)
return md
@property
def pulse_width_fs(self) -> float:
"""Get the reconstructed pulse width in femtoseconds."""
pulse = self._get_retrieval_pulse()
return pulse.fwhm(dt=pulse.dt / 100) / 1e-15
def _get_retrieval_pulse(self) -> pypret.Pulse:
pulse = pypret.Pulse(self.retrieval.pnps.ft, self.retrieval.pnps.w0, unit="om")
pulse.spectrum = self.retrieval.pulse_retrieved * self.retrieval.pnps.mask(
self._plot_param
)
return pulse
def plot_time_domain_retrieval(
self,
fig: Optional[plt.Figure] = None,
yaxis: plotting.PlotYAxis = plotting.PlotYAxis.intensity,
limit: bool = True,
oversampling: int = 8,
phase_blanking: bool = True,
phase_blanking_threshold: float = 1e-3,
) -> Tuple[plt.Figure, plt.Axes, plt.Axes]:
"""
Plot the retrieval result in the time domain.
Parameters
----------
fig : plt.Figure or None, optional
An optional figure to use for the plot.
yaxis : plotting.PlotYAxis, optional
The Y axis setting.
limit : bool, optional
Determine and apply a limit using pypret.
oversampling : int, optional
Oversampling count
phase_blanking : bool, optional
Enable phase blanking with pypret masking.
phase_blanking_threshold : float, optional
Phase blanking threshold.
Returns
-------
plt.Figure
The figure used.
plt.Axes
The left axis.
plt.Axes
The right axis.
"""
assert self.plot is not None
assert self.retrieval is not None
# construct the figure
if fig is None:
fig = cast(plt.Figure, plt.figure())
ax1 = cast(plt.Axes, fig.subplots(nrows=1, ncols=1))
ax12 = cast(plt.Axes, ax1.twinx())
pulse = self._get_retrieval_pulse()
if oversampling:
t = np.linspace(pulse.t[0], pulse.t[-1], pulse.N * oversampling)
field2 = pulse.field_at(t).copy()
else:
t = pulse.t.copy()
field2 = pulse.field.copy()
field2 /= np.abs(field2).max()
result_parameter_mid_idx = np.floor(len(field2) / 2) + 1
profile_max_idx = np.abs(field2).argmax()
field3 = np.roll(field2, -round(profile_max_idx - result_parameter_mid_idx))
li11, li12, _, _ = pypret.graphics.plot_complex(
t,
field3,
ax1,
ax12,
yaxis=yaxis.value,
phase_blanking=phase_blanking,
limit=limit,
phase_blanking_threshold=phase_blanking_threshold,
)
li11.set_linewidth(3.0)
li11.set_color("#1f77b4")
li11.set_alpha(0.6)
li12.set_linewidth(3.0)
li12.set_color("#ff7f0e")
li12.set_alpha(0.6)
fwhm = np.round(pulse.fwhm(dt=pulse.dt / 100) / 1e-15, 2)
fx = EngFormatter(unit="s")
ax1.xaxis.set_major_formatter(fx)
plot_position_mm = self._final_plot_position * 1e3
ax1.set_title(f"time domain @ {plot_position_mm:.3f} mm (FWHM = {fwhm} fs)")
ax1.set_xlabel("time")
ax1.set_ylabel(yaxis.value)
ax12.set_ylabel("phase (rad)")
ax1.legend([li11, li12], [yaxis.value, "phase"])
ax1.set_xlim([-10 * 1e-15 * np.round(fwhm, 0), 10 * 1e-15 * np.round(fwhm, 0)])
return fig, ax1, ax12
def plot_frequency_domain_retrieval(
self,
fig: Optional[plt.Figure] = None,
xaxis: plotting.PlotXAxis = plotting.PlotXAxis.wavelength,
yaxis: plotting.PlotYAxis = plotting.PlotYAxis.intensity,
limit: bool = True,
oversampling: int = 8,
phase_blanking: bool = True,
phase_blanking_threshold: float = 1e-3,
) -> Tuple[plt.Figure, plt.Axes, plt.Axes]:
"""
Plot the retrieval result in the time domain.
Parameters
----------
fig : plt.Figure or None, optional
An optional figure to use for the plot.
xaxis : plotting.PlotXAxis, optional
The X axis setting.
yaxis : plotting.PlotYAxis, optional
The Y axis setting.
limit : bool, optional
Determine and apply a limit using pypret.
oversampling : int, optional
Oversampling count
phase_blanking : bool, optional
Enable phase blanking with pypret masking.
phase_blanking_threshold : float, optional
Phase blanking threshold.
Returns
-------
Tuple[plt.Figure, plt.Axes, plt.Axes]
"""
assert self.plot is not None
assert self.retrieval is not None
# construct the figure
if fig is None:
fig = cast(plt.Figure, plt.figure())
ax2 = cast(plt.Axes, fig.subplots(nrows=1, ncols=1))
ax22 = cast(plt.Axes, ax2.twinx())
pulse = self._get_retrieval_pulse()
if oversampling:
w = np.linspace(pulse.w[0], pulse.w[-1], pulse.N * oversampling)
spectrum2 = pulse.spectrum_at(w).copy()
pulse.spectrum = self.retrieval.pulse_retrieved.copy()
else:
w = pulse.w.copy()
spectrum2 = self.retrieval.pulse_retrieved.copy()
fund_w = (
pypret.frequencies.convert(self.fund.wavelengths, "wl", "om") - pulse.w0
)
spectrum2 /= np.abs(spectrum2).max()
if self.fund is None:
fundamental = None
else:
fundamental = self.get_fund_intensities_bkg_sub(
use_pulse_spectral_intensity=True
)
fundamental /= np.abs(fundamental).max()
if xaxis == plotting.PlotXAxis.wavelength:
w = pypret.frequencies.convert(w + pulse.w0, "om", "wl")
fund_w = self.fund.wavelengths
unit = "m"
label = "wavelength"
elif xaxis == plotting.PlotXAxis.frequency:
unit = " rad Hz"
label = "frequency"
else:
raise ValueError(f"Unsupported x-axis for plotting: {xaxis}")
# Plot in spectral domain
li21, li22, _, _ = plotting.plot_complex_phase(
w,
spectrum2,
ax2,
ax22,
yaxis=yaxis.value,
phase_blanking=phase_blanking,
limit=limit,
phase_blanking_threshold=phase_blanking_threshold,
)
lines = [li21, li22]
labels = ["intensity", "phase"]
if fundamental is not None:
(li31,) = ax2.plot(fund_w, fundamental, "r", ms=4.0, mew=1.0, zorder=0)
lines.append(cast(plt.Line2D, li31))
labels.append("measurement")
li21.set_linewidth(3.0)
li21.set_color("#1f77b4")
li21.set_alpha(0.6)
li22.set_linewidth(3.0)
li22.set_color("#ff7f0e")
li22.set_alpha(0.6)
fx = EngFormatter(unit=unit)
ax2.xaxis.set_major_formatter(fx)
ftl = self.fourier_transform_limit * 1e15