-
Notifications
You must be signed in to change notification settings - Fork 4
/
vmp_analysis.py
1191 lines (1020 loc) · 53.9 KB
/
vmp_analysis.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module is meant for analysis of Meep Plasmonics field results.
@author: Vall
"""
import numpy as np
from scipy.signal import find_peaks
#%% GENERAL: INDEX FUNCTION
def def_index_function(array):
"""
Generates a function to get the index of the closest value inside an array.
Parameters
----------
array : np.array
Input data.
Returns
-------
index_function : function
A function of only one argument `value` that searches for a value
inside the input array and returns the closest index.
"""
if not isinstance(array, np.ndarray):
raise Warning("The input data should be inside a np.ndarray instance")
def index_function(value):
return np.argmin(np.abs(np.asarray(array) - value))
return index_function
#%% FIELD ANALYSIS: CROP FIELD FUNCTIONS
def crop_single_field_yzplane(single_yzplane, y_plane_index, z_plane_index,
cell_width, pml_width):
"""Croppes a single YZ plane field array, dropping the outsides of the cell.
Parameters
----------
single_yzplane : np.array with dimension 2
Bidimensional field array of shape (N,M) where N stands for positions
in the Y axis and M stands for positions in the Z axis.
y_plane_index : function
Function of a single argument that takes in an Y position and returns
the index of the closest value.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
Returns
-------
cropped : np.array
Bidimensional field cropped array of shape (n,m) where n<N stands for
positions in the Y axis and m<M stands for positions in the Z axis.
"""
cropped = single_yzplane[: y_plane_index(cell_width/2 - pml_width) + 1, :]
cropped = cropped[y_plane_index(-cell_width/2 + pml_width) :, :]
cropped = cropped[:,: z_plane_index(cell_width/2 - pml_width) + 1]
cropped = cropped[:, z_plane_index(-cell_width/2 + pml_width) :]
return cropped
def crop_single_field_zprofile(single_zprofile, z_plane_index,
cell_width, pml_width):
"""Croppes a single Z line field array, dropping the outsides of the cell.
Parameters
----------
single_zprofile : np.array with dimension 1
One-dimensional field array of shape (N,) where n stands for positions
in the Z axis.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
Returns
-------
cropped : np.array
One-dimensional field cropped array of shape (n,) where n<N stands for
positions in the Z axis.
"""
cropped = single_zprofile[: z_plane_index(cell_width/2 - pml_width) + 1]
cropped = cropped[z_plane_index(-cell_width/2 + pml_width) :]
return cropped
def crop_single_field_xprofile(single_xprofile, x_line_index,
cell_width, pml_width):
"""Croppes a single Z line field array, dropping the outsides of the cell.
Parameters
----------
single_xprofile : np.array with dimension 1
One-dimensional field array of shape (N,) where n stands for positions
in the X axis.
x_line_index : function
Function of a single argument that takes in an X position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
Returns
-------
cropped : np.array
One-dimensional field cropped array of shape (n,) where n<N stands for
positions in the X axis.
"""
return crop_single_field_zprofile(single_xprofile, x_line_index,
cell_width, pml_width)
def crop_field_yzplane(yzplane_field, y_plane_index, z_plane_index,
cell_width, pml_width):
"""Croppes full YZ planes field array, dropping the outsides of the cell.
Parameters
----------
yzplane_field : np.array with dimension 3
Three-dimensional field array of shape (N,M,K) where N stands for
positions in the Y axis, M stands for positions in the Z axis and K
stands for different time instants.
y_plane_index : function
Function of a single argument that takes in an Y position and returns
the index of the closest value.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
Returns
-------
cropped : np.array
Three-dimensional field array of shape (n,m,K) where n<N stands for
positions in the Y axis, m<M stands for positions in the Z axis and K
stands for different instants of time.
"""
cropped = yzplane_field[: y_plane_index(cell_width/2 - pml_width) + 1, ...]
cropped = cropped[y_plane_index(-cell_width/2 + pml_width) :, ...]
cropped = cropped[:,: z_plane_index(cell_width/2 - pml_width) + 1, ...]
cropped = cropped[:, z_plane_index(-cell_width/2 + pml_width) :, ...]
return cropped
def crop_field_zprofile(zprofile_field, z_plane_index,
cell_width, pml_width):
"""Croppes full Z lines field array, dropping the outsides of the cell.
Parameters
----------
zprofile_field : np.array with dimension 2
Bidimensional field array of shape (N,K) where N stands for positions
in the Z axis and K stands for different time instants.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
Returns
-------
cropped : np.array
Bidimensional field cropped array of shape (n,K) where n<N stands for
positions in the Z axis and K stands for different time instants.
"""
cropped = zprofile_field[: z_plane_index(cell_width/2 - pml_width) + 1, :]
cropped = cropped[z_plane_index(-cell_width/2 + pml_width) :, :]
return cropped
def crop_field_xprofile(xprofile_field, x_line_index,
cell_width, pml_width):
"""Croppes full X lines field array, dropping the outsides of the cell.
Parameters
----------
xprofile_field : np.array with dimension 2
Bidimensional field array of shape (N,K) where N stands for positions
in the X axis and K stands for different time instants.
x_plane_index : function
Function of a single argument that takes in an X position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
Returns
-------
cropped : np.array
Bidimensional field cropped array of shape (n,K) where n<N stands for
positions in the X axis and K stands for different time instants.
"""
return crop_field_zprofile(xprofile_field, x_line_index,
cell_width, pml_width)
#%% FIELD ANALYSIS: SOURCE FROM X LINE FIELD
def get_source_from_line(xline_field, x_line_index,
source_center):
"""Extracts data corresponding to source position from X lines field array.
Parameters
----------
xline_field : np.array with dimension 2
Bidimensional field array of shape (L,K) where L stands for positions
in the X axis and K stands for different time instants.
x_line_index : function
Function of a single argument that takes in an X position and returns
the index of the closest value.
source_center : int, float
YZ wave front planewidth source's X position, generally expressed in
Meep units to be in the same units as the `y_plane` metadata array.
Returns
-------
np.array
One-dimensional field array of shape (K) where K stands for different
time instants.
"""
return np.asarray(xline_field[x_line_index(source_center), :])
def get_peaks_from_source(source_field,
peaks_sep_sensitivity=0.1,
last_stable_periods=5):
"""Finds maximum peaks of a periodic oscillating signal as the source field.
Parameters
----------
source_field : np.array of dimension 1
One-dimensional array of a periodic oscillating signal. Generally,
field array of shape (K) where K stands for different time instants.
peaks_sep_sensitivity=0.1 : float between zero and one, optional
A factor representing the allowed variation percentage in consecutive
peaks separation. Any deviated value will be dropped. If None is
provided, no value will be discarded.
last_stable_periods=5 : int, optional
Number of periods to take as reference of the stable signal, extracted
from the end as the signal is assumed to have both a transcient and a
stationary regimen. If None is provided, all of the signal is taken as
reference.
Returns
-------
selected_peaks : list
List of int index for the maximum peaks found inside the input array.
"""
if not isinstance(source_field, np.ndarray):
source_field = np.array(source_field)
# peaks = find_peaks(source_field, height=0)[0]
if np.sign(np.min(source_field)) == np.sign(np.max(source_field)):
max_peaks = find_peaks(source_field)[0]
min_peaks = find_peaks(-source_field)[0]
peaks = [*min_peaks, *max_peaks]
peaks.sort()
else:
peaks = find_peaks(np.abs(source_field),
height=np.max(np.abs(source_field))/2)[0]
# All peaks, no only maximums, but minimums too
if peaks_sep_sensitivity is not None:
# Take the last periods as reference and define periodicity criteria
if last_stable_periods is not None:
mean_diff = np.mean(np.diff(peaks[-2*last_stable_periods:]))
else: mean_diff = np.mean(np.diff(peaks))
def selection_criteria(k):
eval_point = np.abs( mean_diff - (peaks[k+1] - peaks[k]) )
return eval_point <= peaks_sep_sensitivity * mean_diff
# Filter peaks to make sure they are periodic; i.e. they have equispaced index
selected_peaks = []
for k in range(len(peaks)):
if k == 0 and selection_criteria(k):
selected_peaks.append(peaks[k])
elif k == len(peaks)-1 and selection_criteria(k-1):
selected_peaks.append(peaks[k])
elif selection_criteria(k):
selected_peaks.append(peaks[k])
else: selected_peaks = peaks
if np.sign(np.min(source_field)) != np.sign(np.max(source_field)):
# Check if there's always a single maximum and a single minimum per period
# If not, try to fix it or raise Warning.
selected_sign = np.sign(source_field[selected_peaks])
if np.min(np.abs(np.diff( selected_sign ))) != 2:
error_index = np.argmin(np.abs(np.diff( selected_sign )))
missing_index_lower_bound = selected_peaks[ error_index ]
missing_index_upper_bound = selected_peaks[ error_index + 1 ]
if missing_index_upper_bound - missing_index_lower_bound == 2:
selected_peaks = [*selected_peaks[: error_index + 1],
missing_index_lower_bound + 1,
*selected_peaks[error_index + 1 :]]
selected_sign = np.sign(source_field[selected_peaks])
if np.min(np.abs(np.diff( selected_sign ))) != 2:
print("Warning! Sign algorithm failed and it couldn't be fixed!")
else:
print("Warning! Sign algorithm must have failed!")
else:
k = 0
selected_min, selected_max = [], []
for p in selected_peaks:
if p in min_peaks: selected_min.append(p); k+=1
else: selected_max.append(p); k-=1
if abs(k)>=2: print("Warning! Sign algorithm must have failed!"); break
return selected_peaks
def get_period_from_source(source_field, t_line=None,
peaks_sep_sensitivity=0.1,
periods_sensitivity=0.05,
last_stable_periods=5):
"""Finds period of a periodic oscillating signal as the source field.
Parameters
----------
source_field : np.array of dimension 1
One-dimensional array of a periodic oscillating signal. Generally,
field array of shape (K) where K stands for different time instants.
t_line=None : np.array of dimension 1, optional
One-dimensional array of periodic oscillating signal's independent
variable. Generally, time array of shape (K) where K stands for
different time instants. If None is given, a default integer index
number array is created.
peaks_sep_sensitivity=0.1 : float between zero and one, optional
A factor representing the allowed variation percentage in consecutive
peaks separation. Any deviated value will be dropped. If None is
provided, no value will be discarded.
periods_sensitivity=0.05 : float between zero and one, optional
A factor representing the allowed variation percentage in the period
of selected peaks. All values prior to a certain point will be dropped,
keeping only the last values identified to be stable.
last_stable_periods=5 : int, optional
Number of periods to take as reference of the stable signal, extracted
from the end as the signal is assumed to have both a transcient and a
stationary regimen. If None is provided, all of the signal is taken as
reference.
Returns
-------
considered_peaks : list
List of index k<K considered to calculate the mean period.
amplitude : float
Mean period of the signal, taking into account only those peaks
identified to be stable.
"""
if not isinstance(source_field, np.ndarray):
source_field = np.array(source_field)
if t_line is None:
t_line = np.arange(len(source_field))
peaks = get_peaks_from_source(source_field,
peaks_sep_sensitivity=peaks_sep_sensitivity,
last_stable_periods=last_stable_periods)
semiperiods = np.array(t_line[peaks[1:]] - t_line[peaks[:-1]])
if periods_sensitivity is not None:
# Take the last periods as reference and define stability criteria
if last_stable_periods is not None:
mean_semiperiods = np.mean(semiperiods[-2*last_stable_periods:])
else: mean_semiperiods = np.mean(semiperiods)
def selection_criteria(k):
eval_point = np.abs(semiperiods[k] - mean_semiperiods)
return eval_point <= periods_sensitivity * mean_semiperiods
# Choose only the latter stable periods to compute period
keep_periods_from = 0
for k in range(len(semiperiods)):
if not selection_criteria(k):
keep_periods_from = max(keep_periods_from, k+1)
stable_semiperiods = semiperiods[keep_periods_from:]
period = 2*np.mean(stable_semiperiods)
considered_peaks = peaks[keep_periods_from:]
else:
period = 2*np.mean(semiperiods)
considered_peaks = peaks
return considered_peaks, period
def get_amplitude_from_source(source_field,
peaks_sep_sensitivity=0.1,
amplitude_sensitivity=0.05,
last_stable_periods=5):
"""Finds amplitude of a periodic oscillating signal as the source field.
Parameters
----------
source_field : np.array of dimension 1
One-dimensional array of a periodic oscillating signal. Generally,
field array of shape (K) where K stands for different time instants.
peaks_sep_sensitivity=0.1 : float between zero and one, optional
A factor representing the allowed variation percentage in consecutive
peaks separation. Any deviated value will be dropped.
amplitude_sensitivity=0.05 : float between zero and one, optional
A factor representing the allowed variation percentage in the amplitude
of selected peaks. All values prior to a certain point will be dropped,
keeping only the last values identified to be stable. If None is
provided, no value will be discarded.
last_stable_periods=5 : int, optional
Number of periods to take as reference of the stable signal, extracted
from the end as the signal is assumed to have both a transcient and a
stationary regimen. If None is provided, all of the signal is taken as
reference.
Returns
-------
considered_peaks : list
List of index k<K considered to calculate the mean amplitude.
amplitude : float
Mean amplitude of the signal, taking into account only those peaks
identified to be stable.
"""
if not isinstance(source_field, np.ndarray):
source_field = np.array(source_field)
peaks = get_peaks_from_source(source_field,
peaks_sep_sensitivity=peaks_sep_sensitivity,
last_stable_periods=last_stable_periods)
if np.sign(np.min(source_field[peaks])) != np.sign(np.max(source_field[peaks])):
heights = np.abs(source_field[peaks])
else:
heights = np.abs( np.diff(source_field[peaks]) ) / 2
if amplitude_sensitivity is not None:
# Take the last periods as reference and define stability criteria
if last_stable_periods is not None:
mean_height = np.mean(heights[-2*last_stable_periods:])
else: mean_height = np.mean(heights)
def selection_criteria(k):
eval_point = np.abs(heights[k] - mean_height)
return eval_point <= amplitude_sensitivity * mean_height
# Choose only the latter stable periods to compute amplitude
amp_keep_periods_from = 0
for k in range(len(heights)):
if not selection_criteria(k):
amp_keep_periods_from = max(amp_keep_periods_from, k+1)
if np.sign(np.min(source_field[peaks])) != np.sign(np.max(source_field[peaks])):
stable_heights = np.abs(source_field[peaks[amp_keep_periods_from:]])
else:
stable_heights = np.abs( np.diff(source_field[peaks[amp_keep_periods_from:]]) ) / 2
considered_peaks = peaks[amp_keep_periods_from:]
amplitude = np.mean(stable_heights)
else:
considered_peaks = peaks
amplitude = np.mean(heights)
return considered_peaks, amplitude
#%% FIELD ANALYSIS: ZPROFILE FROM YZ PLANE
def get_background_from_plane(yzplane_field, y_plane_index, z_plane_index,
cell_width, pml_width):
"""Extracts data corresponding to background field from YZ planes field array.
Parameters
----------
yzplane_field : np.array with dimension 3
Three-dimensional field array of shape (N,M,K) where N stands for
positions in the Y axis, M stands for positions in the Z axis and K
stands for different time instants.
y_plane_index : function
Function of a single argument that takes in an Y position and returns
the index of the closest value.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
Returns
-------
np.array
One-dimensional field array of shape (K,) where K stands for different
time instants.
"""
y0_wall = np.mean(yzplane_field[y_plane_index(-cell_width/2 + pml_width),
z_plane_index(-cell_width/2 + pml_width):z_plane_index(cell_width/2 - pml_width),
:], axis=0)
y1_wall = np.mean(yzplane_field[y_plane_index(cell_width/2 - pml_width),
z_plane_index(-cell_width/2 + pml_width):z_plane_index(cell_width/2 - pml_width),
:], axis=0)
z0_wall = np.mean(yzplane_field[y_plane_index(-cell_width/2 + pml_width):y_plane_index(cell_width/2 - pml_width),
z_plane_index(-cell_width/2 + pml_width),
:], axis=0)
z1_wall = np.mean(yzplane_field[y_plane_index(-cell_width/2 + pml_width):y_plane_index(cell_width/2 - pml_width),
z_plane_index(cell_width/2 - pml_width),
:], axis=0)
return np.mean(np.array([y0_wall,y1_wall,z0_wall, z1_wall]), axis=0)
def get_zprofile_from_plane(yzplane_field, y_plane_index):
"""Extracts data corresponding to Z axis from YZ planes field array.
Parameters
----------
yzplane_field : np.array with dimension 3
Three-dimensional field array of shape (N,M,K) where N stands for
positions in the Y axis, M stands for positions in the Z axis and K
stands for different time instants.
y_plane_index : function
Function of a single argument that takes in an Y position and returns
the index of the closest value.
Returns
-------
np.array
Bidimensional field array of shape (M,K) where M stands for
positions in the Z axis and K stands for different time instants.
"""
return np.asarray(yzplane_field[y_plane_index(0), :, :])
def z_integrate_field_zprofile(zprofile_field, z_plane, z_plane_index,
cell_width, pml_width):
"""Crops and integrates in Z on Z profile fields from Z lines field array.
Parameters
----------
zprofile_field : np.array with dimension 2
Bidimensional field array of shape (N,K) where N stands for positions
in the Z axis and K stands for different time instants.
z_plane : np.array with dimension 1
One-dimensional position array of shape (N) where N stands for
positions in the Z axis.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
period_plane : float
Sampling period of the data, generally expressed in Meep units to be
in the correct units to be input of `mp.at_every` step functions.
Returns
-------
integral : np.array with dimension 1
One-dimensional array of shape (K,) where K stands for different time
instants.
"""
integral = np.sum(
crop_field_zprofile(zprofile_field, z_plane_index,
cell_width, pml_width),
axis=0) * np.mean(np.diff(z_plane))
return integral
def detect_sign_field_zprofile(zprofile_field):
"""Detects sign of Z profile fields from Z lines field array.
Parameters
----------
zprofile_field : np.array with dimension at least 1
Field array of shape (...,K) where K stands for different time instants.
Returns
-------
np.array
Sign array of shape (...,K) where K stands for different time instants.
"""
return -np.sign(zprofile_field[0,...])
def find_zpeaks_zprofile(zprofile_field, z_plane_index,
cell_width, pml_width):
"""Finds peaks in Z axis for a Z lines field array.
Parameters
----------
zprofile_field : np.array with dimension 2
Bidimensional field array of shape (N,K) where N stands for positions
in the Z axis and K stands for different time instants.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
Returns
-------
abs_max_z_index : tuple of int
Pair of index n1,n2<N identified to extract all data corresponding to
the maximum values of field at both sides of the Z axis.
max_z_values : np.array with dimension 1
One-dimensional array of shape (K,) where K stands for different time
instants.
"""
cropped_zprofile = crop_single_field_zprofile(zprofile_field, z_plane_index,
cell_width, pml_width)
# Get the central z index
mid_index = int(cropped_zprofile.shape[0]/2)
# Find the position of the absolute maximum on the left side
abs_max_index_left = np.argmax(np.abs(cropped_zprofile[:mid_index,...]))
abs_max_z_index_left = np.unravel_index(abs_max_index_left,
cropped_zprofile[:mid_index,...].shape)[0]
# Find the position of the absolute maximum on the right side
abs_max_index_right = np.argmax(np.abs(cropped_zprofile[mid_index:,...]))
abs_max_z_index_right = np.unravel_index(abs_max_index_right,
cropped_zprofile[mid_index:,...].shape)[0]
abs_max_z_index_right = mid_index + abs_max_z_index_right
# Take its position in Z axis as reference and get all values of the field
max_z_values_left = cropped_zprofile[abs_max_z_index_left, ...]
max_z_values_right = cropped_zprofile[abs_max_z_index_right, ...]
max_z_values = np.mean(np.array([max_z_values_left,max_z_values_right]), axis=0)
abs_max_z_index = (abs_max_z_index_left, abs_max_z_index_right)
return abs_max_z_index, max_z_values
def get_phase_field_peak_background(zprofmax_field, background_field,
peaks_sep_sensitivity=0.1,
periods_sensitivity=0.05,
last_stable_periods=5):
"""Calculates relative phase between field in peaks Z location and background.
Parameters
----------
zprofmax_field : np.array with dimension 1
One-dimensional oscillating signal. Generally, field array,
corresponding to Z peak location, of shape (K,) where K stands for
different time instants.
background_field : np.array with dimension 1
One-dimensional reference oscillating signal, of the same period.
Generally, background field array of shape (K,) where K stands for
different time instants.
peaks_sep_sensitivity=0.1 : float between zero and one, optional
A factor representing the allowed variation percentage in consecutive
peaks separation. Any deviated value will be dropped.
periods_sensitivity=0.05 : float between zero and one, optional
A factor representing the allowed variation percentage in the period
of selected peaks. All values prior to a certain point will be dropped,
keeping only the last values identified to be stable.
last_stable_periods=5 : int, optional
Number of periods to take as reference of the stable signal, extracted
from the end as the signal is assumed to have both a transcient and a
stationary regimen.
Returns
-------
delta_phase : float
Relative phase between field in peaks Z location and background field,
expressed in multiples of pi radians.
"""
back_index = get_peaks_from_source(background_field,
peaks_sep_sensitivity=peaks_sep_sensitivity,
last_stable_periods=last_stable_periods)
zprof_index = get_peaks_from_source(zprofmax_field,
peaks_sep_sensitivity=peaks_sep_sensitivity,
last_stable_periods=last_stable_periods)
back_iperiod = get_period_from_source(background_field,
peaks_sep_sensitivity=peaks_sep_sensitivity,
periods_sensitivity=periods_sensitivity,
last_stable_periods=last_stable_periods)[-1]
zprof_iperiod = get_period_from_source(zprofmax_field,
peaks_sep_sensitivity=peaks_sep_sensitivity,
periods_sensitivity=periods_sensitivity,
last_stable_periods=last_stable_periods)[-1]
if zprofmax_field[ zprof_index[0] ]>0:
zprof_imaxs = np.array( zprof_index[::2] )
zprof_imins = np.array( zprof_index[1::2] )
else:
zprof_imins = np.array( zprof_index[::2] )
zprof_imaxs = np.array( zprof_index[1::2] )
if background_field[ back_index[0]] >0:
back_imaxs = np.array( back_index[::2] )
back_imins = np.array( back_index[1::2] )
else:
back_imins = np.array( back_index[::2] )
back_imaxs = np.array( back_index[1::2] )
min_number = np.min([len(zprof_imaxs), len(zprof_imins),
len(back_imaxs), len(back_imins)])
zprof_imaxs, zprof_imins = zprof_imaxs[-min_number:], zprof_imins[-min_number:]
back_imaxs, back_imins = back_imaxs[-min_number:], back_imins[-min_number:]
choose_which = np.argmin([np.mean(np.abs(zprof_imins - back_imins)),
np.mean(np.abs(zprof_imaxs - back_imaxs)),
np.mean(np.abs(zprof_imins - back_imaxs)),
np.mean(np.abs(zprof_imaxs - back_imins))])
if choose_which < 2:
choose_again = np.argmin([ np.mean(np.abs(zprof_imins - back_imins)),
np.mean(np.abs(zprof_imins[1:] - back_imins[:-1])) ])
data_1 = [ zprof_imins - back_imins,
zprof_imins[1:] - back_imins[:-1] ][choose_again]
choose_again = np.argmin([ np.mean(np.abs(zprof_imaxs - back_imaxs)),
np.mean(np.abs(zprof_imaxs[1:] - back_imaxs[:-1])) ])
data_2 = [ zprof_imaxs - back_imaxs,
zprof_imaxs[1:] - back_imaxs[:-1] ][choose_again]
delta_i = np.mean([ *data_1, *data_2 ])
else:
choose_again = np.argmin([ np.mean(np.abs(zprof_imins - back_imaxs)),
np.mean(np.abs(zprof_imins[1:] - back_imaxs[:-1])) ])
data_1 = [ zprof_imins - back_imins,
zprof_imins[1:] - back_imins[:-1] ][choose_again]
choose_again = np.argmin([ np.mean(np.abs(zprof_imaxs - back_imins)),
np.mean(np.abs(zprof_imaxs[1:] - back_imins[:-1])) ])
data_2 = [ zprof_imaxs - back_imaxs,
zprof_imaxs[1:] - back_imaxs[:-1] ][choose_again]
delta_i = np.mean([ *data_1, *data_2 ])
if delta_i > 0: delta_i = delta_i + 1
else: delta_i = delta_i - 1
delta_phase = 2 * delta_i / np.mean([back_iperiod, zprof_iperiod]) # in multiples of pi radians
return delta_phase
#%% FIELD ANALYSIS: AVERAGE IN TIME
def t_average_intensity_yzplane(yzplane_field, zprofmax_field, t_plane,
y_plane_index, z_plane_index,
cell_width, pml_width,
peaks_sep_sensitivity=0.1,
amplitude_sensitivity=0.05,
last_stable_periods=5):
"""Average intensity in T on cropped YZ planes field array.
Parameters
----------
yzplane_field : np.array with dimension 3
Three-dimensional field array of shape (N,M,K) where N stands for
positions in the Y axis, M stands for positions in the Z axis and K
stands for different time instants.
zprofmax_field : np.array with dimension 1
One-dimensional oscillating signal. Generally, field array,
corresponding to Z peak location, of shape (K,) where K stands for
different time instants.
t_plane : np.array of dimension 1, optional
One-dimensional time array of shape (K) where K stands for
different time instants.
y_plane_index : function
Function of a single argument that takes in an Y position and returns
the index of the closest value.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
peaks_sep_sensitivity=0.1 : float between zero and one, optional
A factor representing the allowed variation percentage in consecutive
peaks separation. Any deviated value will be dropped.
amplitude_sensitivity=0.05 : float between zero and one, optional
A factor representing the allowed variation percentage in the amplitude
of selected peaks. All values prior to a certain point will be dropped,
keeping only the last values identified to be stable.
last_stable_periods=5 : int, optional
Number of periods to take as reference of the stable signal, extracted
from the end as the signal is assumed to have both a transcient and a
stationary regimen.
Returns
-------
intensity : np.array with dimension 2
Bidimensional array of shape (N,M) where N stands for
positions in the Y axis and M stands for positions in the Z axis
"""
# Get peaks that belong to the stationary
stable_peaks_index = get_amplitude_from_source(zprofmax_field,
peaks_sep_sensitivity=peaks_sep_sensitivity,
amplitude_sensitivity=amplitude_sensitivity,
last_stable_periods=last_stable_periods)[0]
# Keep only an even number of semi-periods
if np.sign(zprofmax_field[stable_peaks_index[0]]) == np.sign(zprofmax_field[stable_peaks_index[-1]]):
stable_peaks_index = stable_peaks_index[1:]
intensity = np.sum(
crop_field_yzplane(np.power(yzplane_field[...,stable_peaks_index[0]:stable_peaks_index[-1]], 2),
y_plane_index, z_plane_index, cell_width, pml_width),
axis=-1)
intensity = intensity * np.mean(np.diff(t_plane[stable_peaks_index[0]:stable_peaks_index[-1]]))
intensity = intensity / ( t_plane[stable_peaks_index[-1]]-t_plane[stable_peaks_index[0]] )
# Should multiply by time differential and divide by the period and the number of periods taken into account
# But I'm doing an average in time directly, to take a straight path
return intensity
def t_average_intensity_zprofile(zprofile_field, zprofmax_field,
t_plane, z_plane_index,
cell_width, pml_width,
peaks_sep_sensitivity=0.1,
amplitude_sensitivity=0.05,
last_stable_periods=5):
"""Average intensity in T on cropped Z profile fields from Z lines field array.
Parameters
----------
zprofile_field : np.array with dimension 2
Bidimensional field array of shape (N,K) where N stands for positions
in the Z axis and K stands for different time instants.
t_plane : np.array of dimension 1, optional
One-dimensional time array of shape (K) where K stands for
different time instants.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
peaks_sep_sensitivity=0.1 : float between zero and one, optional
A factor representing the allowed variation percentage in consecutive
peaks separation. Any deviated value will be dropped.
amplitude_sensitivity=0.05 : float between zero and one, optional
A factor representing the allowed variation percentage in the amplitude
of selected peaks. All values prior to a certain point will be dropped,
keeping only the last values identified to be stable.
last_stable_periods=5 : int, optional
Number of periods to take as reference of the stable signal, extracted
from the end as the signal is assumed to have both a transcient and a
stationary regimen.
Returns
-------
intensity : np.array with dimension 1
One-dimensional array of shape (N,) where N stands for different
positions in the Z axis.
"""
# Get peaks that belong to the stationary
stable_peaks_index = get_amplitude_from_source(zprofmax_field,
peaks_sep_sensitivity=peaks_sep_sensitivity,
amplitude_sensitivity=amplitude_sensitivity,
last_stable_periods=last_stable_periods)[0]
# Keep only an even number of semi-periods
if np.sign(zprofmax_field[stable_peaks_index[0]]) == np.sign(zprofmax_field[stable_peaks_index[-1]]):
stable_peaks_index = stable_peaks_index[1:]
intensity = np.sum(
crop_field_zprofile(np.power(zprofile_field[...,stable_peaks_index[0]:stable_peaks_index[-1]], 2),
z_plane_index, cell_width, pml_width),
axis=-1)
intensity = intensity * np.mean(np.diff(t_plane[stable_peaks_index[0]:stable_peaks_index[-1]]))
intensity = intensity / ( t_plane[stable_peaks_index[-1]]-t_plane[stable_peaks_index[0]] )
# Should multiply by time differential and divide by the period and the number of periods taken into account
# But I'm doing an average in time directly, to take a straight path
return intensity
#%% FIELD ANALYSIS: RESONANCE FROM ZPROFILE
def get_all_field_peaks_from_yzplanes(yzplane_field,
y_plane_index, z_plane_index,
cell_width, pml_width,
peaks_sep_sensitivity=0.05,
last_stable_periods=5):
"""Gets all maximum intensification field from a YZ planes field array.
Parameters
----------
yzplane_field : np.array with dimension 3
Three-dimensional field array of shape (N,M,K) where N stands for
positions in the Y axis, M stands for positions in the Z axis and K
stands for different time instants.
y_plane_index : function
Function of a single argument that takes in an Y position and returns
the index of the closest value.
z_plane_index : function
Function of a single argument that takes in an Z position and returns
the index of the closest value.
cell_width : int, float
Cubic cell side's total length, generally expressed in Meep units to
be in the same units as the `y_plane` metadata array.
pml_width : int, float
Cell's isotropic PML's width, generally expressed in Meep units to be
in the same units as the `y_plane` metadata array.
peaks_sep_sensitivity=0.1 : float between zero and one, optional
A factor representing the allowed variation percentage in consecutive
peaks separation. Any deviated value will be dropped.
last_stable_periods=5 : int, optional
Number of periods to take as reference of the stable signal, extracted
from the end as the signal is assumed to have both a transcient and a
stationary regimen.
Returns
-------
field_peaks_index : np.array
Maximum intensification index k<K in an array of shape (Kfp,) where
Kfp<K stands for the selected time instants.
field_peaks_amplitudes : np.array
Absolute amplitude of maximum intensification in an array of shape
(Kfp,) where Kfp<K stands for the selected time instants.
field_peaks_zprofile : np.array
Bidimensional cropped field array of shape (n,Kfp) where n<N stands for
positions in the Z axis and Kfp<K stands for the selected time instants.
field_peaks_yzplane : np.array
Three-dimensional cropped field array of shape (n,m,Kfp) where n<N
stands for positions in the Y axis, m<M stands for positions in the
Z axis and Kfp<K stands for the selected time instants.
"""
# zprofile_field has time as the last dimension
zprofile_field = get_zprofile_from_plane(yzplane_field, y_plane_index)
zprofile_maxs = find_zpeaks_zprofile(zprofile_field, z_plane_index,
cell_width, pml_width)[-1]
# Find peaks in time for the maximum intensification field
field_peaks_index = get_peaks_from_source(zprofile_maxs,
peaks_sep_sensitivity=peaks_sep_sensitivity,
last_stable_periods=last_stable_periods)
field_peaks_amplitudes = np.abs(zprofile_maxs[field_peaks_index])
field_peaks_sign = np.sign(zprofile_maxs[field_peaks_index])
field_peaks_zprofile = [crop_single_field_zprofile(zprofile_field[...,k],
z_plane_index,
cell_width, pml_width)
for k in field_peaks_index]
field_peaks_zprofile = field_peaks_sign * np.array(field_peaks_zprofile).T
field_peaks_yzplane = [crop_single_field_yzplane(yzplane_field[...,k],
y_plane_index, z_plane_index,
cell_width, pml_width)
for k in field_peaks_index]